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.6.22.  By combining all the individual C code files into this
      4 ** single large file, the entire code can be compiled as a one 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% are 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 maximum number of attached databases.  This must be between 0
    195 ** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
    196 ** is used internally to track attached databases.
    197 */
    198 #ifndef SQLITE_MAX_ATTACHED
    199 # define SQLITE_MAX_ATTACHED 10
    200 #endif
    201 
    202 
    203 /*
    204 ** The maximum value of a ?nnn wildcard that the parser will accept.
    205 */
    206 #ifndef SQLITE_MAX_VARIABLE_NUMBER
    207 # define SQLITE_MAX_VARIABLE_NUMBER 999
    208 #endif
    209 
    210 /* Maximum page size.  The upper bound on this value is 32768.  This a limit
    211 ** imposed by the necessity of storing the value in a 2-byte unsigned integer
    212 ** and the fact that the page size must be a power of 2.
    213 **
    214 ** If this limit is changed, then the compiled library is technically
    215 ** incompatible with an SQLite library compiled with a different limit. If
    216 ** a process operating on a database with a page-size of 65536 bytes
    217 ** crashes, then an instance of SQLite compiled with the default page-size
    218 ** limit will not be able to rollback the aborted transaction. This could
    219 ** lead to database corruption.
    220 */
    221 #ifndef SQLITE_MAX_PAGE_SIZE
    222 # define SQLITE_MAX_PAGE_SIZE 32768
    223 #endif
    224 
    225 
    226 /*
    227 ** The default size of a database page.
    228 */
    229 #ifndef SQLITE_DEFAULT_PAGE_SIZE
    230 # define SQLITE_DEFAULT_PAGE_SIZE 1024
    231 #endif
    232 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
    233 # undef SQLITE_DEFAULT_PAGE_SIZE
    234 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
    235 #endif
    236 
    237 /*
    238 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
    239 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
    240 ** device characteristics (sector-size and atomic write() support),
    241 ** SQLite may choose a larger value. This constant is the maximum value
    242 ** SQLite will choose on its own.
    243 */
    244 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
    245 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
    246 #endif
    247 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
    248 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
    249 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
    250 #endif
    251 
    252 
    253 /*
    254 ** Maximum number of pages in one database file.
    255 **
    256 ** This is really just the default value for the max_page_count pragma.
    257 ** This value can be lowered (or raised) at run-time using that the
    258 ** max_page_count macro.
    259 */
    260 #ifndef SQLITE_MAX_PAGE_COUNT
    261 # define SQLITE_MAX_PAGE_COUNT 1073741823
    262 #endif
    263 
    264 /*
    265 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
    266 ** operator.
    267 */
    268 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
    269 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
    270 #endif
    271 
    272 /*
    273 ** Maximum depth of recursion for triggers.
    274 **
    275 ** A value of 1 means that a trigger program will not be able to itself
    276 ** fire any triggers. A value of 0 means that no trigger programs at all
    277 ** may be executed.
    278 */
    279 #ifndef SQLITE_MAX_TRIGGER_DEPTH
    280 # define SQLITE_MAX_TRIGGER_DEPTH 1000
    281 #endif
    282 
    283 /************** End of sqliteLimit.h *****************************************/
    284 /************** Continuing where we left off in sqliteInt.h ******************/
    285 
    286 /* Disable nuisance warnings on Borland compilers */
    287 #if defined(__BORLANDC__)
    288 #pragma warn -rch /* unreachable code */
    289 #pragma warn -ccc /* Condition is always true or false */
    290 #pragma warn -aus /* Assigned value is never used */
    291 #pragma warn -csu /* Comparing signed and unsigned */
    292 #pragma warn -spa /* Suspicious pointer arithmetic */
    293 #endif
    294 
    295 /* Needed for various definitions... */
    296 #ifndef _GNU_SOURCE
    297 # define _GNU_SOURCE
    298 #endif
    299 
    300 /*
    301 ** Include standard header files as necessary
    302 */
    303 #ifdef HAVE_STDINT_H
    304 #include <stdint.h>
    305 #endif
    306 #ifdef HAVE_INTTYPES_H
    307 #include <inttypes.h>
    308 #endif
    309 
    310 #define SQLITE_INDEX_SAMPLES 10
    311 
    312 /*
    313 ** This macro is used to "hide" some ugliness in casting an int
    314 ** value to a ptr value under the MSVC 64-bit compiler.   Casting
    315 ** non 64-bit values to ptr types results in a "hard" error with
    316 ** the MSVC 64-bit compiler which this attempts to avoid.
    317 **
    318 ** A simple compiler pragma or casting sequence could not be found
    319 ** to correct this in all situations, so this macro was introduced.
    320 **
    321 ** It could be argued that the intptr_t type could be used in this
    322 ** case, but that type is not available on all compilers, or
    323 ** requires the #include of specific headers which differs between
    324 ** platforms.
    325 **
    326 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
    327 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
    328 ** So we have to define the macros in different ways depending on the
    329 ** compiler.
    330 */
    331 #if defined(__GNUC__)
    332 # if defined(HAVE_STDINT_H)
    333 #   define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
    334 #   define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
    335 # else
    336 #   define SQLITE_INT_TO_PTR(X)  ((void*)(X))
    337 #   define SQLITE_PTR_TO_INT(X)  ((int)(X))
    338 # endif
    339 #else
    340 # define SQLITE_INT_TO_PTR(X)   ((void*)&((char*)0)[X])
    341 # define SQLITE_PTR_TO_INT(X)   ((int)(((char*)X)-(char*)0))
    342 #endif
    343 
    344 
    345 /*
    346 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
    347 ** Older versions of SQLite used an optional THREADSAFE macro.
    348 ** We support that for legacy
    349 */
    350 #if !defined(SQLITE_THREADSAFE)
    351 #if defined(THREADSAFE)
    352 # define SQLITE_THREADSAFE THREADSAFE
    353 #else
    354 # define SQLITE_THREADSAFE 1
    355 #endif
    356 #endif
    357 
    358 /*
    359 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
    360 ** It determines whether or not the features related to
    361 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
    362 ** be overridden at runtime using the sqlite3_config() API.
    363 */
    364 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
    365 # define SQLITE_DEFAULT_MEMSTATUS 1
    366 #endif
    367 
    368 /*
    369 ** Exactly one of the following macros must be defined in order to
    370 ** specify which memory allocation subsystem to use.
    371 **
    372 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
    373 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
    374 **     SQLITE_MEMORY_SIZE            // internal allocator #1
    375 **     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
    376 **     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
    377 **
    378 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
    379 ** the default.
    380 */
    381 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
    382     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
    383     defined(SQLITE_POW2_MEMORY_SIZE)>1
    384 # error "At most one of the following compile-time configuration options\
    385  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
    386  SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
    387 #endif
    388 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
    389     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
    390     defined(SQLITE_POW2_MEMORY_SIZE)==0
    391 # define SQLITE_SYSTEM_MALLOC 1
    392 #endif
    393 
    394 /*
    395 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
    396 ** sizes of memory allocations below this value where possible.
    397 */
    398 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
    399 # define SQLITE_MALLOC_SOFT_LIMIT 1024
    400 #endif
    401 
    402 /*
    403 ** We need to define _XOPEN_SOURCE as follows in order to enable
    404 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
    405 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
    406 ** so it is omitted there.  See ticket #2673.
    407 **
    408 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
    409 ** implemented on some systems.  So we avoid defining it at all
    410 ** if it is already defined or if it is unneeded because we are
    411 ** not doing a threadsafe build.  Ticket #2681.
    412 **
    413 ** See also ticket #2741.
    414 */
    415 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
    416 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
    417 #endif
    418 
    419 /*
    420 ** The TCL headers are only needed when compiling the TCL bindings.
    421 */
    422 #if defined(SQLITE_TCL) || defined(TCLSH)
    423 # include <tcl.h>
    424 #endif
    425 
    426 /*
    427 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
    428 ** Setting NDEBUG makes the code smaller and run faster.  So the following
    429 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
    430 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
    431 ** feature.
    432 */
    433 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
    434 # define NDEBUG 1
    435 #endif
    436 
    437 /*
    438 ** The testcase() macro is used to aid in coverage testing.  When
    439 ** doing coverage testing, the condition inside the argument to
    440 ** testcase() must be evaluated both true and false in order to
    441 ** get full branch coverage.  The testcase() macro is inserted
    442 ** to help ensure adequate test coverage in places where simple
    443 ** condition/decision coverage is inadequate.  For example, testcase()
    444 ** can be used to make sure boundary values are tested.  For
    445 ** bitmask tests, testcase() can be used to make sure each bit
    446 ** is significant and used at least once.  On switch statements
    447 ** where multiple cases go to the same block of code, testcase()
    448 ** can insure that all cases are evaluated.
    449 **
    450 */
    451 #ifdef SQLITE_COVERAGE_TEST
    452 SQLITE_PRIVATE   void sqlite3Coverage(int);
    453 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
    454 #else
    455 # define testcase(X)
    456 #endif
    457 
    458 /*
    459 ** The TESTONLY macro is used to enclose variable declarations or
    460 ** other bits of code that are needed to support the arguments
    461 ** within testcase() and assert() macros.
    462 */
    463 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
    464 # define TESTONLY(X)  X
    465 #else
    466 # define TESTONLY(X)
    467 #endif
    468 
    469 /*
    470 ** Sometimes we need a small amount of code such as a variable initialization
    471 ** to setup for a later assert() statement.  We do not want this code to
    472 ** appear when assert() is disabled.  The following macro is therefore
    473 ** used to contain that setup code.  The "VVA" acronym stands for
    474 ** "Verification, Validation, and Accreditation".  In other words, the
    475 ** code within VVA_ONLY() will only run during verification processes.
    476 */
    477 #ifndef NDEBUG
    478 # define VVA_ONLY(X)  X
    479 #else
    480 # define VVA_ONLY(X)
    481 #endif
    482 
    483 /*
    484 ** The ALWAYS and NEVER macros surround boolean expressions which
    485 ** are intended to always be true or false, respectively.  Such
    486 ** expressions could be omitted from the code completely.  But they
    487 ** are included in a few cases in order to enhance the resilience
    488 ** of SQLite to unexpected behavior - to make the code "self-healing"
    489 ** or "ductile" rather than being "brittle" and crashing at the first
    490 ** hint of unplanned behavior.
    491 **
    492 ** In other words, ALWAYS and NEVER are added for defensive code.
    493 **
    494 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
    495 ** be true and false so that the unreachable code then specify will
    496 ** not be counted as untested code.
    497 */
    498 #if defined(SQLITE_COVERAGE_TEST)
    499 # define ALWAYS(X)      (1)
    500 # define NEVER(X)       (0)
    501 #elif !defined(NDEBUG)
    502 # define ALWAYS(X)      ((X)?1:(assert(0),0))
    503 # define NEVER(X)       ((X)?(assert(0),1):0)
    504 #else
    505 # define ALWAYS(X)      (X)
    506 # define NEVER(X)       (X)
    507 #endif
    508 
    509 /*
    510 ** The macro unlikely() is a hint that surrounds a boolean
    511 ** expression that is usually false.  Macro likely() surrounds
    512 ** a boolean expression that is usually true.  GCC is able to
    513 ** use these hints to generate better code, sometimes.
    514 */
    515 #if defined(__GNUC__) && 0
    516 # define likely(X)    __builtin_expect((X),1)
    517 # define unlikely(X)  __builtin_expect((X),0)
    518 #else
    519 # define likely(X)    !!(X)
    520 # define unlikely(X)  !!(X)
    521 #endif
    522 
    523 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
    524 /************** Begin file sqlite3.h *****************************************/
    525 /*
    526 ** 2001 September 15
    527 **
    528 ** The author disclaims copyright to this source code.  In place of
    529 ** a legal notice, here is a blessing:
    530 **
    531 **    May you do good and not evil.
    532 **    May you find forgiveness for yourself and forgive others.
    533 **    May you share freely, never taking more than you give.
    534 **
    535 *************************************************************************
    536 ** This header file defines the interface that the SQLite library
    537 ** presents to client programs.  If a C-function, structure, datatype,
    538 ** or constant definition does not appear in this file, then it is
    539 ** not a published API of SQLite, is subject to change without
    540 ** notice, and should not be referenced by programs that use SQLite.
    541 **
    542 ** Some of the definitions that are in this file are marked as
    543 ** "experimental".  Experimental interfaces are normally new
    544 ** features recently added to SQLite.  We do not anticipate changes
    545 ** to experimental interfaces but reserve the right to make minor changes
    546 ** if experience from use "in the wild" suggest such changes are prudent.
    547 **
    548 ** The official C-language API documentation for SQLite is derived
    549 ** from comments in this file.  This file is the authoritative source
    550 ** on how SQLite interfaces are suppose to operate.
    551 **
    552 ** The name of this file under configuration management is "sqlite.h.in".
    553 ** The makefile makes some minor changes to this file (such as inserting
    554 ** the version number) and changes its name to "sqlite3.h" as
    555 ** part of the build process.
    556 */
    557 #ifndef _SQLITE3_H_
    558 #define _SQLITE3_H_
    559 #include <stdarg.h>     /* Needed for the definition of va_list */
    560 
    561 /*
    562 ** Make sure we can call this stuff from C++.
    563 */
    564 #if 0
    565 extern "C" {
    566 #endif
    567 
    568 
    569 /*
    570 ** Add the ability to override 'extern'
    571 */
    572 #ifndef SQLITE_EXTERN
    573 # define SQLITE_EXTERN extern
    574 #endif
    575 
    576 #ifndef SQLITE_API
    577 # define SQLITE_API
    578 #endif
    579 
    580 
    581 /*
    582 ** These no-op macros are used in front of interfaces to mark those
    583 ** interfaces as either deprecated or experimental.  New applications
    584 ** should not use deprecated interfaces - they are support for backwards
    585 ** compatibility only.  Application writers should be aware that
    586 ** experimental interfaces are subject to change in point releases.
    587 **
    588 ** These macros used to resolve to various kinds of compiler magic that
    589 ** would generate warning messages when they were used.  But that
    590 ** compiler magic ended up generating such a flurry of bug reports
    591 ** that we have taken it all out and gone back to using simple
    592 ** noop macros.
    593 */
    594 #define SQLITE_DEPRECATED
    595 #define SQLITE_EXPERIMENTAL
    596 
    597 /*
    598 ** Ensure these symbols were not defined by some previous header file.
    599 */
    600 #ifdef SQLITE_VERSION
    601 # undef SQLITE_VERSION
    602 #endif
    603 #ifdef SQLITE_VERSION_NUMBER
    604 # undef SQLITE_VERSION_NUMBER
    605 #endif
    606 
    607 /*
    608 ** CAPI3REF: Compile-Time Library Version Numbers
    609 **
    610 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
    611 ** evaluates to a string literal that is the SQLite version in the
    612 ** format "X.Y.Z" where X is the major version number (always 3 for
    613 ** SQLite3) and Y is the minor version number and Z is the release number.)^
    614 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
    615 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
    616 ** numbers used in [SQLITE_VERSION].)^
    617 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
    618 ** be larger than the release from which it is derived.  Either Y will
    619 ** be held constant and Z will be incremented or else Y will be incremented
    620 ** and Z will be reset to zero.
    621 **
    622 ** Since version 3.6.18, SQLite source code has been stored in the
    623 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
    624 ** system</a>.  ^The SQLITE_SOURCE_ID macro evalutes to
    625 ** a string which identifies a particular check-in of SQLite
    626 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
    627 ** string contains the date and time of the check-in (UTC) and an SHA1
    628 ** hash of the entire source tree.
    629 **
    630 ** See also: [sqlite3_libversion()],
    631 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
    632 ** [sqlite_version()] and [sqlite_source_id()].
    633 */
    634 #define SQLITE_VERSION        "3.6.22"
    635 #define SQLITE_VERSION_NUMBER 3006022
    636 #define SQLITE_SOURCE_ID      "2010-03-22 23:55:10 82dd61fccff3e4c77e060e5734cd4b4e2eeb7c32"
    637 
    638 /*
    639 ** CAPI3REF: Run-Time Library Version Numbers
    640 ** KEYWORDS: sqlite3_version
    641 **
    642 ** These interfaces provide the same information as the [SQLITE_VERSION],
    643 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
    644 ** but are associated with the library instead of the header file.  ^(Cautious
    645 ** programmers might include assert() statements in their application to
    646 ** verify that values returned by these interfaces match the macros in
    647 ** the header, and thus insure that the application is
    648 ** compiled with matching library and header files.
    649 **
    650 ** <blockquote><pre>
    651 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
    652 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
    653 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
    654 ** </pre></blockquote>)^
    655 **
    656 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
    657 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
    658 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
    659 ** function is provided for use in DLLs since DLL users usually do not have
    660 ** direct access to string constants within the DLL.  ^The
    661 ** sqlite3_libversion_number() function returns an integer equal to
    662 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function a pointer
    663 ** to a string constant whose value is the same as the [SQLITE_SOURCE_ID]
    664 ** C preprocessor macro.
    665 **
    666 ** See also: [sqlite_version()] and [sqlite_source_id()].
    667 */
    668 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
    669 SQLITE_API const char *sqlite3_libversion(void);
    670 SQLITE_API const char *sqlite3_sourceid(void);
    671 SQLITE_API int sqlite3_libversion_number(void);
    672 
    673 /*
    674 ** CAPI3REF: Test To See If The Library Is Threadsafe
    675 **
    676 ** ^The sqlite3_threadsafe() function returns zero if and only if
    677 ** SQLite was compiled mutexing code omitted due to the
    678 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
    679 **
    680 ** SQLite can be compiled with or without mutexes.  When
    681 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
    682 ** are enabled and SQLite is threadsafe.  When the
    683 ** [SQLITE_THREADSAFE] macro is 0,
    684 ** the mutexes are omitted.  Without the mutexes, it is not safe
    685 ** to use SQLite concurrently from more than one thread.
    686 **
    687 ** Enabling mutexes incurs a measurable performance penalty.
    688 ** So if speed is of utmost importance, it makes sense to disable
    689 ** the mutexes.  But for maximum safety, mutexes should be enabled.
    690 ** ^The default behavior is for mutexes to be enabled.
    691 **
    692 ** This interface can be used by an application to make sure that the
    693 ** version of SQLite that it is linking against was compiled with
    694 ** the desired setting of the [SQLITE_THREADSAFE] macro.
    695 **
    696 ** This interface only reports on the compile-time mutex setting
    697 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
    698 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
    699 ** can be fully or partially disabled using a call to [sqlite3_config()]
    700 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
    701 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
    702 ** sqlite3_threadsafe() function shows only the compile-time setting of
    703 ** thread safety, not any run-time changes to that setting made by
    704 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
    705 ** is unchanged by calls to sqlite3_config().)^
    706 **
    707 ** See the [threading mode] documentation for additional information.
    708 */
    709 SQLITE_API int sqlite3_threadsafe(void);
    710 
    711 /*
    712 ** CAPI3REF: Database Connection Handle
    713 ** KEYWORDS: {database connection} {database connections}
    714 **
    715 ** Each open SQLite database is represented by a pointer to an instance of
    716 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
    717 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
    718 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
    719 ** is its destructor.  There are many other interfaces (such as
    720 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
    721 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
    722 ** sqlite3 object.
    723 */
    724 typedef struct sqlite3 sqlite3;
    725 
    726 /*
    727 ** CAPI3REF: 64-Bit Integer Types
    728 ** KEYWORDS: sqlite_int64 sqlite_uint64
    729 **
    730 ** Because there is no cross-platform way to specify 64-bit integer types
    731 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
    732 **
    733 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
    734 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
    735 ** compatibility only.
    736 **
    737 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
    738 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
    739 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
    740 ** between 0 and +18446744073709551615 inclusive.
    741 */
    742 #ifdef SQLITE_INT64_TYPE
    743   typedef SQLITE_INT64_TYPE sqlite_int64;
    744   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
    745 #elif defined(_MSC_VER) || defined(__BORLANDC__)
    746   typedef __int64 sqlite_int64;
    747   typedef unsigned __int64 sqlite_uint64;
    748 #else
    749   typedef long long int sqlite_int64;
    750   typedef unsigned long long int sqlite_uint64;
    751 #endif
    752 typedef sqlite_int64 sqlite3_int64;
    753 typedef sqlite_uint64 sqlite3_uint64;
    754 
    755 /*
    756 ** If compiling for a processor that lacks floating point support,
    757 ** substitute integer for floating-point.
    758 */
    759 #ifdef SQLITE_OMIT_FLOATING_POINT
    760 # define double sqlite3_int64
    761 #endif
    762 
    763 /*
    764 ** CAPI3REF: Closing A Database Connection
    765 **
    766 ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
    767 ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
    768 ** successfullly destroyed and all associated resources are deallocated.
    769 **
    770 ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
    771 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
    772 ** the [sqlite3] object prior to attempting to close the object.  ^If
    773 ** sqlite3_close() is called on a [database connection] that still has
    774 ** outstanding [prepared statements] or [BLOB handles], then it returns
    775 ** SQLITE_BUSY.
    776 **
    777 ** ^If [sqlite3_close()] is invoked while a transaction is open,
    778 ** the transaction is automatically rolled back.
    779 **
    780 ** The C parameter to [sqlite3_close(C)] must be either a NULL
    781 ** pointer or an [sqlite3] object pointer obtained
    782 ** from [sqlite3_open()], [sqlite3_open16()], or
    783 ** [sqlite3_open_v2()], and not previously closed.
    784 ** ^Calling sqlite3_close() with a NULL pointer argument is a
    785 ** harmless no-op.
    786 */
    787 SQLITE_API int sqlite3_close(sqlite3 *);
    788 
    789 /*
    790 ** The type for a callback function.
    791 ** This is legacy and deprecated.  It is included for historical
    792 ** compatibility and is not documented.
    793 */
    794 typedef int (*sqlite3_callback)(void*,int,char**, char**);
    795 
    796 /*
    797 ** CAPI3REF: One-Step Query Execution Interface
    798 **
    799 ** The sqlite3_exec() interface is a convenience wrapper around
    800 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
    801 ** that allows an application to run multiple statements of SQL
    802 ** without having to use a lot of C code.
    803 **
    804 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
    805 ** semicolon-separate SQL statements passed into its 2nd argument,
    806 ** in the context of the [database connection] passed in as its 1st
    807 ** argument.  ^If the callback function of the 3rd argument to
    808 ** sqlite3_exec() is not NULL, then it is invoked for each result row
    809 ** coming out of the evaluated SQL statements.  ^The 4th argument to
    810 ** to sqlite3_exec() is relayed through to the 1st argument of each
    811 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
    812 ** is NULL, then no callback is ever invoked and result rows are
    813 ** ignored.
    814 **
    815 ** ^If an error occurs while evaluating the SQL statements passed into
    816 ** sqlite3_exec(), then execution of the current statement stops and
    817 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
    818 ** is not NULL then any error message is written into memory obtained
    819 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
    820 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
    821 ** on error message strings returned through the 5th parameter of
    822 ** of sqlite3_exec() after the error message string is no longer needed.
    823 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
    824 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
    825 ** NULL before returning.
    826 **
    827 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
    828 ** routine returns SQLITE_ABORT without invoking the callback again and
    829 ** without running any subsequent SQL statements.
    830 **
    831 ** ^The 2nd argument to the sqlite3_exec() callback function is the
    832 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
    833 ** callback is an array of pointers to strings obtained as if from
    834 ** [sqlite3_column_text()], one for each column.  ^If an element of a
    835 ** result row is NULL then the corresponding string pointer for the
    836 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
    837 ** sqlite3_exec() callback is an array of pointers to strings where each
    838 ** entry represents the name of corresponding result column as obtained
    839 ** from [sqlite3_column_name()].
    840 **
    841 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
    842 ** to an empty string, or a pointer that contains only whitespace and/or
    843 ** SQL comments, then no SQL statements are evaluated and the database
    844 ** is not changed.
    845 **
    846 ** Restrictions:
    847 **
    848 ** <ul>
    849 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
    850 **      is a valid and open [database connection].
    851 ** <li> The application must not close [database connection] specified by
    852 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
    853 ** <li> The application must not modify the SQL statement text passed into
    854 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
    855 ** </ul>
    856 */
    857 SQLITE_API int sqlite3_exec(
    858   sqlite3*,                                  /* An open database */
    859   const char *sql,                           /* SQL to be evaluated */
    860   int (*callback)(void*,int,char**,char**),  /* Callback function */
    861   void *,                                    /* 1st argument to callback */
    862   char **errmsg                              /* Error msg written here */
    863 );
    864 
    865 /*
    866 ** CAPI3REF: Result Codes
    867 ** KEYWORDS: SQLITE_OK {error code} {error codes}
    868 ** KEYWORDS: {result code} {result codes}
    869 **
    870 ** Many SQLite functions return an integer result code from the set shown
    871 ** here in order to indicates success or failure.
    872 **
    873 ** New error codes may be added in future versions of SQLite.
    874 **
    875 ** See also: [SQLITE_IOERR_READ | extended result codes]
    876 */
    877 #define SQLITE_OK           0   /* Successful result */
    878 /* beginning-of-error-codes */
    879 #define SQLITE_ERROR        1   /* SQL error or missing database */
    880 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
    881 #define SQLITE_PERM         3   /* Access permission denied */
    882 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
    883 #define SQLITE_BUSY         5   /* The database file is locked */
    884 #define SQLITE_LOCKED       6   /* A table in the database is locked */
    885 #define SQLITE_NOMEM        7   /* A malloc() failed */
    886 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
    887 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
    888 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
    889 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
    890 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
    891 #define SQLITE_FULL        13   /* Insertion failed because database is full */
    892 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
    893 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
    894 #define SQLITE_EMPTY       16   /* Database is empty */
    895 #define SQLITE_SCHEMA      17   /* The database schema changed */
    896 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
    897 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
    898 #define SQLITE_MISMATCH    20   /* Data type mismatch */
    899 #define SQLITE_MISUSE      21   /* Library used incorrectly */
    900 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
    901 #define SQLITE_AUTH        23   /* Authorization denied */
    902 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
    903 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
    904 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
    905 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
    906 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
    907 /* end-of-error-codes */
    908 
    909 /*
    910 ** CAPI3REF: Extended Result Codes
    911 ** KEYWORDS: {extended error code} {extended error codes}
    912 ** KEYWORDS: {extended result code} {extended result codes}
    913 **
    914 ** In its default configuration, SQLite API routines return one of 26 integer
    915 ** [SQLITE_OK | result codes].  However, experience has shown that many of
    916 ** these result codes are too coarse-grained.  They do not provide as
    917 ** much information about problems as programmers might like.  In an effort to
    918 ** address this, newer versions of SQLite (version 3.3.8 and later) include
    919 ** support for additional result codes that provide more detailed information
    920 ** about errors. The extended result codes are enabled or disabled
    921 ** on a per database connection basis using the
    922 ** [sqlite3_extended_result_codes()] API.
    923 **
    924 ** Some of the available extended result codes are listed here.
    925 ** One may expect the number of extended result codes will be expand
    926 ** over time.  Software that uses extended result codes should expect
    927 ** to see new result codes in future releases of SQLite.
    928 **
    929 ** The SQLITE_OK result code will never be extended.  It will always
    930 ** be exactly zero.
    931 */
    932 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
    933 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
    934 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
    935 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
    936 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
    937 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
    938 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
    939 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
    940 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
    941 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
    942 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
    943 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
    944 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
    945 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
    946 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
    947 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
    948 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
    949 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED | (1<<8) )
    950 
    951 /*
    952 ** CAPI3REF: Flags For File Open Operations
    953 **
    954 ** These bit values are intended for use in the
    955 ** 3rd parameter to the [sqlite3_open_v2()] interface and
    956 ** in the 4th parameter to the xOpen method of the
    957 ** [sqlite3_vfs] object.
    958 */
    959 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
    960 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
    961 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
    962 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
    963 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
    964 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
    965 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
    966 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
    967 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
    968 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
    969 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
    970 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
    971 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
    972 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
    973 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
    974 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
    975 
    976 /*
    977 ** CAPI3REF: Device Characteristics
    978 **
    979 ** The xDeviceCapabilities method of the [sqlite3_io_methods]
    980 ** object returns an integer which is a vector of the these
    981 ** bit values expressing I/O characteristics of the mass storage
    982 ** device that holds the file that the [sqlite3_io_methods]
    983 ** refers to.
    984 **
    985 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
    986 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
    987 ** mean that writes of blocks that are nnn bytes in size and
    988 ** are aligned to an address which is an integer multiple of
    989 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
    990 ** that when data is appended to a file, the data is appended
    991 ** first then the size of the file is extended, never the other
    992 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
    993 ** information is written to disk in the same order as calls
    994 ** to xWrite().
    995 */
    996 #define SQLITE_IOCAP_ATOMIC          0x00000001
    997 #define SQLITE_IOCAP_ATOMIC512       0x00000002
    998 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
    999 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
   1000 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
   1001 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
   1002 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
   1003 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
   1004 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
   1005 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
   1006 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
   1007 
   1008 /*
   1009 ** CAPI3REF: File Locking Levels
   1010 **
   1011 ** SQLite uses one of these integer values as the second
   1012 ** argument to calls it makes to the xLock() and xUnlock() methods
   1013 ** of an [sqlite3_io_methods] object.
   1014 */
   1015 #define SQLITE_LOCK_NONE          0
   1016 #define SQLITE_LOCK_SHARED        1
   1017 #define SQLITE_LOCK_RESERVED      2
   1018 #define SQLITE_LOCK_PENDING       3
   1019 #define SQLITE_LOCK_EXCLUSIVE     4
   1020 
   1021 /*
   1022 ** CAPI3REF: Synchronization Type Flags
   1023 **
   1024 ** When SQLite invokes the xSync() method of an
   1025 ** [sqlite3_io_methods] object it uses a combination of
   1026 ** these integer values as the second argument.
   1027 **
   1028 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
   1029 ** sync operation only needs to flush data to mass storage.  Inode
   1030 ** information need not be flushed. If the lower four bits of the flag
   1031 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
   1032 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
   1033 ** to use Mac OS X style fullsync instead of fsync().
   1034 */
   1035 #define SQLITE_SYNC_NORMAL        0x00002
   1036 #define SQLITE_SYNC_FULL          0x00003
   1037 #define SQLITE_SYNC_DATAONLY      0x00010
   1038 
   1039 /*
   1040 ** CAPI3REF: OS Interface Open File Handle
   1041 **
   1042 ** An [sqlite3_file] object represents an open file in the
   1043 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
   1044 ** implementations will
   1045 ** want to subclass this object by appending additional fields
   1046 ** for their own use.  The pMethods entry is a pointer to an
   1047 ** [sqlite3_io_methods] object that defines methods for performing
   1048 ** I/O operations on the open file.
   1049 */
   1050 typedef struct sqlite3_file sqlite3_file;
   1051 struct sqlite3_file {
   1052   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
   1053 };
   1054 
   1055 /*
   1056 ** CAPI3REF: OS Interface File Virtual Methods Object
   1057 **
   1058 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
   1059 ** [sqlite3_file] object (or, more commonly, a subclass of the
   1060 ** [sqlite3_file] object) with a pointer to an instance of this object.
   1061 ** This object defines the methods used to perform various operations
   1062 ** against the open file represented by the [sqlite3_file] object.
   1063 **
   1064 ** If the xOpen method sets the sqlite3_file.pMethods element
   1065 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
   1066 ** may be invoked even if the xOpen reported that it failed.  The
   1067 ** only way to prevent a call to xClose following a failed xOpen
   1068 ** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
   1069 **
   1070 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
   1071 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
   1072 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
   1073 ** flag may be ORed in to indicate that only the data of the file
   1074 ** and not its inode needs to be synced.
   1075 **
   1076 ** The integer values to xLock() and xUnlock() are one of
   1077 ** <ul>
   1078 ** <li> [SQLITE_LOCK_NONE],
   1079 ** <li> [SQLITE_LOCK_SHARED],
   1080 ** <li> [SQLITE_LOCK_RESERVED],
   1081 ** <li> [SQLITE_LOCK_PENDING], or
   1082 ** <li> [SQLITE_LOCK_EXCLUSIVE].
   1083 ** </ul>
   1084 ** xLock() increases the lock. xUnlock() decreases the lock.
   1085 ** The xCheckReservedLock() method checks whether any database connection,
   1086 ** either in this process or in some other process, is holding a RESERVED,
   1087 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
   1088 ** if such a lock exists and false otherwise.
   1089 **
   1090 ** The xFileControl() method is a generic interface that allows custom
   1091 ** VFS implementations to directly control an open file using the
   1092 ** [sqlite3_file_control()] interface.  The second "op" argument is an
   1093 ** integer opcode.  The third argument is a generic pointer intended to
   1094 ** point to a structure that may contain arguments or space in which to
   1095 ** write return values.  Potential uses for xFileControl() might be
   1096 ** functions to enable blocking locks with timeouts, to change the
   1097 ** locking strategy (for example to use dot-file locks), to inquire
   1098 ** about the status of a lock, or to break stale locks.  The SQLite
   1099 ** core reserves all opcodes less than 100 for its own use.
   1100 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
   1101 ** Applications that define a custom xFileControl method should use opcodes
   1102 ** greater than 100 to avoid conflicts.
   1103 **
   1104 ** The xSectorSize() method returns the sector size of the
   1105 ** device that underlies the file.  The sector size is the
   1106 ** minimum write that can be performed without disturbing
   1107 ** other bytes in the file.  The xDeviceCharacteristics()
   1108 ** method returns a bit vector describing behaviors of the
   1109 ** underlying device:
   1110 **
   1111 ** <ul>
   1112 ** <li> [SQLITE_IOCAP_ATOMIC]
   1113 ** <li> [SQLITE_IOCAP_ATOMIC512]
   1114 ** <li> [SQLITE_IOCAP_ATOMIC1K]
   1115 ** <li> [SQLITE_IOCAP_ATOMIC2K]
   1116 ** <li> [SQLITE_IOCAP_ATOMIC4K]
   1117 ** <li> [SQLITE_IOCAP_ATOMIC8K]
   1118 ** <li> [SQLITE_IOCAP_ATOMIC16K]
   1119 ** <li> [SQLITE_IOCAP_ATOMIC32K]
   1120 ** <li> [SQLITE_IOCAP_ATOMIC64K]
   1121 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
   1122 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
   1123 ** </ul>
   1124 **
   1125 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
   1126 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
   1127 ** mean that writes of blocks that are nnn bytes in size and
   1128 ** are aligned to an address which is an integer multiple of
   1129 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
   1130 ** that when data is appended to a file, the data is appended
   1131 ** first then the size of the file is extended, never the other
   1132 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
   1133 ** information is written to disk in the same order as calls
   1134 ** to xWrite().
   1135 **
   1136 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
   1137 ** in the unread portions of the buffer with zeros.  A VFS that
   1138 ** fails to zero-fill short reads might seem to work.  However,
   1139 ** failure to zero-fill short reads will eventually lead to
   1140 ** database corruption.
   1141 */
   1142 typedef struct sqlite3_io_methods sqlite3_io_methods;
   1143 struct sqlite3_io_methods {
   1144   int iVersion;
   1145   int (*xClose)(sqlite3_file*);
   1146   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
   1147   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
   1148   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
   1149   int (*xSync)(sqlite3_file*, int flags);
   1150   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
   1151   int (*xLock)(sqlite3_file*, int);
   1152   int (*xUnlock)(sqlite3_file*, int);
   1153   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
   1154   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
   1155   int (*xSectorSize)(sqlite3_file*);
   1156   int (*xDeviceCharacteristics)(sqlite3_file*);
   1157   /* Additional methods may be added in future releases */
   1158 };
   1159 
   1160 /*
   1161 ** CAPI3REF: Standard File Control Opcodes
   1162 **
   1163 ** These integer constants are opcodes for the xFileControl method
   1164 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
   1165 ** interface.
   1166 **
   1167 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
   1168 ** opcode causes the xFileControl method to write the current state of
   1169 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
   1170 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
   1171 ** into an integer that the pArg argument points to. This capability
   1172 ** is used during testing and only needs to be supported when SQLITE_TEST
   1173 ** is defined.
   1174 */
   1175 #define SQLITE_FCNTL_LOCKSTATE        1
   1176 #define SQLITE_GET_LOCKPROXYFILE      2
   1177 #define SQLITE_SET_LOCKPROXYFILE      3
   1178 #define SQLITE_LAST_ERRNO             4
   1179 
   1180 /*
   1181 ** CAPI3REF: Mutex Handle
   1182 **
   1183 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
   1184 ** abstract type for a mutex object.  The SQLite core never looks
   1185 ** at the internal representation of an [sqlite3_mutex].  It only
   1186 ** deals with pointers to the [sqlite3_mutex] object.
   1187 **
   1188 ** Mutexes are created using [sqlite3_mutex_alloc()].
   1189 */
   1190 typedef struct sqlite3_mutex sqlite3_mutex;
   1191 
   1192 /*
   1193 ** CAPI3REF: OS Interface Object
   1194 **
   1195 ** An instance of the sqlite3_vfs object defines the interface between
   1196 ** the SQLite core and the underlying operating system.  The "vfs"
   1197 ** in the name of the object stands for "virtual file system".
   1198 **
   1199 ** The value of the iVersion field is initially 1 but may be larger in
   1200 ** future versions of SQLite.  Additional fields may be appended to this
   1201 ** object when the iVersion value is increased.  Note that the structure
   1202 ** of the sqlite3_vfs object changes in the transaction between
   1203 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
   1204 ** modified.
   1205 **
   1206 ** The szOsFile field is the size of the subclassed [sqlite3_file]
   1207 ** structure used by this VFS.  mxPathname is the maximum length of
   1208 ** a pathname in this VFS.
   1209 **
   1210 ** Registered sqlite3_vfs objects are kept on a linked list formed by
   1211 ** the pNext pointer.  The [sqlite3_vfs_register()]
   1212 ** and [sqlite3_vfs_unregister()] interfaces manage this list
   1213 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
   1214 ** searches the list.  Neither the application code nor the VFS
   1215 ** implementation should use the pNext pointer.
   1216 **
   1217 ** The pNext field is the only field in the sqlite3_vfs
   1218 ** structure that SQLite will ever modify.  SQLite will only access
   1219 ** or modify this field while holding a particular static mutex.
   1220 ** The application should never modify anything within the sqlite3_vfs
   1221 ** object once the object has been registered.
   1222 **
   1223 ** The zName field holds the name of the VFS module.  The name must
   1224 ** be unique across all VFS modules.
   1225 **
   1226 ** SQLite will guarantee that the zFilename parameter to xOpen
   1227 ** is either a NULL pointer or string obtained
   1228 ** from xFullPathname().  SQLite further guarantees that
   1229 ** the string will be valid and unchanged until xClose() is
   1230 ** called. Because of the previous sentence,
   1231 ** the [sqlite3_file] can safely store a pointer to the
   1232 ** filename if it needs to remember the filename for some reason.
   1233 ** If the zFilename parameter is xOpen is a NULL pointer then xOpen
   1234 ** must invent its own temporary name for the file.  Whenever the
   1235 ** xFilename parameter is NULL it will also be the case that the
   1236 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
   1237 **
   1238 ** The flags argument to xOpen() includes all bits set in
   1239 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
   1240 ** or [sqlite3_open16()] is used, then flags includes at least
   1241 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
   1242 ** If xOpen() opens a file read-only then it sets *pOutFlags to
   1243 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
   1244 **
   1245 ** SQLite will also add one of the following flags to the xOpen()
   1246 ** call, depending on the object being opened:
   1247 **
   1248 ** <ul>
   1249 ** <li>  [SQLITE_OPEN_MAIN_DB]
   1250 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
   1251 ** <li>  [SQLITE_OPEN_TEMP_DB]
   1252 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
   1253 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
   1254 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
   1255 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
   1256 ** </ul>
   1257 **
   1258 ** The file I/O implementation can use the object type flags to
   1259 ** change the way it deals with files.  For example, an application
   1260 ** that does not care about crash recovery or rollback might make
   1261 ** the open of a journal file a no-op.  Writes to this journal would
   1262 ** also be no-ops, and any attempt to read the journal would return
   1263 ** SQLITE_IOERR.  Or the implementation might recognize that a database
   1264 ** file will be doing page-aligned sector reads and writes in a random
   1265 ** order and set up its I/O subsystem accordingly.
   1266 **
   1267 ** SQLite might also add one of the following flags to the xOpen method:
   1268 **
   1269 ** <ul>
   1270 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
   1271 ** <li> [SQLITE_OPEN_EXCLUSIVE]
   1272 ** </ul>
   1273 **
   1274 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
   1275 ** deleted when it is closed.  The [SQLITE_OPEN_DELETEONCLOSE]
   1276 ** will be set for TEMP  databases, journals and for subjournals.
   1277 **
   1278 ** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
   1279 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
   1280 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
   1281 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
   1282 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
   1283 ** be created, and that it is an error if it already exists.
   1284 ** It is <i>not</i> used to indicate the file should be opened
   1285 ** for exclusive access.
   1286 **
   1287 ** At least szOsFile bytes of memory are allocated by SQLite
   1288 ** to hold the  [sqlite3_file] structure passed as the third
   1289 ** argument to xOpen.  The xOpen method does not have to
   1290 ** allocate the structure; it should just fill it in.  Note that
   1291 ** the xOpen method must set the sqlite3_file.pMethods to either
   1292 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
   1293 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
   1294 ** element will be valid after xOpen returns regardless of the success
   1295 ** or failure of the xOpen call.
   1296 **
   1297 ** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
   1298 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
   1299 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
   1300 ** to test whether a file is at least readable.   The file can be a
   1301 ** directory.
   1302 **
   1303 ** SQLite will always allocate at least mxPathname+1 bytes for the
   1304 ** output buffer xFullPathname.  The exact size of the output buffer
   1305 ** is also passed as a parameter to both  methods. If the output buffer
   1306 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
   1307 ** handled as a fatal error by SQLite, vfs implementations should endeavor
   1308 ** to prevent this by setting mxPathname to a sufficiently large value.
   1309 **
   1310 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
   1311 ** are not strictly a part of the filesystem, but they are
   1312 ** included in the VFS structure for completeness.
   1313 ** The xRandomness() function attempts to return nBytes bytes
   1314 ** of good-quality randomness into zOut.  The return value is
   1315 ** the actual number of bytes of randomness obtained.
   1316 ** The xSleep() method causes the calling thread to sleep for at
   1317 ** least the number of microseconds given.  The xCurrentTime()
   1318 ** method returns a Julian Day Number for the current date and time.
   1319 **
   1320 */
   1321 typedef struct sqlite3_vfs sqlite3_vfs;
   1322 struct sqlite3_vfs {
   1323   int iVersion;            /* Structure version number */
   1324   int szOsFile;            /* Size of subclassed sqlite3_file */
   1325   int mxPathname;          /* Maximum file pathname length */
   1326   sqlite3_vfs *pNext;      /* Next registered VFS */
   1327   const char *zName;       /* Name of this virtual file system */
   1328   void *pAppData;          /* Pointer to application-specific data */
   1329   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
   1330                int flags, int *pOutFlags);
   1331   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
   1332   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
   1333   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
   1334   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
   1335   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
   1336   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
   1337   void (*xDlClose)(sqlite3_vfs*, void*);
   1338   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
   1339   int (*xSleep)(sqlite3_vfs*, int microseconds);
   1340   int (*xCurrentTime)(sqlite3_vfs*, double*);
   1341   int (*xGetLastError)(sqlite3_vfs*, int, char *);
   1342   /* New fields may be appended in figure versions.  The iVersion
   1343   ** value will increment whenever this happens. */
   1344 };
   1345 
   1346 /*
   1347 ** CAPI3REF: Flags for the xAccess VFS method
   1348 **
   1349 ** These integer constants can be used as the third parameter to
   1350 ** the xAccess method of an [sqlite3_vfs] object.  They determine
   1351 ** what kind of permissions the xAccess method is looking for.
   1352 ** With SQLITE_ACCESS_EXISTS, the xAccess method
   1353 ** simply checks whether the file exists.
   1354 ** With SQLITE_ACCESS_READWRITE, the xAccess method
   1355 ** checks whether the file is both readable and writable.
   1356 ** With SQLITE_ACCESS_READ, the xAccess method
   1357 ** checks whether the file is readable.
   1358 */
   1359 #define SQLITE_ACCESS_EXISTS    0
   1360 #define SQLITE_ACCESS_READWRITE 1
   1361 #define SQLITE_ACCESS_READ      2
   1362 
   1363 /*
   1364 ** CAPI3REF: Initialize The SQLite Library
   1365 **
   1366 ** ^The sqlite3_initialize() routine initializes the
   1367 ** SQLite library.  ^The sqlite3_shutdown() routine
   1368 ** deallocates any resources that were allocated by sqlite3_initialize().
   1369 ** These routines are designed to aid in process initialization and
   1370 ** shutdown on embedded systems.  Workstation applications using
   1371 ** SQLite normally do not need to invoke either of these routines.
   1372 **
   1373 ** A call to sqlite3_initialize() is an "effective" call if it is
   1374 ** the first time sqlite3_initialize() is invoked during the lifetime of
   1375 ** the process, or if it is the first time sqlite3_initialize() is invoked
   1376 ** following a call to sqlite3_shutdown().  ^(Only an effective call
   1377 ** of sqlite3_initialize() does any initialization.  All other calls
   1378 ** are harmless no-ops.)^
   1379 **
   1380 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
   1381 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
   1382 ** an effective call to sqlite3_shutdown() does any deinitialization.
   1383 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
   1384 **
   1385 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
   1386 ** is not.  The sqlite3_shutdown() interface must only be called from a
   1387 ** single thread.  All open [database connections] must be closed and all
   1388 ** other SQLite resources must be deallocated prior to invoking
   1389 ** sqlite3_shutdown().
   1390 **
   1391 ** Among other things, ^sqlite3_initialize() will invoke
   1392 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
   1393 ** will invoke sqlite3_os_end().
   1394 **
   1395 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
   1396 ** ^If for some reason, sqlite3_initialize() is unable to initialize
   1397 ** the library (perhaps it is unable to allocate a needed resource such
   1398 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
   1399 **
   1400 ** ^The sqlite3_initialize() routine is called internally by many other
   1401 ** SQLite interfaces so that an application usually does not need to
   1402 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
   1403 ** calls sqlite3_initialize() so the SQLite library will be automatically
   1404 ** initialized when [sqlite3_open()] is called if it has not be initialized
   1405 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
   1406 ** compile-time option, then the automatic calls to sqlite3_initialize()
   1407 ** are omitted and the application must call sqlite3_initialize() directly
   1408 ** prior to using any other SQLite interface.  For maximum portability,
   1409 ** it is recommended that applications always invoke sqlite3_initialize()
   1410 ** directly prior to using any other SQLite interface.  Future releases
   1411 ** of SQLite may require this.  In other words, the behavior exhibited
   1412 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
   1413 ** default behavior in some future release of SQLite.
   1414 **
   1415 ** The sqlite3_os_init() routine does operating-system specific
   1416 ** initialization of the SQLite library.  The sqlite3_os_end()
   1417 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
   1418 ** performed by these routines include allocation or deallocation
   1419 ** of static resources, initialization of global variables,
   1420 ** setting up a default [sqlite3_vfs] module, or setting up
   1421 ** a default configuration using [sqlite3_config()].
   1422 **
   1423 ** The application should never invoke either sqlite3_os_init()
   1424 ** or sqlite3_os_end() directly.  The application should only invoke
   1425 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
   1426 ** interface is called automatically by sqlite3_initialize() and
   1427 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
   1428 ** implementations for sqlite3_os_init() and sqlite3_os_end()
   1429 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
   1430 ** When [custom builds | built for other platforms]
   1431 ** (using the [SQLITE_OS_OTHER=1] compile-time
   1432 ** option) the application must supply a suitable implementation for
   1433 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
   1434 ** implementation of sqlite3_os_init() or sqlite3_os_end()
   1435 ** must return [SQLITE_OK] on success and some other [error code] upon
   1436 ** failure.
   1437 */
   1438 SQLITE_API int sqlite3_initialize(void);
   1439 SQLITE_API int sqlite3_shutdown(void);
   1440 SQLITE_API int sqlite3_os_init(void);
   1441 SQLITE_API int sqlite3_os_end(void);
   1442 
   1443 /*
   1444 ** CAPI3REF: Configuring The SQLite Library
   1445 **
   1446 ** The sqlite3_config() interface is used to make global configuration
   1447 ** changes to SQLite in order to tune SQLite to the specific needs of
   1448 ** the application.  The default configuration is recommended for most
   1449 ** applications and so this routine is usually not necessary.  It is
   1450 ** provided to support rare applications with unusual needs.
   1451 **
   1452 ** The sqlite3_config() interface is not threadsafe.  The application
   1453 ** must insure that no other SQLite interfaces are invoked by other
   1454 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
   1455 ** may only be invoked prior to library initialization using
   1456 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
   1457 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
   1458 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
   1459 ** Note, however, that ^sqlite3_config() can be called as part of the
   1460 ** implementation of an application-defined [sqlite3_os_init()].
   1461 **
   1462 ** The first argument to sqlite3_config() is an integer
   1463 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
   1464 ** what property of SQLite is to be configured.  Subsequent arguments
   1465 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
   1466 ** in the first argument.
   1467 **
   1468 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
   1469 ** ^If the option is unknown or SQLite is unable to set the option
   1470 ** then this routine returns a non-zero [error code].
   1471 */
   1472 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
   1473 
   1474 /*
   1475 ** CAPI3REF: Configure database connections
   1476 ** EXPERIMENTAL
   1477 **
   1478 ** The sqlite3_db_config() interface is used to make configuration
   1479 ** changes to a [database connection].  The interface is similar to
   1480 ** [sqlite3_config()] except that the changes apply to a single
   1481 ** [database connection] (specified in the first argument).  The
   1482 ** sqlite3_db_config() interface should only be used immediately after
   1483 ** the database connection is created using [sqlite3_open()],
   1484 ** [sqlite3_open16()], or [sqlite3_open_v2()].
   1485 **
   1486 ** The second argument to sqlite3_db_config(D,V,...)  is the
   1487 ** configuration verb - an integer code that indicates what
   1488 ** aspect of the [database connection] is being configured.
   1489 ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
   1490 ** New verbs are likely to be added in future releases of SQLite.
   1491 ** Additional arguments depend on the verb.
   1492 **
   1493 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
   1494 ** the call is considered successful.
   1495 */
   1496 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
   1497 
   1498 /*
   1499 ** CAPI3REF: Memory Allocation Routines
   1500 ** EXPERIMENTAL
   1501 **
   1502 ** An instance of this object defines the interface between SQLite
   1503 ** and low-level memory allocation routines.
   1504 **
   1505 ** This object is used in only one place in the SQLite interface.
   1506 ** A pointer to an instance of this object is the argument to
   1507 ** [sqlite3_config()] when the configuration option is
   1508 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
   1509 ** By creating an instance of this object
   1510 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
   1511 ** during configuration, an application can specify an alternative
   1512 ** memory allocation subsystem for SQLite to use for all of its
   1513 ** dynamic memory needs.
   1514 **
   1515 ** Note that SQLite comes with several [built-in memory allocators]
   1516 ** that are perfectly adequate for the overwhelming majority of applications
   1517 ** and that this object is only useful to a tiny minority of applications
   1518 ** with specialized memory allocation requirements.  This object is
   1519 ** also used during testing of SQLite in order to specify an alternative
   1520 ** memory allocator that simulates memory out-of-memory conditions in
   1521 ** order to verify that SQLite recovers gracefully from such
   1522 ** conditions.
   1523 **
   1524 ** The xMalloc and xFree methods must work like the
   1525 ** malloc() and free() functions from the standard C library.
   1526 ** The xRealloc method must work like realloc() from the standard C library
   1527 ** with the exception that if the second argument to xRealloc is zero,
   1528 ** xRealloc must be a no-op - it must not perform any allocation or
   1529 ** deallocation.  ^SQLite guarantees that the second argument to
   1530 ** xRealloc is always a value returned by a prior call to xRoundup.
   1531 ** And so in cases where xRoundup always returns a positive number,
   1532 ** xRealloc can perform exactly as the standard library realloc() and
   1533 ** still be in compliance with this specification.
   1534 **
   1535 ** xSize should return the allocated size of a memory allocation
   1536 ** previously obtained from xMalloc or xRealloc.  The allocated size
   1537 ** is always at least as big as the requested size but may be larger.
   1538 **
   1539 ** The xRoundup method returns what would be the allocated size of
   1540 ** a memory allocation given a particular requested size.  Most memory
   1541 ** allocators round up memory allocations at least to the next multiple
   1542 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
   1543 ** Every memory allocation request coming in through [sqlite3_malloc()]
   1544 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
   1545 ** that causes the corresponding memory allocation to fail.
   1546 **
   1547 ** The xInit method initializes the memory allocator.  (For example,
   1548 ** it might allocate any require mutexes or initialize internal data
   1549 ** structures.  The xShutdown method is invoked (indirectly) by
   1550 ** [sqlite3_shutdown()] and should deallocate any resources acquired
   1551 ** by xInit.  The pAppData pointer is used as the only parameter to
   1552 ** xInit and xShutdown.
   1553 **
   1554 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
   1555 ** the xInit method, so the xInit method need not be threadsafe.  The
   1556 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
   1557 ** not need to be threadsafe either.  For all other methods, SQLite
   1558 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
   1559 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
   1560 ** it is by default) and so the methods are automatically serialized.
   1561 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
   1562 ** methods must be threadsafe or else make their own arrangements for
   1563 ** serialization.
   1564 **
   1565 ** SQLite will never invoke xInit() more than once without an intervening
   1566 ** call to xShutdown().
   1567 */
   1568 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
   1569 struct sqlite3_mem_methods {
   1570   void *(*xMalloc)(int);         /* Memory allocation function */
   1571   void (*xFree)(void*);          /* Free a prior allocation */
   1572   void *(*xRealloc)(void*,int);  /* Resize an allocation */
   1573   int (*xSize)(void*);           /* Return the size of an allocation */
   1574   int (*xRoundup)(int);          /* Round up request size to allocation size */
   1575   int (*xInit)(void*);           /* Initialize the memory allocator */
   1576   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
   1577   void *pAppData;                /* Argument to xInit() and xShutdown() */
   1578 };
   1579 
   1580 /*
   1581 ** CAPI3REF: Configuration Options
   1582 ** EXPERIMENTAL
   1583 **
   1584 ** These constants are the available integer configuration options that
   1585 ** can be passed as the first argument to the [sqlite3_config()] interface.
   1586 **
   1587 ** New configuration options may be added in future releases of SQLite.
   1588 ** Existing configuration options might be discontinued.  Applications
   1589 ** should check the return code from [sqlite3_config()] to make sure that
   1590 ** the call worked.  The [sqlite3_config()] interface will return a
   1591 ** non-zero [error code] if a discontinued or unsupported configuration option
   1592 ** is invoked.
   1593 **
   1594 ** <dl>
   1595 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
   1596 ** <dd>There are no arguments to this option.  ^This option sets the
   1597 ** [threading mode] to Single-thread.  In other words, it disables
   1598 ** all mutexing and puts SQLite into a mode where it can only be used
   1599 ** by a single thread.   ^If SQLite is compiled with
   1600 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1601 ** it is not possible to change the [threading mode] from its default
   1602 ** value of Single-thread and so [sqlite3_config()] will return
   1603 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
   1604 ** configuration option.</dd>
   1605 **
   1606 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
   1607 ** <dd>There are no arguments to this option.  ^This option sets the
   1608 ** [threading mode] to Multi-thread.  In other words, it disables
   1609 ** mutexing on [database connection] and [prepared statement] objects.
   1610 ** The application is responsible for serializing access to
   1611 ** [database connections] and [prepared statements].  But other mutexes
   1612 ** are enabled so that SQLite will be safe to use in a multi-threaded
   1613 ** environment as long as no two threads attempt to use the same
   1614 ** [database connection] at the same time.  ^If SQLite is compiled with
   1615 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1616 ** it is not possible to set the Multi-thread [threading mode] and
   1617 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
   1618 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
   1619 **
   1620 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
   1621 ** <dd>There are no arguments to this option.  ^This option sets the
   1622 ** [threading mode] to Serialized. In other words, this option enables
   1623 ** all mutexes including the recursive
   1624 ** mutexes on [database connection] and [prepared statement] objects.
   1625 ** In this mode (which is the default when SQLite is compiled with
   1626 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
   1627 ** to [database connections] and [prepared statements] so that the
   1628 ** application is free to use the same [database connection] or the
   1629 ** same [prepared statement] in different threads at the same time.
   1630 ** ^If SQLite is compiled with
   1631 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1632 ** it is not possible to set the Serialized [threading mode] and
   1633 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
   1634 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
   1635 **
   1636 ** <dt>SQLITE_CONFIG_MALLOC</dt>
   1637 ** <dd> ^(This option takes a single argument which is a pointer to an
   1638 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
   1639 ** alternative low-level memory allocation routines to be used in place of
   1640 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
   1641 ** its own private copy of the content of the [sqlite3_mem_methods] structure
   1642 ** before the [sqlite3_config()] call returns.</dd>
   1643 **
   1644 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
   1645 ** <dd> ^(This option takes a single argument which is a pointer to an
   1646 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
   1647 ** structure is filled with the currently defined memory allocation routines.)^
   1648 ** This option can be used to overload the default memory allocation
   1649 ** routines with a wrapper that simulations memory allocation failure or
   1650 ** tracks memory usage, for example. </dd>
   1651 **
   1652 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
   1653 ** <dd> ^This option takes single argument of type int, interpreted as a
   1654 ** boolean, which enables or disables the collection of memory allocation
   1655 ** statistics. ^(When memory allocation statistics are disabled, the
   1656 ** following SQLite interfaces become non-operational:
   1657 **   <ul>
   1658 **   <li> [sqlite3_memory_used()]
   1659 **   <li> [sqlite3_memory_highwater()]
   1660 **   <li> [sqlite3_soft_heap_limit()]
   1661 **   <li> [sqlite3_status()]
   1662 **   </ul>)^
   1663 ** ^Memory allocation statistics are enabled by default unless SQLite is
   1664 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
   1665 ** allocation statistics are disabled by default.
   1666 ** </dd>
   1667 **
   1668 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
   1669 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
   1670 ** scratch memory.  There are three arguments:  A pointer an 8-byte
   1671 ** aligned memory buffer from which the scrach allocations will be
   1672 ** drawn, the size of each scratch allocation (sz),
   1673 ** and the maximum number of scratch allocations (N).  The sz
   1674 ** argument must be a multiple of 16. The sz parameter should be a few bytes
   1675 ** larger than the actual scratch space required due to internal overhead.
   1676 ** The first argument must be a pointer to an 8-byte aligned buffer
   1677 ** of at least sz*N bytes of memory.
   1678 ** ^SQLite will use no more than one scratch buffer per thread.  So
   1679 ** N should be set to the expected maximum number of threads.  ^SQLite will
   1680 ** never require a scratch buffer that is more than 6 times the database
   1681 ** page size. ^If SQLite needs needs additional scratch memory beyond
   1682 ** what is provided by this configuration option, then
   1683 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
   1684 **
   1685 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
   1686 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
   1687 ** the database page cache with the default page cache implemenation.
   1688 ** This configuration should not be used if an application-define page
   1689 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
   1690 ** There are three arguments to this option: A pointer to 8-byte aligned
   1691 ** memory, the size of each page buffer (sz), and the number of pages (N).
   1692 ** The sz argument should be the size of the largest database page
   1693 ** (a power of two between 512 and 32768) plus a little extra for each
   1694 ** page header.  ^The page header size is 20 to 40 bytes depending on
   1695 ** the host architecture.  ^It is harmless, apart from the wasted memory,
   1696 ** to make sz a little too large.  The first
   1697 ** argument should point to an allocation of at least sz*N bytes of memory.
   1698 ** ^SQLite will use the memory provided by the first argument to satisfy its
   1699 ** memory needs for the first N pages that it adds to cache.  ^If additional
   1700 ** page cache memory is needed beyond what is provided by this option, then
   1701 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
   1702 ** ^The implementation might use one or more of the N buffers to hold
   1703 ** memory accounting information. The pointer in the first argument must
   1704 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
   1705 ** will be undefined.</dd>
   1706 **
   1707 ** <dt>SQLITE_CONFIG_HEAP</dt>
   1708 ** <dd> ^This option specifies a static memory buffer that SQLite will use
   1709 ** for all of its dynamic memory allocation needs beyond those provided
   1710 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
   1711 ** There are three arguments: An 8-byte aligned pointer to the memory,
   1712 ** the number of bytes in the memory buffer, and the minimum allocation size.
   1713 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
   1714 ** to using its default memory allocator (the system malloc() implementation),
   1715 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
   1716 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
   1717 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
   1718 ** allocator is engaged to handle all of SQLites memory allocation needs.
   1719 ** The first pointer (the memory pointer) must be aligned to an 8-byte
   1720 ** boundary or subsequent behavior of SQLite will be undefined.</dd>
   1721 **
   1722 ** <dt>SQLITE_CONFIG_MUTEX</dt>
   1723 ** <dd> ^(This option takes a single argument which is a pointer to an
   1724 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
   1725 ** alternative low-level mutex routines to be used in place
   1726 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
   1727 ** content of the [sqlite3_mutex_methods] structure before the call to
   1728 ** [sqlite3_config()] returns. ^If SQLite is compiled with
   1729 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1730 ** the entire mutexing subsystem is omitted from the build and hence calls to
   1731 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
   1732 ** return [SQLITE_ERROR].</dd>
   1733 **
   1734 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
   1735 ** <dd> ^(This option takes a single argument which is a pointer to an
   1736 ** instance of the [sqlite3_mutex_methods] structure.  The
   1737 ** [sqlite3_mutex_methods]
   1738 ** structure is filled with the currently defined mutex routines.)^
   1739 ** This option can be used to overload the default mutex allocation
   1740 ** routines with a wrapper used to track mutex usage for performance
   1741 ** profiling or testing, for example.   ^If SQLite is compiled with
   1742 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1743 ** the entire mutexing subsystem is omitted from the build and hence calls to
   1744 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
   1745 ** return [SQLITE_ERROR].</dd>
   1746 **
   1747 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
   1748 ** <dd> ^(This option takes two arguments that determine the default
   1749 ** memory allocation for the lookaside memory allocator on each
   1750 ** [database connection].  The first argument is the
   1751 ** size of each lookaside buffer slot and the second is the number of
   1752 ** slots allocated to each database connection.)^  ^(This option sets the
   1753 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
   1754 ** verb to [sqlite3_db_config()] can be used to change the lookaside
   1755 ** configuration on individual connections.)^ </dd>
   1756 **
   1757 ** <dt>SQLITE_CONFIG_PCACHE</dt>
   1758 ** <dd> ^(This option takes a single argument which is a pointer to
   1759 ** an [sqlite3_pcache_methods] object.  This object specifies the interface
   1760 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
   1761 ** object and uses it for page cache memory allocations.</dd>
   1762 **
   1763 ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
   1764 ** <dd> ^(This option takes a single argument which is a pointer to an
   1765 ** [sqlite3_pcache_methods] object.  SQLite copies of the current
   1766 ** page cache implementation into that object.)^ </dd>
   1767 **
   1768 ** </dl>
   1769 */
   1770 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
   1771 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
   1772 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
   1773 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
   1774 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
   1775 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
   1776 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
   1777 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
   1778 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
   1779 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
   1780 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
   1781 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
   1782 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
   1783 #define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
   1784 #define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
   1785 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
   1786 
   1787 /*
   1788 ** CAPI3REF: Configuration Options
   1789 ** EXPERIMENTAL
   1790 **
   1791 ** These constants are the available integer configuration options that
   1792 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
   1793 **
   1794 ** New configuration options may be added in future releases of SQLite.
   1795 ** Existing configuration options might be discontinued.  Applications
   1796 ** should check the return code from [sqlite3_db_config()] to make sure that
   1797 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
   1798 ** non-zero [error code] if a discontinued or unsupported configuration option
   1799 ** is invoked.
   1800 **
   1801 ** <dl>
   1802 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
   1803 ** <dd> ^This option takes three additional arguments that determine the
   1804 ** [lookaside memory allocator] configuration for the [database connection].
   1805 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
   1806 ** pointer to an memory buffer to use for lookaside memory.
   1807 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
   1808 ** may be NULL in which case SQLite will allocate the
   1809 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
   1810 ** size of each lookaside buffer slot.  ^The third argument is the number of
   1811 ** slots.  The size of the buffer in the first argument must be greater than
   1812 ** or equal to the product of the second and third arguments.  The buffer
   1813 ** must be aligned to an 8-byte boundary.  ^If the second argument to
   1814 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
   1815 ** rounded down to the next smaller
   1816 ** multiple of 8.  See also: [SQLITE_CONFIG_LOOKASIDE]</dd>
   1817 **
   1818 ** </dl>
   1819 */
   1820 #define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
   1821 
   1822 
   1823 /*
   1824 ** CAPI3REF: Enable Or Disable Extended Result Codes
   1825 **
   1826 ** ^The sqlite3_extended_result_codes() routine enables or disables the
   1827 ** [extended result codes] feature of SQLite. ^The extended result
   1828 ** codes are disabled by default for historical compatibility.
   1829 */
   1830 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
   1831 
   1832 /*
   1833 ** CAPI3REF: Last Insert Rowid
   1834 **
   1835 ** ^Each entry in an SQLite table has a unique 64-bit signed
   1836 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
   1837 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
   1838 ** names are not also used by explicitly declared columns. ^If
   1839 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
   1840 ** is another alias for the rowid.
   1841 **
   1842 ** ^This routine returns the [rowid] of the most recent
   1843 ** successful [INSERT] into the database from the [database connection]
   1844 ** in the first argument.  ^If no successful [INSERT]s
   1845 ** have ever occurred on that database connection, zero is returned.
   1846 **
   1847 ** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
   1848 ** row is returned by this routine as long as the trigger is running.
   1849 ** But once the trigger terminates, the value returned by this routine
   1850 ** reverts to the last value inserted before the trigger fired.)^
   1851 **
   1852 ** ^An [INSERT] that fails due to a constraint violation is not a
   1853 ** successful [INSERT] and does not change the value returned by this
   1854 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
   1855 ** and INSERT OR ABORT make no changes to the return value of this
   1856 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
   1857 ** encounters a constraint violation, it does not fail.  The
   1858 ** INSERT continues to completion after deleting rows that caused
   1859 ** the constraint problem so INSERT OR REPLACE will always change
   1860 ** the return value of this interface.)^
   1861 **
   1862 ** ^For the purposes of this routine, an [INSERT] is considered to
   1863 ** be successful even if it is subsequently rolled back.
   1864 **
   1865 ** This function is accessible to SQL statements via the
   1866 ** [last_insert_rowid() SQL function].
   1867 **
   1868 ** If a separate thread performs a new [INSERT] on the same
   1869 ** database connection while the [sqlite3_last_insert_rowid()]
   1870 ** function is running and thus changes the last insert [rowid],
   1871 ** then the value returned by [sqlite3_last_insert_rowid()] is
   1872 ** unpredictable and might not equal either the old or the new
   1873 ** last insert [rowid].
   1874 */
   1875 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
   1876 
   1877 /*
   1878 ** CAPI3REF: Count The Number Of Rows Modified
   1879 **
   1880 ** ^This function returns the number of database rows that were changed
   1881 ** or inserted or deleted by the most recently completed SQL statement
   1882 ** on the [database connection] specified by the first parameter.
   1883 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
   1884 ** or [DELETE] statement are counted.  Auxiliary changes caused by
   1885 ** triggers or [foreign key actions] are not counted.)^ Use the
   1886 ** [sqlite3_total_changes()] function to find the total number of changes
   1887 ** including changes caused by triggers and foreign key actions.
   1888 **
   1889 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
   1890 ** are not counted.  Only real table changes are counted.
   1891 **
   1892 ** ^(A "row change" is a change to a single row of a single table
   1893 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
   1894 ** are changed as side effects of [REPLACE] constraint resolution,
   1895 ** rollback, ABORT processing, [DROP TABLE], or by any other
   1896 ** mechanisms do not count as direct row changes.)^
   1897 **
   1898 ** A "trigger context" is a scope of execution that begins and
   1899 ** ends with the script of a [CREATE TRIGGER | trigger].
   1900 ** Most SQL statements are
   1901 ** evaluated outside of any trigger.  This is the "top level"
   1902 ** trigger context.  If a trigger fires from the top level, a
   1903 ** new trigger context is entered for the duration of that one
   1904 ** trigger.  Subtriggers create subcontexts for their duration.
   1905 **
   1906 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
   1907 ** not create a new trigger context.
   1908 **
   1909 ** ^This function returns the number of direct row changes in the
   1910 ** most recent INSERT, UPDATE, or DELETE statement within the same
   1911 ** trigger context.
   1912 **
   1913 ** ^Thus, when called from the top level, this function returns the
   1914 ** number of changes in the most recent INSERT, UPDATE, or DELETE
   1915 ** that also occurred at the top level.  ^(Within the body of a trigger,
   1916 ** the sqlite3_changes() interface can be called to find the number of
   1917 ** changes in the most recently completed INSERT, UPDATE, or DELETE
   1918 ** statement within the body of the same trigger.
   1919 ** However, the number returned does not include changes
   1920 ** caused by subtriggers since those have their own context.)^
   1921 **
   1922 ** See also the [sqlite3_total_changes()] interface, the
   1923 ** [count_changes pragma], and the [changes() SQL function].
   1924 **
   1925 ** If a separate thread makes changes on the same database connection
   1926 ** while [sqlite3_changes()] is running then the value returned
   1927 ** is unpredictable and not meaningful.
   1928 */
   1929 SQLITE_API int sqlite3_changes(sqlite3*);
   1930 
   1931 /*
   1932 ** CAPI3REF: Total Number Of Rows Modified
   1933 **
   1934 ** ^This function returns the number of row changes caused by [INSERT],
   1935 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
   1936 ** ^(The count returned by sqlite3_total_changes() includes all changes
   1937 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
   1938 ** [foreign key actions]. However,
   1939 ** the count does not include changes used to implement [REPLACE] constraints,
   1940 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
   1941 ** count does not include rows of views that fire an [INSTEAD OF trigger],
   1942 ** though if the INSTEAD OF trigger makes changes of its own, those changes
   1943 ** are counted.)^
   1944 ** ^The sqlite3_total_changes() function counts the changes as soon as
   1945 ** the statement that makes them is completed (when the statement handle
   1946 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
   1947 **
   1948 ** See also the [sqlite3_changes()] interface, the
   1949 ** [count_changes pragma], and the [total_changes() SQL function].
   1950 **
   1951 ** If a separate thread makes changes on the same database connection
   1952 ** while [sqlite3_total_changes()] is running then the value
   1953 ** returned is unpredictable and not meaningful.
   1954 */
   1955 SQLITE_API int sqlite3_total_changes(sqlite3*);
   1956 
   1957 /*
   1958 ** CAPI3REF: Interrupt A Long-Running Query
   1959 **
   1960 ** ^This function causes any pending database operation to abort and
   1961 ** return at its earliest opportunity. This routine is typically
   1962 ** called in response to a user action such as pressing "Cancel"
   1963 ** or Ctrl-C where the user wants a long query operation to halt
   1964 ** immediately.
   1965 **
   1966 ** ^It is safe to call this routine from a thread different from the
   1967 ** thread that is currently running the database operation.  But it
   1968 ** is not safe to call this routine with a [database connection] that
   1969 ** is closed or might close before sqlite3_interrupt() returns.
   1970 **
   1971 ** ^If an SQL operation is very nearly finished at the time when
   1972 ** sqlite3_interrupt() is called, then it might not have an opportunity
   1973 ** to be interrupted and might continue to completion.
   1974 **
   1975 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
   1976 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
   1977 ** that is inside an explicit transaction, then the entire transaction
   1978 ** will be rolled back automatically.
   1979 **
   1980 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
   1981 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
   1982 ** that are started after the sqlite3_interrupt() call and before the
   1983 ** running statements reaches zero are interrupted as if they had been
   1984 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
   1985 ** that are started after the running statement count reaches zero are
   1986 ** not effected by the sqlite3_interrupt().
   1987 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
   1988 ** SQL statements is a no-op and has no effect on SQL statements
   1989 ** that are started after the sqlite3_interrupt() call returns.
   1990 **
   1991 ** If the database connection closes while [sqlite3_interrupt()]
   1992 ** is running then bad things will likely happen.
   1993 */
   1994 SQLITE_API void sqlite3_interrupt(sqlite3*);
   1995 
   1996 /*
   1997 ** CAPI3REF: Determine If An SQL Statement Is Complete
   1998 **
   1999 ** These routines are useful during command-line input to determine if the
   2000 ** currently entered text seems to form a complete SQL statement or
   2001 ** if additional input is needed before sending the text into
   2002 ** SQLite for parsing.  ^These routines return 1 if the input string
   2003 ** appears to be a complete SQL statement.  ^A statement is judged to be
   2004 ** complete if it ends with a semicolon token and is not a prefix of a
   2005 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
   2006 ** string literals or quoted identifier names or comments are not
   2007 ** independent tokens (they are part of the token in which they are
   2008 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
   2009 ** and comments that follow the final semicolon are ignored.
   2010 **
   2011 ** ^These routines return 0 if the statement is incomplete.  ^If a
   2012 ** memory allocation fails, then SQLITE_NOMEM is returned.
   2013 **
   2014 ** ^These routines do not parse the SQL statements thus
   2015 ** will not detect syntactically incorrect SQL.
   2016 **
   2017 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
   2018 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
   2019 ** automatically by sqlite3_complete16().  If that initialization fails,
   2020 ** then the return value from sqlite3_complete16() will be non-zero
   2021 ** regardless of whether or not the input SQL is complete.)^
   2022 **
   2023 ** The input to [sqlite3_complete()] must be a zero-terminated
   2024 ** UTF-8 string.
   2025 **
   2026 ** The input to [sqlite3_complete16()] must be a zero-terminated
   2027 ** UTF-16 string in native byte order.
   2028 */
   2029 SQLITE_API int sqlite3_complete(const char *sql);
   2030 SQLITE_API int sqlite3_complete16(const void *sql);
   2031 
   2032 /*
   2033 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
   2034 **
   2035 ** ^This routine sets a callback function that might be invoked whenever
   2036 ** an attempt is made to open a database table that another thread
   2037 ** or process has locked.
   2038 **
   2039 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
   2040 ** is returned immediately upon encountering the lock.  ^If the busy callback
   2041 ** is not NULL, then the callback might be invoked with two arguments.
   2042 **
   2043 ** ^The first argument to the busy handler is a copy of the void* pointer which
   2044 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
   2045 ** the busy handler callback is the number of times that the busy handler has
   2046 ** been invoked for this locking event.  ^If the
   2047 ** busy callback returns 0, then no additional attempts are made to
   2048 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
   2049 ** ^If the callback returns non-zero, then another attempt
   2050 ** is made to open the database for reading and the cycle repeats.
   2051 **
   2052 ** The presence of a busy handler does not guarantee that it will be invoked
   2053 ** when there is lock contention. ^If SQLite determines that invoking the busy
   2054 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
   2055 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
   2056 ** Consider a scenario where one process is holding a read lock that
   2057 ** it is trying to promote to a reserved lock and
   2058 ** a second process is holding a reserved lock that it is trying
   2059 ** to promote to an exclusive lock.  The first process cannot proceed
   2060 ** because it is blocked by the second and the second process cannot
   2061 ** proceed because it is blocked by the first.  If both processes
   2062 ** invoke the busy handlers, neither will make any progress.  Therefore,
   2063 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
   2064 ** will induce the first process to release its read lock and allow
   2065 ** the second process to proceed.
   2066 **
   2067 ** ^The default busy callback is NULL.
   2068 **
   2069 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
   2070 ** when SQLite is in the middle of a large transaction where all the
   2071 ** changes will not fit into the in-memory cache.  SQLite will
   2072 ** already hold a RESERVED lock on the database file, but it needs
   2073 ** to promote this lock to EXCLUSIVE so that it can spill cache
   2074 ** pages into the database file without harm to concurrent
   2075 ** readers.  ^If it is unable to promote the lock, then the in-memory
   2076 ** cache will be left in an inconsistent state and so the error
   2077 ** code is promoted from the relatively benign [SQLITE_BUSY] to
   2078 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
   2079 ** forces an automatic rollback of the changes.  See the
   2080 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
   2081 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
   2082 ** this is important.
   2083 **
   2084 ** ^(There can only be a single busy handler defined for each
   2085 ** [database connection].  Setting a new busy handler clears any
   2086 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
   2087 ** will also set or clear the busy handler.
   2088 **
   2089 ** The busy callback should not take any actions which modify the
   2090 ** database connection that invoked the busy handler.  Any such actions
   2091 ** result in undefined behavior.
   2092 **
   2093 ** A busy handler must not close the database connection
   2094 ** or [prepared statement] that invoked the busy handler.
   2095 */
   2096 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
   2097 
   2098 /*
   2099 ** CAPI3REF: Set A Busy Timeout
   2100 **
   2101 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
   2102 ** for a specified amount of time when a table is locked.  ^The handler
   2103 ** will sleep multiple times until at least "ms" milliseconds of sleeping
   2104 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
   2105 ** the handler returns 0 which causes [sqlite3_step()] to return
   2106 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
   2107 **
   2108 ** ^Calling this routine with an argument less than or equal to zero
   2109 ** turns off all busy handlers.
   2110 **
   2111 ** ^(There can only be a single busy handler for a particular
   2112 ** [database connection] any any given moment.  If another busy handler
   2113 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
   2114 ** this routine, that other busy handler is cleared.)^
   2115 */
   2116 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
   2117 
   2118 /*
   2119 ** CAPI3REF: Convenience Routines For Running Queries
   2120 **
   2121 ** Definition: A <b>result table</b> is memory data structure created by the
   2122 ** [sqlite3_get_table()] interface.  A result table records the
   2123 ** complete query results from one or more queries.
   2124 **
   2125 ** The table conceptually has a number of rows and columns.  But
   2126 ** these numbers are not part of the result table itself.  These
   2127 ** numbers are obtained separately.  Let N be the number of rows
   2128 ** and M be the number of columns.
   2129 **
   2130 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
   2131 ** There are (N+1)*M elements in the array.  The first M pointers point
   2132 ** to zero-terminated strings that  contain the names of the columns.
   2133 ** The remaining entries all point to query results.  NULL values result
   2134 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
   2135 ** string representation as returned by [sqlite3_column_text()].
   2136 **
   2137 ** A result table might consist of one or more memory allocations.
   2138 ** It is not safe to pass a result table directly to [sqlite3_free()].
   2139 ** A result table should be deallocated using [sqlite3_free_table()].
   2140 **
   2141 ** As an example of the result table format, suppose a query result
   2142 ** is as follows:
   2143 **
   2144 ** <blockquote><pre>
   2145 **        Name        | Age
   2146 **        -----------------------
   2147 **        Alice       | 43
   2148 **        Bob         | 28
   2149 **        Cindy       | 21
   2150 ** </pre></blockquote>
   2151 **
   2152 ** There are two column (M==2) and three rows (N==3).  Thus the
   2153 ** result table has 8 entries.  Suppose the result table is stored
   2154 ** in an array names azResult.  Then azResult holds this content:
   2155 **
   2156 ** <blockquote><pre>
   2157 **        azResult&#91;0] = "Name";
   2158 **        azResult&#91;1] = "Age";
   2159 **        azResult&#91;2] = "Alice";
   2160 **        azResult&#91;3] = "43";
   2161 **        azResult&#91;4] = "Bob";
   2162 **        azResult&#91;5] = "28";
   2163 **        azResult&#91;6] = "Cindy";
   2164 **        azResult&#91;7] = "21";
   2165 ** </pre></blockquote>
   2166 **
   2167 ** ^The sqlite3_get_table() function evaluates one or more
   2168 ** semicolon-separated SQL statements in the zero-terminated UTF-8
   2169 ** string of its 2nd parameter and returns a result table to the
   2170 ** pointer given in its 3rd parameter.
   2171 **
   2172 ** After the application has finished with the result from sqlite3_get_table(),
   2173 ** it should pass the result table pointer to sqlite3_free_table() in order to
   2174 ** release the memory that was malloced.  Because of the way the
   2175 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
   2176 ** function must not try to call [sqlite3_free()] directly.  Only
   2177 ** [sqlite3_free_table()] is able to release the memory properly and safely.
   2178 **
   2179 ** ^(The sqlite3_get_table() interface is implemented as a wrapper around
   2180 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
   2181 ** to any internal data structures of SQLite.  It uses only the public
   2182 ** interface defined here.  As a consequence, errors that occur in the
   2183 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
   2184 ** reflected in subsequent calls to [sqlite3_errcode()] or
   2185 ** [sqlite3_errmsg()].)^
   2186 */
   2187 SQLITE_API int sqlite3_get_table(
   2188   sqlite3 *db,          /* An open database */
   2189   const char *zSql,     /* SQL to be evaluated */
   2190   char ***pazResult,    /* Results of the query */
   2191   int *pnRow,           /* Number of result rows written here */
   2192   int *pnColumn,        /* Number of result columns written here */
   2193   char **pzErrmsg       /* Error msg written here */
   2194 );
   2195 SQLITE_API void sqlite3_free_table(char **result);
   2196 
   2197 /*
   2198 ** CAPI3REF: Formatted String Printing Functions
   2199 **
   2200 ** These routines are work-alikes of the "printf()" family of functions
   2201 ** from the standard C library.
   2202 **
   2203 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
   2204 ** results into memory obtained from [sqlite3_malloc()].
   2205 ** The strings returned by these two routines should be
   2206 ** released by [sqlite3_free()].  ^Both routines return a
   2207 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
   2208 ** memory to hold the resulting string.
   2209 **
   2210 ** ^(In sqlite3_snprintf() routine is similar to "snprintf()" from
   2211 ** the standard C library.  The result is written into the
   2212 ** buffer supplied as the second parameter whose size is given by
   2213 ** the first parameter. Note that the order of the
   2214 ** first two parameters is reversed from snprintf().)^  This is an
   2215 ** historical accident that cannot be fixed without breaking
   2216 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
   2217 ** returns a pointer to its buffer instead of the number of
   2218 ** characters actually written into the buffer.)^  We admit that
   2219 ** the number of characters written would be a more useful return
   2220 ** value but we cannot change the implementation of sqlite3_snprintf()
   2221 ** now without breaking compatibility.
   2222 **
   2223 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
   2224 ** guarantees that the buffer is always zero-terminated.  ^The first
   2225 ** parameter "n" is the total size of the buffer, including space for
   2226 ** the zero terminator.  So the longest string that can be completely
   2227 ** written will be n-1 characters.
   2228 **
   2229 ** These routines all implement some additional formatting
   2230 ** options that are useful for constructing SQL statements.
   2231 ** All of the usual printf() formatting options apply.  In addition, there
   2232 ** is are "%q", "%Q", and "%z" options.
   2233 **
   2234 ** ^(The %q option works like %s in that it substitutes a null-terminated
   2235 ** string from the argument list.  But %q also doubles every '\'' character.
   2236 ** %q is designed for use inside a string literal.)^  By doubling each '\''
   2237 ** character it escapes that character and allows it to be inserted into
   2238 ** the string.
   2239 **
   2240 ** For example, assume the string variable zText contains text as follows:
   2241 **
   2242 ** <blockquote><pre>
   2243 **  char *zText = "It's a happy day!";
   2244 ** </pre></blockquote>
   2245 **
   2246 ** One can use this text in an SQL statement as follows:
   2247 **
   2248 ** <blockquote><pre>
   2249 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
   2250 **  sqlite3_exec(db, zSQL, 0, 0, 0);
   2251 **  sqlite3_free(zSQL);
   2252 ** </pre></blockquote>
   2253 **
   2254 ** Because the %q format string is used, the '\'' character in zText
   2255 ** is escaped and the SQL generated is as follows:
   2256 **
   2257 ** <blockquote><pre>
   2258 **  INSERT INTO table1 VALUES('It''s a happy day!')
   2259 ** </pre></blockquote>
   2260 **
   2261 ** This is correct.  Had we used %s instead of %q, the generated SQL
   2262 ** would have looked like this:
   2263 **
   2264 ** <blockquote><pre>
   2265 **  INSERT INTO table1 VALUES('It's a happy day!');
   2266 ** </pre></blockquote>
   2267 **
   2268 ** This second example is an SQL syntax error.  As a general rule you should
   2269 ** always use %q instead of %s when inserting text into a string literal.
   2270 **
   2271 ** ^(The %Q option works like %q except it also adds single quotes around
   2272 ** the outside of the total string.  Additionally, if the parameter in the
   2273 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
   2274 ** single quotes).)^  So, for example, one could say:
   2275 **
   2276 ** <blockquote><pre>
   2277 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
   2278 **  sqlite3_exec(db, zSQL, 0, 0, 0);
   2279 **  sqlite3_free(zSQL);
   2280 ** </pre></blockquote>
   2281 **
   2282 ** The code above will render a correct SQL statement in the zSQL
   2283 ** variable even if the zText variable is a NULL pointer.
   2284 **
   2285 ** ^(The "%z" formatting option works like "%s" but with the
   2286 ** addition that after the string has been read and copied into
   2287 ** the result, [sqlite3_free()] is called on the input string.)^
   2288 */
   2289 SQLITE_API char *sqlite3_mprintf(const char*,...);
   2290 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
   2291 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
   2292 
   2293 /*
   2294 ** CAPI3REF: Memory Allocation Subsystem
   2295 **
   2296 ** The SQLite core uses these three routines for all of its own
   2297 ** internal memory allocation needs. "Core" in the previous sentence
   2298 ** does not include operating-system specific VFS implementation.  The
   2299 ** Windows VFS uses native malloc() and free() for some operations.
   2300 **
   2301 ** ^The sqlite3_malloc() routine returns a pointer to a block
   2302 ** of memory at least N bytes in length, where N is the parameter.
   2303 ** ^If sqlite3_malloc() is unable to obtain sufficient free
   2304 ** memory, it returns a NULL pointer.  ^If the parameter N to
   2305 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
   2306 ** a NULL pointer.
   2307 **
   2308 ** ^Calling sqlite3_free() with a pointer previously returned
   2309 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
   2310 ** that it might be reused.  ^The sqlite3_free() routine is
   2311 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
   2312 ** to sqlite3_free() is harmless.  After being freed, memory
   2313 ** should neither be read nor written.  Even reading previously freed
   2314 ** memory might result in a segmentation fault or other severe error.
   2315 ** Memory corruption, a segmentation fault, or other severe error
   2316 ** might result if sqlite3_free() is called with a non-NULL pointer that
   2317 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
   2318 **
   2319 ** ^(The sqlite3_realloc() interface attempts to resize a
   2320 ** prior memory allocation to be at least N bytes, where N is the
   2321 ** second parameter.  The memory allocation to be resized is the first
   2322 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
   2323 ** is a NULL pointer then its behavior is identical to calling
   2324 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
   2325 ** ^If the second parameter to sqlite3_realloc() is zero or
   2326 ** negative then the behavior is exactly the same as calling
   2327 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
   2328 ** ^sqlite3_realloc() returns a pointer to a memory allocation
   2329 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
   2330 ** ^If M is the size of the prior allocation, then min(N,M) bytes
   2331 ** of the prior allocation are copied into the beginning of buffer returned
   2332 ** by sqlite3_realloc() and the prior allocation is freed.
   2333 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
   2334 ** is not freed.
   2335 **
   2336 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
   2337 ** is always aligned to at least an 8 byte boundary.
   2338 **
   2339 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
   2340 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
   2341 ** implementation of these routines to be omitted.  That capability
   2342 ** is no longer provided.  Only built-in memory allocators can be used.
   2343 **
   2344 ** The Windows OS interface layer calls
   2345 ** the system malloc() and free() directly when converting
   2346 ** filenames between the UTF-8 encoding used by SQLite
   2347 ** and whatever filename encoding is used by the particular Windows
   2348 ** installation.  Memory allocation errors are detected, but
   2349 ** they are reported back as [SQLITE_CANTOPEN] or
   2350 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
   2351 **
   2352 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
   2353 ** must be either NULL or else pointers obtained from a prior
   2354 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
   2355 ** not yet been released.
   2356 **
   2357 ** The application must not read or write any part of
   2358 ** a block of memory after it has been released using
   2359 ** [sqlite3_free()] or [sqlite3_realloc()].
   2360 */
   2361 SQLITE_API void *sqlite3_malloc(int);
   2362 SQLITE_API void *sqlite3_realloc(void*, int);
   2363 SQLITE_API void sqlite3_free(void*);
   2364 
   2365 /*
   2366 ** CAPI3REF: Memory Allocator Statistics
   2367 **
   2368 ** SQLite provides these two interfaces for reporting on the status
   2369 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
   2370 ** routines, which form the built-in memory allocation subsystem.
   2371 **
   2372 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
   2373 ** of memory currently outstanding (malloced but not freed).
   2374 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
   2375 ** value of [sqlite3_memory_used()] since the high-water mark
   2376 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
   2377 ** [sqlite3_memory_highwater()] include any overhead
   2378 ** added by SQLite in its implementation of [sqlite3_malloc()],
   2379 ** but not overhead added by the any underlying system library
   2380 ** routines that [sqlite3_malloc()] may call.
   2381 **
   2382 ** ^The memory high-water mark is reset to the current value of
   2383 ** [sqlite3_memory_used()] if and only if the parameter to
   2384 ** [sqlite3_memory_highwater()] is true.  ^The value returned
   2385 ** by [sqlite3_memory_highwater(1)] is the high-water mark
   2386 ** prior to the reset.
   2387 */
   2388 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
   2389 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
   2390 
   2391 /*
   2392 ** CAPI3REF: Pseudo-Random Number Generator
   2393 **
   2394 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
   2395 ** select random [ROWID | ROWIDs] when inserting new records into a table that
   2396 ** already uses the largest possible [ROWID].  The PRNG is also used for
   2397 ** the build-in random() and randomblob() SQL functions.  This interface allows
   2398 ** applications to access the same PRNG for other purposes.
   2399 **
   2400 ** ^A call to this routine stores N bytes of randomness into buffer P.
   2401 **
   2402 ** ^The first time this routine is invoked (either internally or by
   2403 ** the application) the PRNG is seeded using randomness obtained
   2404 ** from the xRandomness method of the default [sqlite3_vfs] object.
   2405 ** ^On all subsequent invocations, the pseudo-randomness is generated
   2406 ** internally and without recourse to the [sqlite3_vfs] xRandomness
   2407 ** method.
   2408 */
   2409 SQLITE_API void sqlite3_randomness(int N, void *P);
   2410 
   2411 /*
   2412 ** CAPI3REF: Compile-Time Authorization Callbacks
   2413 **
   2414 ** ^This routine registers a authorizer callback with a particular
   2415 ** [database connection], supplied in the first argument.
   2416 ** ^The authorizer callback is invoked as SQL statements are being compiled
   2417 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
   2418 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
   2419 ** points during the compilation process, as logic is being created
   2420 ** to perform various actions, the authorizer callback is invoked to
   2421 ** see if those actions are allowed.  ^The authorizer callback should
   2422 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
   2423 ** specific action but allow the SQL statement to continue to be
   2424 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
   2425 ** rejected with an error.  ^If the authorizer callback returns
   2426 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
   2427 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
   2428 ** the authorizer will fail with an error message.
   2429 **
   2430 ** When the callback returns [SQLITE_OK], that means the operation
   2431 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
   2432 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
   2433 ** authorizer will fail with an error message explaining that
   2434 ** access is denied.
   2435 **
   2436 ** ^The first parameter to the authorizer callback is a copy of the third
   2437 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
   2438 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
   2439 ** the particular action to be authorized. ^The third through sixth parameters
   2440 ** to the callback are zero-terminated strings that contain additional
   2441 ** details about the action to be authorized.
   2442 **
   2443 ** ^If the action code is [SQLITE_READ]
   2444 ** and the callback returns [SQLITE_IGNORE] then the
   2445 ** [prepared statement] statement is constructed to substitute
   2446 ** a NULL value in place of the table column that would have
   2447 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
   2448 ** return can be used to deny an untrusted user access to individual
   2449 ** columns of a table.
   2450 ** ^If the action code is [SQLITE_DELETE] and the callback returns
   2451 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
   2452 ** [truncate optimization] is disabled and all rows are deleted individually.
   2453 **
   2454 ** An authorizer is used when [sqlite3_prepare | preparing]
   2455 ** SQL statements from an untrusted source, to ensure that the SQL statements
   2456 ** do not try to access data they are not allowed to see, or that they do not
   2457 ** try to execute malicious statements that damage the database.  For
   2458 ** example, an application may allow a user to enter arbitrary
   2459 ** SQL queries for evaluation by a database.  But the application does
   2460 ** not want the user to be able to make arbitrary changes to the
   2461 ** database.  An authorizer could then be put in place while the
   2462 ** user-entered SQL is being [sqlite3_prepare | prepared] that
   2463 ** disallows everything except [SELECT] statements.
   2464 **
   2465 ** Applications that need to process SQL from untrusted sources
   2466 ** might also consider lowering resource limits using [sqlite3_limit()]
   2467 ** and limiting database size using the [max_page_count] [PRAGMA]
   2468 ** in addition to using an authorizer.
   2469 **
   2470 ** ^(Only a single authorizer can be in place on a database connection
   2471 ** at a time.  Each call to sqlite3_set_authorizer overrides the
   2472 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
   2473 ** The authorizer is disabled by default.
   2474 **
   2475 ** The authorizer callback must not do anything that will modify
   2476 ** the database connection that invoked the authorizer callback.
   2477 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   2478 ** database connections for the meaning of "modify" in this paragraph.
   2479 **
   2480 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
   2481 ** statement might be re-prepared during [sqlite3_step()] due to a
   2482 ** schema change.  Hence, the application should ensure that the
   2483 ** correct authorizer callback remains in place during the [sqlite3_step()].
   2484 **
   2485 ** ^Note that the authorizer callback is invoked only during
   2486 ** [sqlite3_prepare()] or its variants.  Authorization is not
   2487 ** performed during statement evaluation in [sqlite3_step()], unless
   2488 ** as stated in the previous paragraph, sqlite3_step() invokes
   2489 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
   2490 */
   2491 SQLITE_API int sqlite3_set_authorizer(
   2492   sqlite3*,
   2493   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
   2494   void *pUserData
   2495 );
   2496 
   2497 /*
   2498 ** CAPI3REF: Authorizer Return Codes
   2499 **
   2500 ** The [sqlite3_set_authorizer | authorizer callback function] must
   2501 ** return either [SQLITE_OK] or one of these two constants in order
   2502 ** to signal SQLite whether or not the action is permitted.  See the
   2503 ** [sqlite3_set_authorizer | authorizer documentation] for additional
   2504 ** information.
   2505 */
   2506 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
   2507 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
   2508 
   2509 /*
   2510 ** CAPI3REF: Authorizer Action Codes
   2511 **
   2512 ** The [sqlite3_set_authorizer()] interface registers a callback function
   2513 ** that is invoked to authorize certain SQL statement actions.  The
   2514 ** second parameter to the callback is an integer code that specifies
   2515 ** what action is being authorized.  These are the integer action codes that
   2516 ** the authorizer callback may be passed.
   2517 **
   2518 ** These action code values signify what kind of operation is to be
   2519 ** authorized.  The 3rd and 4th parameters to the authorization
   2520 ** callback function will be parameters or NULL depending on which of these
   2521 ** codes is used as the second parameter.  ^(The 5th parameter to the
   2522 ** authorizer callback is the name of the database ("main", "temp",
   2523 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
   2524 ** is the name of the inner-most trigger or view that is responsible for
   2525 ** the access attempt or NULL if this access attempt is directly from
   2526 ** top-level SQL code.
   2527 */
   2528 /******************************************* 3rd ************ 4th ***********/
   2529 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
   2530 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
   2531 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
   2532 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
   2533 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
   2534 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
   2535 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
   2536 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
   2537 #define SQLITE_DELETE                9   /* Table Name      NULL            */
   2538 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
   2539 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
   2540 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
   2541 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
   2542 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
   2543 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
   2544 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
   2545 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
   2546 #define SQLITE_INSERT               18   /* Table Name      NULL            */
   2547 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
   2548 #define SQLITE_READ                 20   /* Table Name      Column Name     */
   2549 #define SQLITE_SELECT               21   /* NULL            NULL            */
   2550 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
   2551 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
   2552 #define SQLITE_ATTACH               24   /* Filename        NULL            */
   2553 #define SQLITE_DETACH               25   /* Database Name   NULL            */
   2554 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
   2555 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
   2556 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
   2557 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
   2558 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
   2559 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
   2560 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
   2561 #define SQLITE_COPY                  0   /* No longer used */
   2562 
   2563 /*
   2564 ** CAPI3REF: Tracing And Profiling Functions
   2565 ** EXPERIMENTAL
   2566 **
   2567 ** These routines register callback functions that can be used for
   2568 ** tracing and profiling the execution of SQL statements.
   2569 **
   2570 ** ^The callback function registered by sqlite3_trace() is invoked at
   2571 ** various times when an SQL statement is being run by [sqlite3_step()].
   2572 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
   2573 ** SQL statement text as the statement first begins executing.
   2574 ** ^(Additional sqlite3_trace() callbacks might occur
   2575 ** as each triggered subprogram is entered.  The callbacks for triggers
   2576 ** contain a UTF-8 SQL comment that identifies the trigger.)^
   2577 **
   2578 ** ^The callback function registered by sqlite3_profile() is invoked
   2579 ** as each SQL statement finishes.  ^The profile callback contains
   2580 ** the original statement text and an estimate of wall-clock time
   2581 ** of how long that statement took to run.
   2582 */
   2583 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
   2584 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
   2585    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
   2586 
   2587 /*
   2588 ** CAPI3REF: Query Progress Callbacks
   2589 **
   2590 ** ^This routine configures a callback function - the
   2591 ** progress callback - that is invoked periodically during long
   2592 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
   2593 ** [sqlite3_get_table()].  An example use for this
   2594 ** interface is to keep a GUI updated during a large query.
   2595 **
   2596 ** ^If the progress callback returns non-zero, the operation is
   2597 ** interrupted.  This feature can be used to implement a
   2598 ** "Cancel" button on a GUI progress dialog box.
   2599 **
   2600 ** The progress handler must not do anything that will modify
   2601 ** the database connection that invoked the progress handler.
   2602 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   2603 ** database connections for the meaning of "modify" in this paragraph.
   2604 **
   2605 */
   2606 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
   2607 
   2608 /*
   2609 ** CAPI3REF: Opening A New Database Connection
   2610 **
   2611 ** ^These routines open an SQLite database file whose name is given by the
   2612 ** filename argument. ^The filename argument is interpreted as UTF-8 for
   2613 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
   2614 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
   2615 ** returned in *ppDb, even if an error occurs.  The only exception is that
   2616 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
   2617 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
   2618 ** object.)^ ^(If the database is opened (and/or created) successfully, then
   2619 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
   2620 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
   2621 ** an English language description of the error following a failure of any
   2622 ** of the sqlite3_open() routines.
   2623 **
   2624 ** ^The default encoding for the database will be UTF-8 if
   2625 ** sqlite3_open() or sqlite3_open_v2() is called and
   2626 ** UTF-16 in the native byte order if sqlite3_open16() is used.
   2627 **
   2628 ** Whether or not an error occurs when it is opened, resources
   2629 ** associated with the [database connection] handle should be released by
   2630 ** passing it to [sqlite3_close()] when it is no longer required.
   2631 **
   2632 ** The sqlite3_open_v2() interface works like sqlite3_open()
   2633 ** except that it accepts two additional parameters for additional control
   2634 ** over the new database connection.  ^(The flags parameter to
   2635 ** sqlite3_open_v2() can take one of
   2636 ** the following three values, optionally combined with the
   2637 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
   2638 ** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
   2639 **
   2640 ** <dl>
   2641 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
   2642 ** <dd>The database is opened in read-only mode.  If the database does not
   2643 ** already exist, an error is returned.</dd>)^
   2644 **
   2645 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
   2646 ** <dd>The database is opened for reading and writing if possible, or reading
   2647 ** only if the file is write protected by the operating system.  In either
   2648 ** case the database must already exist, otherwise an error is returned.</dd>)^
   2649 **
   2650 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
   2651 ** <dd>The database is opened for reading and writing, and is creates it if
   2652 ** it does not already exist. This is the behavior that is always used for
   2653 ** sqlite3_open() and sqlite3_open16().</dd>)^
   2654 ** </dl>
   2655 **
   2656 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
   2657 ** combinations shown above or one of the combinations shown above combined
   2658 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
   2659 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
   2660 ** then the behavior is undefined.
   2661 **
   2662 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
   2663 ** opens in the multi-thread [threading mode] as long as the single-thread
   2664 ** mode has not been set at compile-time or start-time.  ^If the
   2665 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
   2666 ** in the serialized [threading mode] unless single-thread was
   2667 ** previously selected at compile-time or start-time.
   2668 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
   2669 ** eligible to use [shared cache mode], regardless of whether or not shared
   2670 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
   2671 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
   2672 ** participate in [shared cache mode] even if it is enabled.
   2673 **
   2674 ** ^If the filename is ":memory:", then a private, temporary in-memory database
   2675 ** is created for the connection.  ^This in-memory database will vanish when
   2676 ** the database connection is closed.  Future versions of SQLite might
   2677 ** make use of additional special filenames that begin with the ":" character.
   2678 ** It is recommended that when a database filename actually does begin with
   2679 ** a ":" character you should prefix the filename with a pathname such as
   2680 ** "./" to avoid ambiguity.
   2681 **
   2682 ** ^If the filename is an empty string, then a private, temporary
   2683 ** on-disk database will be created.  ^This private database will be
   2684 ** automatically deleted as soon as the database connection is closed.
   2685 **
   2686 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
   2687 ** [sqlite3_vfs] object that defines the operating system interface that
   2688 ** the new database connection should use.  ^If the fourth parameter is
   2689 ** a NULL pointer then the default [sqlite3_vfs] object is used.
   2690 **
   2691 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
   2692 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
   2693 ** codepage is currently defined.  Filenames containing international
   2694 ** characters must be converted to UTF-8 prior to passing them into
   2695 ** sqlite3_open() or sqlite3_open_v2().
   2696 */
   2697 SQLITE_API int sqlite3_open(
   2698   const char *filename,   /* Database filename (UTF-8) */
   2699   sqlite3 **ppDb          /* OUT: SQLite db handle */
   2700 );
   2701 SQLITE_API int sqlite3_open16(
   2702   const void *filename,   /* Database filename (UTF-16) */
   2703   sqlite3 **ppDb          /* OUT: SQLite db handle */
   2704 );
   2705 SQLITE_API int sqlite3_open_v2(
   2706   const char *filename,   /* Database filename (UTF-8) */
   2707   sqlite3 **ppDb,         /* OUT: SQLite db handle */
   2708   int flags,              /* Flags */
   2709   const char *zVfs        /* Name of VFS module to use */
   2710 );
   2711 
   2712 /*
   2713 ** CAPI3REF: Error Codes And Messages
   2714 **
   2715 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
   2716 ** [extended result code] for the most recent failed sqlite3_* API call
   2717 ** associated with a [database connection]. If a prior API call failed
   2718 ** but the most recent API call succeeded, the return value from
   2719 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
   2720 ** interface is the same except that it always returns the
   2721 ** [extended result code] even when extended result codes are
   2722 ** disabled.
   2723 **
   2724 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
   2725 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
   2726 ** ^(Memory to hold the error message string is managed internally.
   2727 ** The application does not need to worry about freeing the result.
   2728 ** However, the error string might be overwritten or deallocated by
   2729 ** subsequent calls to other SQLite interface functions.)^
   2730 **
   2731 ** When the serialized [threading mode] is in use, it might be the
   2732 ** case that a second error occurs on a separate thread in between
   2733 ** the time of the first error and the call to these interfaces.
   2734 ** When that happens, the second error will be reported since these
   2735 ** interfaces always report the most recent result.  To avoid
   2736 ** this, each thread can obtain exclusive use of the [database connection] D
   2737 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
   2738 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
   2739 ** all calls to the interfaces listed here are completed.
   2740 **
   2741 ** If an interface fails with SQLITE_MISUSE, that means the interface
   2742 ** was invoked incorrectly by the application.  In that case, the
   2743 ** error code and message may or may not be set.
   2744 */
   2745 SQLITE_API int sqlite3_errcode(sqlite3 *db);
   2746 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
   2747 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
   2748 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
   2749 
   2750 /*
   2751 ** CAPI3REF: SQL Statement Object
   2752 ** KEYWORDS: {prepared statement} {prepared statements}
   2753 **
   2754 ** An instance of this object represents a single SQL statement.
   2755 ** This object is variously known as a "prepared statement" or a
   2756 ** "compiled SQL statement" or simply as a "statement".
   2757 **
   2758 ** The life of a statement object goes something like this:
   2759 **
   2760 ** <ol>
   2761 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
   2762 **      function.
   2763 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
   2764 **      interfaces.
   2765 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
   2766 ** <li> Reset the statement using [sqlite3_reset()] then go back
   2767 **      to step 2.  Do this zero or more times.
   2768 ** <li> Destroy the object using [sqlite3_finalize()].
   2769 ** </ol>
   2770 **
   2771 ** Refer to documentation on individual methods above for additional
   2772 ** information.
   2773 */
   2774 typedef struct sqlite3_stmt sqlite3_stmt;
   2775 
   2776 /*
   2777 ** CAPI3REF: Run-time Limits
   2778 **
   2779 ** ^(This interface allows the size of various constructs to be limited
   2780 ** on a connection by connection basis.  The first parameter is the
   2781 ** [database connection] whose limit is to be set or queried.  The
   2782 ** second parameter is one of the [limit categories] that define a
   2783 ** class of constructs to be size limited.  The third parameter is the
   2784 ** new limit for that construct.  The function returns the old limit.)^
   2785 **
   2786 ** ^If the new limit is a negative number, the limit is unchanged.
   2787 ** ^(For the limit category of SQLITE_LIMIT_XYZ there is a
   2788 ** [limits | hard upper bound]
   2789 ** set by a compile-time C preprocessor macro named
   2790 ** [limits | SQLITE_MAX_XYZ].
   2791 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
   2792 ** ^Attempts to increase a limit above its hard upper bound are
   2793 ** silently truncated to the hard upper bound.
   2794 **
   2795 ** Run-time limits are intended for use in applications that manage
   2796 ** both their own internal database and also databases that are controlled
   2797 ** by untrusted external sources.  An example application might be a
   2798 ** web browser that has its own databases for storing history and
   2799 ** separate databases controlled by JavaScript applications downloaded
   2800 ** off the Internet.  The internal databases can be given the
   2801 ** large, default limits.  Databases managed by external sources can
   2802 ** be given much smaller limits designed to prevent a denial of service
   2803 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
   2804 ** interface to further control untrusted SQL.  The size of the database
   2805 ** created by an untrusted script can be contained using the
   2806 ** [max_page_count] [PRAGMA].
   2807 **
   2808 ** New run-time limit categories may be added in future releases.
   2809 */
   2810 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
   2811 
   2812 /*
   2813 ** CAPI3REF: Run-Time Limit Categories
   2814 ** KEYWORDS: {limit category} {*limit categories}
   2815 **
   2816 ** These constants define various performance limits
   2817 ** that can be lowered at run-time using [sqlite3_limit()].
   2818 ** The synopsis of the meanings of the various limits is shown below.
   2819 ** Additional information is available at [limits | Limits in SQLite].
   2820 **
   2821 ** <dl>
   2822 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
   2823 ** <dd>The maximum size of any string or BLOB or table row.<dd>)^
   2824 **
   2825 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
   2826 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
   2827 **
   2828 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
   2829 ** <dd>The maximum number of columns in a table definition or in the
   2830 ** result set of a [SELECT] or the maximum number of columns in an index
   2831 ** or in an ORDER BY or GROUP BY clause.</dd>)^
   2832 **
   2833 ** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
   2834 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
   2835 **
   2836 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
   2837 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
   2838 **
   2839 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
   2840 ** <dd>The maximum number of instructions in a virtual machine program
   2841 ** used to implement an SQL statement.</dd>)^
   2842 **
   2843 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
   2844 ** <dd>The maximum number of arguments on a function.</dd>)^
   2845 **
   2846 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
   2847 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
   2848 **
   2849 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
   2850 ** <dd>The maximum length of the pattern argument to the [LIKE] or
   2851 ** [GLOB] operators.</dd>)^
   2852 **
   2853 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
   2854 ** <dd>The maximum number of variables in an SQL statement that can
   2855 ** be bound.</dd>)^
   2856 **
   2857 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
   2858 ** <dd>The maximum depth of recursion for triggers.</dd>)^
   2859 ** </dl>
   2860 */
   2861 #define SQLITE_LIMIT_LENGTH                    0
   2862 #define SQLITE_LIMIT_SQL_LENGTH                1
   2863 #define SQLITE_LIMIT_COLUMN                    2
   2864 #define SQLITE_LIMIT_EXPR_DEPTH                3
   2865 #define SQLITE_LIMIT_COMPOUND_SELECT           4
   2866 #define SQLITE_LIMIT_VDBE_OP                   5
   2867 #define SQLITE_LIMIT_FUNCTION_ARG              6
   2868 #define SQLITE_LIMIT_ATTACHED                  7
   2869 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
   2870 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
   2871 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
   2872 
   2873 /*
   2874 ** CAPI3REF: Compiling An SQL Statement
   2875 ** KEYWORDS: {SQL statement compiler}
   2876 **
   2877 ** To execute an SQL query, it must first be compiled into a byte-code
   2878 ** program using one of these routines.
   2879 **
   2880 ** The first argument, "db", is a [database connection] obtained from a
   2881 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
   2882 ** [sqlite3_open16()].  The database connection must not have been closed.
   2883 **
   2884 ** The second argument, "zSql", is the statement to be compiled, encoded
   2885 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
   2886 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
   2887 ** use UTF-16.
   2888 **
   2889 ** ^If the nByte argument is less than zero, then zSql is read up to the
   2890 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
   2891 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
   2892 ** zSql string ends at either the first '\000' or '\u0000' character or
   2893 ** the nByte-th byte, whichever comes first. If the caller knows
   2894 ** that the supplied string is nul-terminated, then there is a small
   2895 ** performance advantage to be gained by passing an nByte parameter that
   2896 ** is equal to the number of bytes in the input string <i>including</i>
   2897 ** the nul-terminator bytes.
   2898 **
   2899 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
   2900 ** past the end of the first SQL statement in zSql.  These routines only
   2901 ** compile the first statement in zSql, so *pzTail is left pointing to
   2902 ** what remains uncompiled.
   2903 **
   2904 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
   2905 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
   2906 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
   2907 ** string or a comment) then *ppStmt is set to NULL.
   2908 ** The calling procedure is responsible for deleting the compiled
   2909 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
   2910 ** ppStmt may not be NULL.
   2911 **
   2912 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
   2913 ** otherwise an [error code] is returned.
   2914 **
   2915 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
   2916 ** recommended for all new programs. The two older interfaces are retained
   2917 ** for backwards compatibility, but their use is discouraged.
   2918 ** ^In the "v2" interfaces, the prepared statement
   2919 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
   2920 ** original SQL text. This causes the [sqlite3_step()] interface to
   2921 ** behave differently in three ways:
   2922 **
   2923 ** <ol>
   2924 ** <li>
   2925 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
   2926 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
   2927 ** statement and try to run it again.  ^If the schema has changed in
   2928 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
   2929 ** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
   2930 ** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
   2931 ** error go away.  Note: use [sqlite3_errmsg()] to find the text
   2932 ** of the parsing error that results in an [SQLITE_SCHEMA] return.
   2933 ** </li>
   2934 **
   2935 ** <li>
   2936 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
   2937 ** [error codes] or [extended error codes].  ^The legacy behavior was that
   2938 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
   2939 ** and the application would have to make a second call to [sqlite3_reset()]
   2940 ** in order to find the underlying cause of the problem. With the "v2" prepare
   2941 ** interfaces, the underlying reason for the error is returned immediately.
   2942 ** </li>
   2943 **
   2944 ** <li>
   2945 ** ^If the value of a [parameter | host parameter] in the WHERE clause might
   2946 ** change the query plan for a statement, then the statement may be
   2947 ** automatically recompiled (as if there had been a schema change) on the first
   2948 ** [sqlite3_step()] call following any change to the
   2949 ** [sqlite3_bind_text | bindings] of the [parameter].
   2950 ** </li>
   2951 ** </ol>
   2952 */
   2953 SQLITE_API int sqlite3_prepare(
   2954   sqlite3 *db,            /* Database handle */
   2955   const char *zSql,       /* SQL statement, UTF-8 encoded */
   2956   int nByte,              /* Maximum length of zSql in bytes. */
   2957   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   2958   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
   2959 );
   2960 SQLITE_API int sqlite3_prepare_v2(
   2961   sqlite3 *db,            /* Database handle */
   2962   const char *zSql,       /* SQL statement, UTF-8 encoded */
   2963   int nByte,              /* Maximum length of zSql in bytes. */
   2964   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   2965   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
   2966 );
   2967 SQLITE_API int sqlite3_prepare16(
   2968   sqlite3 *db,            /* Database handle */
   2969   const void *zSql,       /* SQL statement, UTF-16 encoded */
   2970   int nByte,              /* Maximum length of zSql in bytes. */
   2971   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   2972   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
   2973 );
   2974 SQLITE_API int sqlite3_prepare16_v2(
   2975   sqlite3 *db,            /* Database handle */
   2976   const void *zSql,       /* SQL statement, UTF-16 encoded */
   2977   int nByte,              /* Maximum length of zSql in bytes. */
   2978   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   2979   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
   2980 );
   2981 
   2982 /*
   2983 ** CAPI3REF: Retrieving Statement SQL
   2984 **
   2985 ** ^This interface can be used to retrieve a saved copy of the original
   2986 ** SQL text used to create a [prepared statement] if that statement was
   2987 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
   2988 */
   2989 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
   2990 
   2991 /*
   2992 ** CAPI3REF: Dynamically Typed Value Object
   2993 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
   2994 **
   2995 ** SQLite uses the sqlite3_value object to represent all values
   2996 ** that can be stored in a database table. SQLite uses dynamic typing
   2997 ** for the values it stores.  ^Values stored in sqlite3_value objects
   2998 ** can be integers, floating point values, strings, BLOBs, or NULL.
   2999 **
   3000 ** An sqlite3_value object may be either "protected" or "unprotected".
   3001 ** Some interfaces require a protected sqlite3_value.  Other interfaces
   3002 ** will accept either a protected or an unprotected sqlite3_value.
   3003 ** Every interface that accepts sqlite3_value arguments specifies
   3004 ** whether or not it requires a protected sqlite3_value.
   3005 **
   3006 ** The terms "protected" and "unprotected" refer to whether or not
   3007 ** a mutex is held.  A internal mutex is held for a protected
   3008 ** sqlite3_value object but no mutex is held for an unprotected
   3009 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
   3010 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
   3011 ** or if SQLite is run in one of reduced mutex modes
   3012 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
   3013 ** then there is no distinction between protected and unprotected
   3014 ** sqlite3_value objects and they can be used interchangeably.  However,
   3015 ** for maximum code portability it is recommended that applications
   3016 ** still make the distinction between between protected and unprotected
   3017 ** sqlite3_value objects even when not strictly required.
   3018 **
   3019 ** ^The sqlite3_value objects that are passed as parameters into the
   3020 ** implementation of [application-defined SQL functions] are protected.
   3021 ** ^The sqlite3_value object returned by
   3022 ** [sqlite3_column_value()] is unprotected.
   3023 ** Unprotected sqlite3_value objects may only be used with
   3024 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
   3025 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
   3026 ** interfaces require protected sqlite3_value objects.
   3027 */
   3028 typedef struct Mem sqlite3_value;
   3029 
   3030 /*
   3031 ** CAPI3REF: SQL Function Context Object
   3032 **
   3033 ** The context in which an SQL function executes is stored in an
   3034 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
   3035 ** is always first parameter to [application-defined SQL functions].
   3036 ** The application-defined SQL function implementation will pass this
   3037 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
   3038 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
   3039 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
   3040 ** and/or [sqlite3_set_auxdata()].
   3041 */
   3042 typedef struct sqlite3_context sqlite3_context;
   3043 
   3044 /*
   3045 ** CAPI3REF: Binding Values To Prepared Statements
   3046 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
   3047 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
   3048 **
   3049 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
   3050 ** literals may be replaced by a [parameter] that matches one of following
   3051 ** templates:
   3052 **
   3053 ** <ul>
   3054 ** <li>  ?
   3055 ** <li>  ?NNN
   3056 ** <li>  :VVV
   3057 ** <li>  @VVV
   3058 ** <li>  $VVV
   3059 ** </ul>
   3060 **
   3061 ** In the templates above, NNN represents an integer literal,
   3062 ** and VVV represents an alphanumeric identifer.)^  ^The values of these
   3063 ** parameters (also called "host parameter names" or "SQL parameters")
   3064 ** can be set using the sqlite3_bind_*() routines defined here.
   3065 **
   3066 ** ^The first argument to the sqlite3_bind_*() routines is always
   3067 ** a pointer to the [sqlite3_stmt] object returned from
   3068 ** [sqlite3_prepare_v2()] or its variants.
   3069 **
   3070 ** ^The second argument is the index of the SQL parameter to be set.
   3071 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
   3072 ** SQL parameter is used more than once, second and subsequent
   3073 ** occurrences have the same index as the first occurrence.
   3074 ** ^The index for named parameters can be looked up using the
   3075 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
   3076 ** for "?NNN" parameters is the value of NNN.
   3077 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
   3078 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
   3079 **
   3080 ** ^The third argument is the value to bind to the parameter.
   3081 **
   3082 ** ^(In those routines that have a fourth argument, its value is the
   3083 ** number of bytes in the parameter.  To be clear: the value is the
   3084 ** number of <u>bytes</u> in the value, not the number of characters.)^
   3085 ** ^If the fourth parameter is negative, the length of the string is
   3086 ** the number of bytes up to the first zero terminator.
   3087 **
   3088 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
   3089 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
   3090 ** string after SQLite has finished with it. ^If the fifth argument is
   3091 ** the special value [SQLITE_STATIC], then SQLite assumes that the
   3092 ** information is in static, unmanaged space and does not need to be freed.
   3093 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
   3094 ** SQLite makes its own private copy of the data immediately, before
   3095 ** the sqlite3_bind_*() routine returns.
   3096 **
   3097 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
   3098 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
   3099 ** (just an integer to hold its size) while it is being processed.
   3100 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
   3101 ** content is later written using
   3102 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
   3103 ** ^A negative value for the zeroblob results in a zero-length BLOB.
   3104 **
   3105 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
   3106 ** for the [prepared statement] or with a prepared statement for which
   3107 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
   3108 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
   3109 ** routine is passed a [prepared statement] that has been finalized, the
   3110 ** result is undefined and probably harmful.
   3111 **
   3112 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
   3113 ** ^Unbound parameters are interpreted as NULL.
   3114 **
   3115 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
   3116 ** [error code] if anything goes wrong.
   3117 ** ^[SQLITE_RANGE] is returned if the parameter
   3118 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
   3119 **
   3120 ** See also: [sqlite3_bind_parameter_count()],
   3121 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
   3122 */
   3123 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
   3124 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
   3125 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
   3126 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
   3127 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
   3128 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
   3129 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
   3130 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
   3131 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
   3132 
   3133 /*
   3134 ** CAPI3REF: Number Of SQL Parameters
   3135 **
   3136 ** ^This routine can be used to find the number of [SQL parameters]
   3137 ** in a [prepared statement].  SQL parameters are tokens of the
   3138 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
   3139 ** placeholders for values that are [sqlite3_bind_blob | bound]
   3140 ** to the parameters at a later time.
   3141 **
   3142 ** ^(This routine actually returns the index of the largest (rightmost)
   3143 ** parameter. For all forms except ?NNN, this will correspond to the
   3144 ** number of unique parameters.  If parameters of the ?NNN form are used,
   3145 ** there may be gaps in the list.)^
   3146 **
   3147 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   3148 ** [sqlite3_bind_parameter_name()], and
   3149 ** [sqlite3_bind_parameter_index()].
   3150 */
   3151 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
   3152 
   3153 /*
   3154 ** CAPI3REF: Name Of A Host Parameter
   3155 **
   3156 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
   3157 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
   3158 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
   3159 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
   3160 ** respectively.
   3161 ** In other words, the initial ":" or "$" or "@" or "?"
   3162 ** is included as part of the name.)^
   3163 ** ^Parameters of the form "?" without a following integer have no name
   3164 ** and are referred to as "nameless" or "anonymous parameters".
   3165 **
   3166 ** ^The first host parameter has an index of 1, not 0.
   3167 **
   3168 ** ^If the value N is out of range or if the N-th parameter is
   3169 ** nameless, then NULL is returned.  ^The returned string is
   3170 ** always in UTF-8 encoding even if the named parameter was
   3171 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
   3172 ** [sqlite3_prepare16_v2()].
   3173 **
   3174 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   3175 ** [sqlite3_bind_parameter_count()], and
   3176 ** [sqlite3_bind_parameter_index()].
   3177 */
   3178 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
   3179 
   3180 /*
   3181 ** CAPI3REF: Index Of A Parameter With A Given Name
   3182 **
   3183 ** ^Return the index of an SQL parameter given its name.  ^The
   3184 ** index value returned is suitable for use as the second
   3185 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
   3186 ** is returned if no matching parameter is found.  ^The parameter
   3187 ** name must be given in UTF-8 even if the original statement
   3188 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
   3189 **
   3190 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   3191 ** [sqlite3_bind_parameter_count()], and
   3192 ** [sqlite3_bind_parameter_index()].
   3193 */
   3194 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
   3195 
   3196 /*
   3197 ** CAPI3REF: Reset All Bindings On A Prepared Statement
   3198 **
   3199 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
   3200 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
   3201 ** ^Use this routine to reset all host parameters to NULL.
   3202 */
   3203 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
   3204 
   3205 /*
   3206 ** CAPI3REF: Number Of Columns In A Result Set
   3207 **
   3208 ** ^Return the number of columns in the result set returned by the
   3209 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
   3210 ** statement that does not return data (for example an [UPDATE]).
   3211 */
   3212 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
   3213 
   3214 /*
   3215 ** CAPI3REF: Column Names In A Result Set
   3216 **
   3217 ** ^These routines return the name assigned to a particular column
   3218 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
   3219 ** interface returns a pointer to a zero-terminated UTF-8 string
   3220 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
   3221 ** UTF-16 string.  ^The first parameter is the [prepared statement]
   3222 ** that implements the [SELECT] statement. ^The second parameter is the
   3223 ** column number.  ^The leftmost column is number 0.
   3224 **
   3225 ** ^The returned string pointer is valid until either the [prepared statement]
   3226 ** is destroyed by [sqlite3_finalize()] or until the next call to
   3227 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
   3228 **
   3229 ** ^If sqlite3_malloc() fails during the processing of either routine
   3230 ** (for example during a conversion from UTF-8 to UTF-16) then a
   3231 ** NULL pointer is returned.
   3232 **
   3233 ** ^The name of a result column is the value of the "AS" clause for
   3234 ** that column, if there is an AS clause.  If there is no AS clause
   3235 ** then the name of the column is unspecified and may change from
   3236 ** one release of SQLite to the next.
   3237 */
   3238 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
   3239 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
   3240 
   3241 /*
   3242 ** CAPI3REF: Source Of Data In A Query Result
   3243 **
   3244 ** ^These routines provide a means to determine the database, table, and
   3245 ** table column that is the origin of a particular result column in
   3246 ** [SELECT] statement.
   3247 ** ^The name of the database or table or column can be returned as
   3248 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
   3249 ** the database name, the _table_ routines return the table name, and
   3250 ** the origin_ routines return the column name.
   3251 ** ^The returned string is valid until the [prepared statement] is destroyed
   3252 ** using [sqlite3_finalize()] or until the same information is requested
   3253 ** again in a different encoding.
   3254 **
   3255 ** ^The names returned are the original un-aliased names of the
   3256 ** database, table, and column.
   3257 **
   3258 ** ^The first argument to these interfaces is a [prepared statement].
   3259 ** ^These functions return information about the Nth result column returned by
   3260 ** the statement, where N is the second function argument.
   3261 ** ^The left-most column is column 0 for these routines.
   3262 **
   3263 ** ^If the Nth column returned by the statement is an expression or
   3264 ** subquery and is not a column value, then all of these functions return
   3265 ** NULL.  ^These routine might also return NULL if a memory allocation error
   3266 ** occurs.  ^Otherwise, they return the name of the attached database, table,
   3267 ** or column that query result column was extracted from.
   3268 **
   3269 ** ^As with all other SQLite APIs, those whose names end with "16" return
   3270 ** UTF-16 encoded strings and the other functions return UTF-8.
   3271 **
   3272 ** ^These APIs are only available if the library was compiled with the
   3273 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
   3274 **
   3275 ** If two or more threads call one or more of these routines against the same
   3276 ** prepared statement and column at the same time then the results are
   3277 ** undefined.
   3278 **
   3279 ** If two or more threads call one or more
   3280 ** [sqlite3_column_database_name | column metadata interfaces]
   3281 ** for the same [prepared statement] and result column
   3282 ** at the same time then the results are undefined.
   3283 */
   3284 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
   3285 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
   3286 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
   3287 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
   3288 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
   3289 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
   3290 
   3291 /*
   3292 ** CAPI3REF: Declared Datatype Of A Query Result
   3293 **
   3294 ** ^(The first parameter is a [prepared statement].
   3295 ** If this statement is a [SELECT] statement and the Nth column of the
   3296 ** returned result set of that [SELECT] is a table column (not an
   3297 ** expression or subquery) then the declared type of the table
   3298 ** column is returned.)^  ^If the Nth column of the result set is an
   3299 ** expression or subquery, then a NULL pointer is returned.
   3300 ** ^The returned string is always UTF-8 encoded.
   3301 **
   3302 ** ^(For example, given the database schema:
   3303 **
   3304 ** CREATE TABLE t1(c1 VARIANT);
   3305 **
   3306 ** and the following statement to be compiled:
   3307 **
   3308 ** SELECT c1 + 1, c1 FROM t1;
   3309 **
   3310 ** this routine would return the string "VARIANT" for the second result
   3311 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
   3312 **
   3313 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
   3314 ** is declared to contain a particular type does not mean that the
   3315 ** data stored in that column is of the declared type.  SQLite is
   3316 ** strongly typed, but the typing is dynamic not static.  ^Type
   3317 ** is associated with individual values, not with the containers
   3318 ** used to hold those values.
   3319 */
   3320 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
   3321 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
   3322 
   3323 /*
   3324 ** CAPI3REF: Evaluate An SQL Statement
   3325 **
   3326 ** After a [prepared statement] has been prepared using either
   3327 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
   3328 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
   3329 ** must be called one or more times to evaluate the statement.
   3330 **
   3331 ** The details of the behavior of the sqlite3_step() interface depend
   3332 ** on whether the statement was prepared using the newer "v2" interface
   3333 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
   3334 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
   3335 ** new "v2" interface is recommended for new applications but the legacy
   3336 ** interface will continue to be supported.
   3337 **
   3338 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
   3339 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
   3340 ** ^With the "v2" interface, any of the other [result codes] or
   3341 ** [extended result codes] might be returned as well.
   3342 **
   3343 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
   3344 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
   3345 ** or occurs outside of an explicit transaction, then you can retry the
   3346 ** statement.  If the statement is not a [COMMIT] and occurs within a
   3347 ** explicit transaction then you should rollback the transaction before
   3348 ** continuing.
   3349 **
   3350 ** ^[SQLITE_DONE] means that the statement has finished executing
   3351 ** successfully.  sqlite3_step() should not be called again on this virtual
   3352 ** machine without first calling [sqlite3_reset()] to reset the virtual
   3353 ** machine back to its initial state.
   3354 **
   3355 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
   3356 ** is returned each time a new row of data is ready for processing by the
   3357 ** caller. The values may be accessed using the [column access functions].
   3358 ** sqlite3_step() is called again to retrieve the next row of data.
   3359 **
   3360 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
   3361 ** violation) has occurred.  sqlite3_step() should not be called again on
   3362 ** the VM. More information may be found by calling [sqlite3_errmsg()].
   3363 ** ^With the legacy interface, a more specific error code (for example,
   3364 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
   3365 ** can be obtained by calling [sqlite3_reset()] on the
   3366 ** [prepared statement].  ^In the "v2" interface,
   3367 ** the more specific error code is returned directly by sqlite3_step().
   3368 **
   3369 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
   3370 ** Perhaps it was called on a [prepared statement] that has
   3371 ** already been [sqlite3_finalize | finalized] or on one that had
   3372 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
   3373 ** be the case that the same database connection is being used by two or
   3374 ** more threads at the same moment in time.
   3375 **
   3376 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
   3377 ** API always returns a generic error code, [SQLITE_ERROR], following any
   3378 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
   3379 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
   3380 ** specific [error codes] that better describes the error.
   3381 ** We admit that this is a goofy design.  The problem has been fixed
   3382 ** with the "v2" interface.  If you prepare all of your SQL statements
   3383 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
   3384 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
   3385 ** then the more specific [error codes] are returned directly
   3386 ** by sqlite3_step().  The use of the "v2" interface is recommended.
   3387 */
   3388 SQLITE_API int sqlite3_step(sqlite3_stmt*);
   3389 
   3390 /*
   3391 ** CAPI3REF: Number of columns in a result set
   3392 **
   3393 ** ^The sqlite3_data_count(P) the number of columns in the
   3394 ** of the result set of [prepared statement] P.
   3395 */
   3396 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
   3397 
   3398 /*
   3399 ** CAPI3REF: Fundamental Datatypes
   3400 ** KEYWORDS: SQLITE_TEXT
   3401 **
   3402 ** ^(Every value in SQLite has one of five fundamental datatypes:
   3403 **
   3404 ** <ul>
   3405 ** <li> 64-bit signed integer
   3406 ** <li> 64-bit IEEE floating point number
   3407 ** <li> string
   3408 ** <li> BLOB
   3409 ** <li> NULL
   3410 ** </ul>)^
   3411 **
   3412 ** These constants are codes for each of those types.
   3413 **
   3414 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
   3415 ** for a completely different meaning.  Software that links against both
   3416 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
   3417 ** SQLITE_TEXT.
   3418 */
   3419 #define SQLITE_INTEGER  1
   3420 #define SQLITE_FLOAT    2
   3421 #define SQLITE_BLOB     4
   3422 #define SQLITE_NULL     5
   3423 #ifdef SQLITE_TEXT
   3424 # undef SQLITE_TEXT
   3425 #else
   3426 # define SQLITE_TEXT     3
   3427 #endif
   3428 #define SQLITE3_TEXT     3
   3429 
   3430 /*
   3431 ** CAPI3REF: Result Values From A Query
   3432 ** KEYWORDS: {column access functions}
   3433 **
   3434 ** These routines form the "result set" interface.
   3435 **
   3436 ** ^These routines return information about a single column of the current
   3437 ** result row of a query.  ^In every case the first argument is a pointer
   3438 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
   3439 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
   3440 ** and the second argument is the index of the column for which information
   3441 ** should be returned. ^The leftmost column of the result set has the index 0.
   3442 ** ^The number of columns in the result can be determined using
   3443 ** [sqlite3_column_count()].
   3444 **
   3445 ** If the SQL statement does not currently point to a valid row, or if the
   3446 ** column index is out of range, the result is undefined.
   3447 ** These routines may only be called when the most recent call to
   3448 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
   3449 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
   3450 ** If any of these routines are called after [sqlite3_reset()] or
   3451 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
   3452 ** something other than [SQLITE_ROW], the results are undefined.
   3453 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
   3454 ** are called from a different thread while any of these routines
   3455 ** are pending, then the results are undefined.
   3456 **
   3457 ** ^The sqlite3_column_type() routine returns the
   3458 ** [SQLITE_INTEGER | datatype code] for the initial data type
   3459 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
   3460 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
   3461 ** returned by sqlite3_column_type() is only meaningful if no type
   3462 ** conversions have occurred as described below.  After a type conversion,
   3463 ** the value returned by sqlite3_column_type() is undefined.  Future
   3464 ** versions of SQLite may change the behavior of sqlite3_column_type()
   3465 ** following a type conversion.
   3466 **
   3467 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
   3468 ** routine returns the number of bytes in that BLOB or string.
   3469 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
   3470 ** the string to UTF-8 and then returns the number of bytes.
   3471 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
   3472 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
   3473 ** the number of bytes in that string.
   3474 ** ^The value returned does not include the zero terminator at the end
   3475 ** of the string.  ^For clarity: the value returned is the number of
   3476 ** bytes in the string, not the number of characters.
   3477 **
   3478 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
   3479 ** even empty strings, are always zero terminated.  ^The return
   3480 ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
   3481 ** pointer, possibly even a NULL pointer.
   3482 **
   3483 ** ^The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
   3484 ** but leaves the result in UTF-16 in native byte order instead of UTF-8.
   3485 ** ^The zero terminator is not included in this count.
   3486 **
   3487 ** ^The object returned by [sqlite3_column_value()] is an
   3488 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
   3489 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
   3490 ** If the [unprotected sqlite3_value] object returned by
   3491 ** [sqlite3_column_value()] is used in any other way, including calls
   3492 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
   3493 ** or [sqlite3_value_bytes()], then the behavior is undefined.
   3494 **
   3495 ** These routines attempt to convert the value where appropriate.  ^For
   3496 ** example, if the internal representation is FLOAT and a text result
   3497 ** is requested, [sqlite3_snprintf()] is used internally to perform the
   3498 ** conversion automatically.  ^(The following table details the conversions
   3499 ** that are applied:
   3500 **
   3501 ** <blockquote>
   3502 ** <table border="1">
   3503 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
   3504 **
   3505 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
   3506 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
   3507 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
   3508 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
   3509 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
   3510 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
   3511 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
   3512 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
   3513 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
   3514 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
   3515 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
   3516 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
   3517 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
   3518 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
   3519 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
   3520 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
   3521 ** </table>
   3522 ** </blockquote>)^
   3523 **
   3524 ** The table above makes reference to standard C library functions atoi()
   3525 ** and atof().  SQLite does not really use these functions.  It has its
   3526 ** own equivalent internal routines.  The atoi() and atof() names are
   3527 ** used in the table for brevity and because they are familiar to most
   3528 ** C programmers.
   3529 **
   3530 ** ^Note that when type conversions occur, pointers returned by prior
   3531 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
   3532 ** sqlite3_column_text16() may be invalidated.
   3533 ** ^(Type conversions and pointer invalidations might occur
   3534 ** in the following cases:
   3535 **
   3536 ** <ul>
   3537 ** <li> The initial content is a BLOB and sqlite3_column_text() or
   3538 **      sqlite3_column_text16() is called.  A zero-terminator might
   3539 **      need to be added to the string.</li>
   3540 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
   3541 **      sqlite3_column_text16() is called.  The content must be converted
   3542 **      to UTF-16.</li>
   3543 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
   3544 **      sqlite3_column_text() is called.  The content must be converted
   3545 **      to UTF-8.</li>
   3546 ** </ul>)^
   3547 **
   3548 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
   3549 ** not invalidate a prior pointer, though of course the content of the buffer
   3550 ** that the prior pointer points to will have been modified.  Other kinds
   3551 ** of conversion are done in place when it is possible, but sometimes they
   3552 ** are not possible and in those cases prior pointers are invalidated.
   3553 **
   3554 ** ^(The safest and easiest to remember policy is to invoke these routines
   3555 ** in one of the following ways:
   3556 **
   3557 ** <ul>
   3558 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
   3559 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
   3560 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
   3561 ** </ul>)^
   3562 **
   3563 ** In other words, you should call sqlite3_column_text(),
   3564 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
   3565 ** into the desired format, then invoke sqlite3_column_bytes() or
   3566 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
   3567 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
   3568 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
   3569 ** with calls to sqlite3_column_bytes().
   3570 **
   3571 ** ^The pointers returned are valid until a type conversion occurs as
   3572 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
   3573 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
   3574 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
   3575 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
   3576 ** [sqlite3_free()].
   3577 **
   3578 ** ^(If a memory allocation error occurs during the evaluation of any
   3579 ** of these routines, a default value is returned.  The default value
   3580 ** is either the integer 0, the floating point number 0.0, or a NULL
   3581 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
   3582 ** [SQLITE_NOMEM].)^
   3583 */
   3584 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
   3585 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
   3586 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
   3587 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
   3588 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
   3589 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
   3590 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
   3591 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
   3592 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
   3593 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
   3594 
   3595 /*
   3596 ** CAPI3REF: Destroy A Prepared Statement Object
   3597 **
   3598 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
   3599 ** ^If the statement was executed successfully or not executed at all, then
   3600 ** SQLITE_OK is returned. ^If execution of the statement failed then an
   3601 ** [error code] or [extended error code] is returned.
   3602 **
   3603 ** ^This routine can be called at any point during the execution of the
   3604 ** [prepared statement].  ^If the virtual machine has not
   3605 ** completed execution when this routine is called, that is like
   3606 ** encountering an error or an [sqlite3_interrupt | interrupt].
   3607 ** ^Incomplete updates may be rolled back and transactions canceled,
   3608 ** depending on the circumstances, and the
   3609 ** [error code] returned will be [SQLITE_ABORT].
   3610 */
   3611 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
   3612 
   3613 /*
   3614 ** CAPI3REF: Reset A Prepared Statement Object
   3615 **
   3616 ** The sqlite3_reset() function is called to reset a [prepared statement]
   3617 ** object back to its initial state, ready to be re-executed.
   3618 ** ^Any SQL statement variables that had values bound to them using
   3619 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
   3620 ** Use [sqlite3_clear_bindings()] to reset the bindings.
   3621 **
   3622 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
   3623 ** back to the beginning of its program.
   3624 **
   3625 ** ^If the most recent call to [sqlite3_step(S)] for the
   3626 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
   3627 ** or if [sqlite3_step(S)] has never before been called on S,
   3628 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
   3629 **
   3630 ** ^If the most recent call to [sqlite3_step(S)] for the
   3631 ** [prepared statement] S indicated an error, then
   3632 ** [sqlite3_reset(S)] returns an appropriate [error code].
   3633 **
   3634 ** ^The [sqlite3_reset(S)] interface does not change the values
   3635 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
   3636 */
   3637 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
   3638 
   3639 /*
   3640 ** CAPI3REF: Create Or Redefine SQL Functions
   3641 ** KEYWORDS: {function creation routines}
   3642 ** KEYWORDS: {application-defined SQL function}
   3643 ** KEYWORDS: {application-defined SQL functions}
   3644 **
   3645 ** ^These two functions (collectively known as "function creation routines")
   3646 ** are used to add SQL functions or aggregates or to redefine the behavior
   3647 ** of existing SQL functions or aggregates.  The only difference between the
   3648 ** two is that the second parameter, the name of the (scalar) function or
   3649 ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
   3650 ** for sqlite3_create_function16().
   3651 **
   3652 ** ^The first parameter is the [database connection] to which the SQL
   3653 ** function is to be added.  ^If an application uses more than one database
   3654 ** connection then application-defined SQL functions must be added
   3655 ** to each database connection separately.
   3656 **
   3657 ** The second parameter is the name of the SQL function to be created or
   3658 ** redefined.  ^The length of the name is limited to 255 bytes, exclusive of
   3659 ** the zero-terminator.  Note that the name length limit is in bytes, not
   3660 ** characters.  ^Any attempt to create a function with a longer name
   3661 ** will result in [SQLITE_ERROR] being returned.
   3662 **
   3663 ** ^The third parameter (nArg)
   3664 ** is the number of arguments that the SQL function or
   3665 ** aggregate takes. ^If this parameter is -1, then the SQL function or
   3666 ** aggregate may take any number of arguments between 0 and the limit
   3667 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
   3668 ** parameter is less than -1 or greater than 127 then the behavior is
   3669 ** undefined.
   3670 **
   3671 ** The fourth parameter, eTextRep, specifies what
   3672 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
   3673 ** its parameters.  Any SQL function implementation should be able to work
   3674 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
   3675 ** more efficient with one encoding than another.  ^An application may
   3676 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
   3677 ** times with the same function but with different values of eTextRep.
   3678 ** ^When multiple implementations of the same function are available, SQLite
   3679 ** will pick the one that involves the least amount of data conversion.
   3680 ** If there is only a single implementation which does not care what text
   3681 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
   3682 **
   3683 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
   3684 ** function can gain access to this pointer using [sqlite3_user_data()].)^
   3685 **
   3686 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
   3687 ** pointers to C-language functions that implement the SQL function or
   3688 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
   3689 ** callback only; NULL pointers should be passed as the xStep and xFinal
   3690 ** parameters. ^An aggregate SQL function requires an implementation of xStep
   3691 ** and xFinal and NULL should be passed for xFunc. ^To delete an existing
   3692 ** SQL function or aggregate, pass NULL for all three function callbacks.
   3693 **
   3694 ** ^It is permitted to register multiple implementations of the same
   3695 ** functions with the same name but with either differing numbers of
   3696 ** arguments or differing preferred text encodings.  ^SQLite will use
   3697 ** the implementation that most closely matches the way in which the
   3698 ** SQL function is used.  ^A function implementation with a non-negative
   3699 ** nArg parameter is a better match than a function implementation with
   3700 ** a negative nArg.  ^A function where the preferred text encoding
   3701 ** matches the database encoding is a better
   3702 ** match than a function where the encoding is different.
   3703 ** ^A function where the encoding difference is between UTF16le and UTF16be
   3704 ** is a closer match than a function where the encoding difference is
   3705 ** between UTF8 and UTF16.
   3706 **
   3707 ** ^Built-in functions may be overloaded by new application-defined functions.
   3708 ** ^The first application-defined function with a given name overrides all
   3709 ** built-in functions in the same [database connection] with the same name.
   3710 ** ^Subsequent application-defined functions of the same name only override
   3711 ** prior application-defined functions that are an exact match for the
   3712 ** number of parameters and preferred encoding.
   3713 **
   3714 ** ^An application-defined function is permitted to call other
   3715 ** SQLite interfaces.  However, such calls must not
   3716 ** close the database connection nor finalize or reset the prepared
   3717 ** statement in which the function is running.
   3718 */
   3719 SQLITE_API int sqlite3_create_function(
   3720   sqlite3 *db,
   3721   const char *zFunctionName,
   3722   int nArg,
   3723   int eTextRep,
   3724   void *pApp,
   3725   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   3726   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   3727   void (*xFinal)(sqlite3_context*)
   3728 );
   3729 SQLITE_API int sqlite3_create_function16(
   3730   sqlite3 *db,
   3731   const void *zFunctionName,
   3732   int nArg,
   3733   int eTextRep,
   3734   void *pApp,
   3735   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   3736   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   3737   void (*xFinal)(sqlite3_context*)
   3738 );
   3739 
   3740 /*
   3741 ** CAPI3REF: Text Encodings
   3742 **
   3743 ** These constant define integer codes that represent the various
   3744 ** text encodings supported by SQLite.
   3745 */
   3746 #define SQLITE_UTF8           1
   3747 #define SQLITE_UTF16LE        2
   3748 #define SQLITE_UTF16BE        3
   3749 #define SQLITE_UTF16          4    /* Use native byte order */
   3750 #define SQLITE_ANY            5    /* sqlite3_create_function only */
   3751 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
   3752 
   3753 /*
   3754 ** CAPI3REF: Deprecated Functions
   3755 ** DEPRECATED
   3756 **
   3757 ** These functions are [deprecated].  In order to maintain
   3758 ** backwards compatibility with older code, these functions continue
   3759 ** to be supported.  However, new applications should avoid
   3760 ** the use of these functions.  To help encourage people to avoid
   3761 ** using these functions, we are not going to tell you what they do.
   3762 */
   3763 #ifndef SQLITE_OMIT_DEPRECATED
   3764 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
   3765 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
   3766 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
   3767 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
   3768 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
   3769 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
   3770 #endif
   3771 
   3772 /*
   3773 ** CAPI3REF: Obtaining SQL Function Parameter Values
   3774 **
   3775 ** The C-language implementation of SQL functions and aggregates uses
   3776 ** this set of interface routines to access the parameter values on
   3777 ** the function or aggregate.
   3778 **
   3779 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
   3780 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
   3781 ** define callbacks that implement the SQL functions and aggregates.
   3782 ** The 4th parameter to these callbacks is an array of pointers to
   3783 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
   3784 ** each parameter to the SQL function.  These routines are used to
   3785 ** extract values from the [sqlite3_value] objects.
   3786 **
   3787 ** These routines work only with [protected sqlite3_value] objects.
   3788 ** Any attempt to use these routines on an [unprotected sqlite3_value]
   3789 ** object results in undefined behavior.
   3790 **
   3791 ** ^These routines work just like the corresponding [column access functions]
   3792 ** except that  these routines take a single [protected sqlite3_value] object
   3793 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
   3794 **
   3795 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
   3796 ** in the native byte-order of the host machine.  ^The
   3797 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
   3798 ** extract UTF-16 strings as big-endian and little-endian respectively.
   3799 **
   3800 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
   3801 ** numeric affinity to the value.  This means that an attempt is
   3802 ** made to convert the value to an integer or floating point.  If
   3803 ** such a conversion is possible without loss of information (in other
   3804 ** words, if the value is a string that looks like a number)
   3805 ** then the conversion is performed.  Otherwise no conversion occurs.
   3806 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
   3807 **
   3808 ** Please pay particular attention to the fact that the pointer returned
   3809 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
   3810 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
   3811 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
   3812 ** or [sqlite3_value_text16()].
   3813 **
   3814 ** These routines must be called from the same thread as
   3815 ** the SQL function that supplied the [sqlite3_value*] parameters.
   3816 */
   3817 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
   3818 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
   3819 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
   3820 SQLITE_API double sqlite3_value_double(sqlite3_value*);
   3821 SQLITE_API int sqlite3_value_int(sqlite3_value*);
   3822 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
   3823 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
   3824 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
   3825 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
   3826 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
   3827 SQLITE_API int sqlite3_value_type(sqlite3_value*);
   3828 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
   3829 
   3830 /*
   3831 ** CAPI3REF: Obtain Aggregate Function Context
   3832 **
   3833 ** Implementions of aggregate SQL functions use this
   3834 ** routine to allocate memory for storing their state.
   3835 **
   3836 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
   3837 ** for a particular aggregate function, SQLite
   3838 ** allocates N of memory, zeroes out that memory, and returns a pointer
   3839 ** to the new memory. ^On second and subsequent calls to
   3840 ** sqlite3_aggregate_context() for the same aggregate function instance,
   3841 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
   3842 ** called once for each invocation of the xStep callback and then one
   3843 ** last time when the xFinal callback is invoked.  ^(When no rows match
   3844 ** an aggregate query, the xStep() callback of the aggregate function
   3845 ** implementation is never called and xFinal() is called exactly once.
   3846 ** In those cases, sqlite3_aggregate_context() might be called for the
   3847 ** first time from within xFinal().)^
   3848 **
   3849 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
   3850 ** less than or equal to zero or if a memory allocate error occurs.
   3851 **
   3852 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
   3853 ** determined by the N parameter on first successful call.  Changing the
   3854 ** value of N in subsequent call to sqlite3_aggregate_context() within
   3855 ** the same aggregate function instance will not resize the memory
   3856 ** allocation.)^
   3857 **
   3858 ** ^SQLite automatically frees the memory allocated by
   3859 ** sqlite3_aggregate_context() when the aggregate query concludes.
   3860 **
   3861 ** The first parameter must be a copy of the
   3862 ** [sqlite3_context | SQL function context] that is the first parameter
   3863 ** to the xStep or xFinal callback routine that implements the aggregate
   3864 ** function.
   3865 **
   3866 ** This routine must be called from the same thread in which
   3867 ** the aggregate SQL function is running.
   3868 */
   3869 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
   3870 
   3871 /*
   3872 ** CAPI3REF: User Data For Functions
   3873 **
   3874 ** ^The sqlite3_user_data() interface returns a copy of
   3875 ** the pointer that was the pUserData parameter (the 5th parameter)
   3876 ** of the [sqlite3_create_function()]
   3877 ** and [sqlite3_create_function16()] routines that originally
   3878 ** registered the application defined function.
   3879 **
   3880 ** This routine must be called from the same thread in which
   3881 ** the application-defined function is running.
   3882 */
   3883 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
   3884 
   3885 /*
   3886 ** CAPI3REF: Database Connection For Functions
   3887 **
   3888 ** ^The sqlite3_context_db_handle() interface returns a copy of
   3889 ** the pointer to the [database connection] (the 1st parameter)
   3890 ** of the [sqlite3_create_function()]
   3891 ** and [sqlite3_create_function16()] routines that originally
   3892 ** registered the application defined function.
   3893 */
   3894 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
   3895 
   3896 /*
   3897 ** CAPI3REF: Function Auxiliary Data
   3898 **
   3899 ** The following two functions may be used by scalar SQL functions to
   3900 ** associate metadata with argument values. If the same value is passed to
   3901 ** multiple invocations of the same SQL function during query execution, under
   3902 ** some circumstances the associated metadata may be preserved. This may
   3903 ** be used, for example, to add a regular-expression matching scalar
   3904 ** function. The compiled version of the regular expression is stored as
   3905 ** metadata associated with the SQL value passed as the regular expression
   3906 ** pattern.  The compiled regular expression can be reused on multiple
   3907 ** invocations of the same function so that the original pattern string
   3908 ** does not need to be recompiled on each invocation.
   3909 **
   3910 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
   3911 ** associated by the sqlite3_set_auxdata() function with the Nth argument
   3912 ** value to the application-defined function. ^If no metadata has been ever
   3913 ** been set for the Nth argument of the function, or if the corresponding
   3914 ** function parameter has changed since the meta-data was set,
   3915 ** then sqlite3_get_auxdata() returns a NULL pointer.
   3916 **
   3917 ** ^The sqlite3_set_auxdata() interface saves the metadata
   3918 ** pointed to by its 3rd parameter as the metadata for the N-th
   3919 ** argument of the application-defined function.  Subsequent
   3920 ** calls to sqlite3_get_auxdata() might return this data, if it has
   3921 ** not been destroyed.
   3922 ** ^If it is not NULL, SQLite will invoke the destructor
   3923 ** function given by the 4th parameter to sqlite3_set_auxdata() on
   3924 ** the metadata when the corresponding function parameter changes
   3925 ** or when the SQL statement completes, whichever comes first.
   3926 **
   3927 ** SQLite is free to call the destructor and drop metadata on any
   3928 ** parameter of any function at any time.  ^The only guarantee is that
   3929 ** the destructor will be called before the metadata is dropped.
   3930 **
   3931 ** ^(In practice, metadata is preserved between function calls for
   3932 ** expressions that are constant at compile time. This includes literal
   3933 ** values and [parameters].)^
   3934 **
   3935 ** These routines must be called from the same thread in which
   3936 ** the SQL function is running.
   3937 */
   3938 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
   3939 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
   3940 
   3941 
   3942 /*
   3943 ** CAPI3REF: Constants Defining Special Destructor Behavior
   3944 **
   3945 ** These are special values for the destructor that is passed in as the
   3946 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
   3947 ** argument is SQLITE_STATIC, it means that the content pointer is constant
   3948 ** and will never change.  It does not need to be destroyed.  ^The
   3949 ** SQLITE_TRANSIENT value means that the content will likely change in
   3950 ** the near future and that SQLite should make its own private copy of
   3951 ** the content before returning.
   3952 **
   3953 ** The typedef is necessary to work around problems in certain
   3954 ** C++ compilers.  See ticket #2191.
   3955 */
   3956 typedef void (*sqlite3_destructor_type)(void*);
   3957 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
   3958 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
   3959 
   3960 /*
   3961 ** CAPI3REF: Setting The Result Of An SQL Function
   3962 **
   3963 ** These routines are used by the xFunc or xFinal callbacks that
   3964 ** implement SQL functions and aggregates.  See
   3965 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
   3966 ** for additional information.
   3967 **
   3968 ** These functions work very much like the [parameter binding] family of
   3969 ** functions used to bind values to host parameters in prepared statements.
   3970 ** Refer to the [SQL parameter] documentation for additional information.
   3971 **
   3972 ** ^The sqlite3_result_blob() interface sets the result from
   3973 ** an application-defined function to be the BLOB whose content is pointed
   3974 ** to by the second parameter and which is N bytes long where N is the
   3975 ** third parameter.
   3976 **
   3977 ** ^The sqlite3_result_zeroblob() interfaces set the result of
   3978 ** the application-defined function to be a BLOB containing all zero
   3979 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
   3980 **
   3981 ** ^The sqlite3_result_double() interface sets the result from
   3982 ** an application-defined function to be a floating point value specified
   3983 ** by its 2nd argument.
   3984 **
   3985 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
   3986 ** cause the implemented SQL function to throw an exception.
   3987 ** ^SQLite uses the string pointed to by the
   3988 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
   3989 ** as the text of an error message.  ^SQLite interprets the error
   3990 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
   3991 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
   3992 ** byte order.  ^If the third parameter to sqlite3_result_error()
   3993 ** or sqlite3_result_error16() is negative then SQLite takes as the error
   3994 ** message all text up through the first zero character.
   3995 ** ^If the third parameter to sqlite3_result_error() or
   3996 ** sqlite3_result_error16() is non-negative then SQLite takes that many
   3997 ** bytes (not characters) from the 2nd parameter as the error message.
   3998 ** ^The sqlite3_result_error() and sqlite3_result_error16()
   3999 ** routines make a private copy of the error message text before
   4000 ** they return.  Hence, the calling function can deallocate or
   4001 ** modify the text after they return without harm.
   4002 ** ^The sqlite3_result_error_code() function changes the error code
   4003 ** returned by SQLite as a result of an error in a function.  ^By default,
   4004 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
   4005 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
   4006 **
   4007 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
   4008 ** indicating that a string or BLOB is too long to represent.
   4009 **
   4010 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
   4011 ** indicating that a memory allocation failed.
   4012 **
   4013 ** ^The sqlite3_result_int() interface sets the return value
   4014 ** of the application-defined function to be the 32-bit signed integer
   4015 ** value given in the 2nd argument.
   4016 ** ^The sqlite3_result_int64() interface sets the return value
   4017 ** of the application-defined function to be the 64-bit signed integer
   4018 ** value given in the 2nd argument.
   4019 **
   4020 ** ^The sqlite3_result_null() interface sets the return value
   4021 ** of the application-defined function to be NULL.
   4022 **
   4023 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
   4024 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
   4025 ** set the return value of the application-defined function to be
   4026 ** a text string which is represented as UTF-8, UTF-16 native byte order,
   4027 ** UTF-16 little endian, or UTF-16 big endian, respectively.
   4028 ** ^SQLite takes the text result from the application from
   4029 ** the 2nd parameter of the sqlite3_result_text* interfaces.
   4030 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
   4031 ** is negative, then SQLite takes result text from the 2nd parameter
   4032 ** through the first zero character.
   4033 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
   4034 ** is non-negative, then as many bytes (not characters) of the text
   4035 ** pointed to by the 2nd parameter are taken as the application-defined
   4036 ** function result.
   4037 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
   4038 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
   4039 ** function as the destructor on the text or BLOB result when it has
   4040 ** finished using that result.
   4041 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
   4042 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
   4043 ** assumes that the text or BLOB result is in constant space and does not
   4044 ** copy the content of the parameter nor call a destructor on the content
   4045 ** when it has finished using that result.
   4046 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
   4047 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
   4048 ** then SQLite makes a copy of the result into space obtained from
   4049 ** from [sqlite3_malloc()] before it returns.
   4050 **
   4051 ** ^The sqlite3_result_value() interface sets the result of
   4052 ** the application-defined function to be a copy the
   4053 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
   4054 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
   4055 ** so that the [sqlite3_value] specified in the parameter may change or
   4056 ** be deallocated after sqlite3_result_value() returns without harm.
   4057 ** ^A [protected sqlite3_value] object may always be used where an
   4058 ** [unprotected sqlite3_value] object is required, so either
   4059 ** kind of [sqlite3_value] object can be used with this interface.
   4060 **
   4061 ** If these routines are called from within the different thread
   4062 ** than the one containing the application-defined function that received
   4063 ** the [sqlite3_context] pointer, the results are undefined.
   4064 */
   4065 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
   4066 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
   4067 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
   4068 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
   4069 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
   4070 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
   4071 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
   4072 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
   4073 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
   4074 SQLITE_API void sqlite3_result_null(sqlite3_context*);
   4075 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
   4076 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
   4077 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
   4078 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
   4079 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
   4080 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
   4081 
   4082 /*
   4083 ** CAPI3REF: Define New Collating Sequences
   4084 **
   4085 ** These functions are used to add new collation sequences to the
   4086 ** [database connection] specified as the first argument.
   4087 **
   4088 ** ^The name of the new collation sequence is specified as a UTF-8 string
   4089 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
   4090 ** and a UTF-16 string for sqlite3_create_collation16(). ^In all cases
   4091 ** the name is passed as the second function argument.
   4092 **
   4093 ** ^The third argument may be one of the constants [SQLITE_UTF8],
   4094 ** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
   4095 ** routine expects to be passed pointers to strings encoded using UTF-8,
   4096 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. ^The
   4097 ** third argument might also be [SQLITE_UTF16] to indicate that the routine
   4098 ** expects pointers to be UTF-16 strings in the native byte order, or the
   4099 ** argument can be [SQLITE_UTF16_ALIGNED] if the
   4100 ** the routine expects pointers to 16-bit word aligned strings
   4101 ** of UTF-16 in the native byte order.
   4102 **
   4103 ** A pointer to the user supplied routine must be passed as the fifth
   4104 ** argument.  ^If it is NULL, this is the same as deleting the collation
   4105 ** sequence (so that SQLite cannot call it anymore).
   4106 ** ^Each time the application supplied function is invoked, it is passed
   4107 ** as its first parameter a copy of the void* passed as the fourth argument
   4108 ** to sqlite3_create_collation() or sqlite3_create_collation16().
   4109 **
   4110 ** ^The remaining arguments to the application-supplied routine are two strings,
   4111 ** each represented by a (length, data) pair and encoded in the encoding
   4112 ** that was passed as the third argument when the collation sequence was
   4113 ** registered.  The application defined collation routine should
   4114 ** return negative, zero or positive if the first string is less than,
   4115 ** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
   4116 **
   4117 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
   4118 ** except that it takes an extra argument which is a destructor for
   4119 ** the collation.  ^The destructor is called when the collation is
   4120 ** destroyed and is passed a copy of the fourth parameter void* pointer
   4121 ** of the sqlite3_create_collation_v2().
   4122 ** ^Collations are destroyed when they are overridden by later calls to the
   4123 ** collation creation functions or when the [database connection] is closed
   4124 ** using [sqlite3_close()].
   4125 **
   4126 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
   4127 */
   4128 SQLITE_API int sqlite3_create_collation(
   4129   sqlite3*,
   4130   const char *zName,
   4131   int eTextRep,
   4132   void*,
   4133   int(*xCompare)(void*,int,const void*,int,const void*)
   4134 );
   4135 SQLITE_API int sqlite3_create_collation_v2(
   4136   sqlite3*,
   4137   const char *zName,
   4138   int eTextRep,
   4139   void*,
   4140   int(*xCompare)(void*,int,const void*,int,const void*),
   4141   void(*xDestroy)(void*)
   4142 );
   4143 SQLITE_API int sqlite3_create_collation16(
   4144   sqlite3*,
   4145   const void *zName,
   4146   int eTextRep,
   4147   void*,
   4148   int(*xCompare)(void*,int,const void*,int,const void*)
   4149 );
   4150 
   4151 /*
   4152 ** CAPI3REF: Collation Needed Callbacks
   4153 **
   4154 ** ^To avoid having to register all collation sequences before a database
   4155 ** can be used, a single callback function may be registered with the
   4156 ** [database connection] to be invoked whenever an undefined collation
   4157 ** sequence is required.
   4158 **
   4159 ** ^If the function is registered using the sqlite3_collation_needed() API,
   4160 ** then it is passed the names of undefined collation sequences as strings
   4161 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
   4162 ** the names are passed as UTF-16 in machine native byte order.
   4163 ** ^A call to either function replaces the existing collation-needed callback.
   4164 **
   4165 ** ^(When the callback is invoked, the first argument passed is a copy
   4166 ** of the second argument to sqlite3_collation_needed() or
   4167 ** sqlite3_collation_needed16().  The second argument is the database
   4168 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
   4169 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
   4170 ** sequence function required.  The fourth parameter is the name of the
   4171 ** required collation sequence.)^
   4172 **
   4173 ** The callback function should register the desired collation using
   4174 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
   4175 ** [sqlite3_create_collation_v2()].
   4176 */
   4177 SQLITE_API int sqlite3_collation_needed(
   4178   sqlite3*,
   4179   void*,
   4180   void(*)(void*,sqlite3*,int eTextRep,const char*)
   4181 );
   4182 SQLITE_API int sqlite3_collation_needed16(
   4183   sqlite3*,
   4184   void*,
   4185   void(*)(void*,sqlite3*,int eTextRep,const void*)
   4186 );
   4187 
   4188 /*
   4189 ** Specify the key for an encrypted database.  This routine should be
   4190 ** called right after sqlite3_open().
   4191 **
   4192 ** The code to implement this API is not available in the public release
   4193 ** of SQLite.
   4194 */
   4195 SQLITE_API int sqlite3_key(
   4196   sqlite3 *db,                   /* Database to be rekeyed */
   4197   const void *pKey, int nKey     /* The key */
   4198 );
   4199 
   4200 /*
   4201 ** Change the key on an open database.  If the current database is not
   4202 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
   4203 ** database is decrypted.
   4204 **
   4205 ** The code to implement this API is not available in the public release
   4206 ** of SQLite.
   4207 */
   4208 SQLITE_API int sqlite3_rekey(
   4209   sqlite3 *db,                   /* Database to be rekeyed */
   4210   const void *pKey, int nKey     /* The new key */
   4211 );
   4212 
   4213 /*
   4214 ** CAPI3REF: Suspend Execution For A Short Time
   4215 **
   4216 ** ^The sqlite3_sleep() function causes the current thread to suspend execution
   4217 ** for at least a number of milliseconds specified in its parameter.
   4218 **
   4219 ** ^If the operating system does not support sleep requests with
   4220 ** millisecond time resolution, then the time will be rounded up to
   4221 ** the nearest second. ^The number of milliseconds of sleep actually
   4222 ** requested from the operating system is returned.
   4223 **
   4224 ** ^SQLite implements this interface by calling the xSleep()
   4225 ** method of the default [sqlite3_vfs] object.
   4226 */
   4227 SQLITE_API int sqlite3_sleep(int);
   4228 
   4229 /*
   4230 ** CAPI3REF: Name Of The Folder Holding Temporary Files
   4231 **
   4232 ** ^(If this global variable is made to point to a string which is
   4233 ** the name of a folder (a.k.a. directory), then all temporary files
   4234 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
   4235 ** will be placed in that directory.)^  ^If this variable
   4236 ** is a NULL pointer, then SQLite performs a search for an appropriate
   4237 ** temporary file directory.
   4238 **
   4239 ** It is not safe to read or modify this variable in more than one
   4240 ** thread at a time.  It is not safe to read or modify this variable
   4241 ** if a [database connection] is being used at the same time in a separate
   4242 ** thread.
   4243 ** It is intended that this variable be set once
   4244 ** as part of process initialization and before any SQLite interface
   4245 ** routines have been called and that this variable remain unchanged
   4246 ** thereafter.
   4247 **
   4248 ** ^The [temp_store_directory pragma] may modify this variable and cause
   4249 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
   4250 ** the [temp_store_directory pragma] always assumes that any string
   4251 ** that this variable points to is held in memory obtained from
   4252 ** [sqlite3_malloc] and the pragma may attempt to free that memory
   4253 ** using [sqlite3_free].
   4254 ** Hence, if this variable is modified directly, either it should be
   4255 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
   4256 ** or else the use of the [temp_store_directory pragma] should be avoided.
   4257 */
   4258 SQLITE_API char *sqlite3_temp_directory;
   4259 
   4260 /*
   4261 ** CAPI3REF: Test For Auto-Commit Mode
   4262 ** KEYWORDS: {autocommit mode}
   4263 **
   4264 ** ^The sqlite3_get_autocommit() interface returns non-zero or
   4265 ** zero if the given database connection is or is not in autocommit mode,
   4266 ** respectively.  ^Autocommit mode is on by default.
   4267 ** ^Autocommit mode is disabled by a [BEGIN] statement.
   4268 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
   4269 **
   4270 ** If certain kinds of errors occur on a statement within a multi-statement
   4271 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
   4272 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
   4273 ** transaction might be rolled back automatically.  The only way to
   4274 ** find out whether SQLite automatically rolled back the transaction after
   4275 ** an error is to use this function.
   4276 **
   4277 ** If another thread changes the autocommit status of the database
   4278 ** connection while this routine is running, then the return value
   4279 ** is undefined.
   4280 */
   4281 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
   4282 
   4283 /*
   4284 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
   4285 **
   4286 ** ^The sqlite3_db_handle interface returns the [database connection] handle
   4287 ** to which a [prepared statement] belongs.  ^The [database connection]
   4288 ** returned by sqlite3_db_handle is the same [database connection]
   4289 ** that was the first argument
   4290 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
   4291 ** create the statement in the first place.
   4292 */
   4293 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
   4294 
   4295 /*
   4296 ** CAPI3REF: Find the next prepared statement
   4297 **
   4298 ** ^This interface returns a pointer to the next [prepared statement] after
   4299 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
   4300 ** then this interface returns a pointer to the first prepared statement
   4301 ** associated with the database connection pDb.  ^If no prepared statement
   4302 ** satisfies the conditions of this routine, it returns NULL.
   4303 **
   4304 ** The [database connection] pointer D in a call to
   4305 ** [sqlite3_next_stmt(D,S)] must refer to an open database
   4306 ** connection and in particular must not be a NULL pointer.
   4307 */
   4308 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
   4309 
   4310 /*
   4311 ** CAPI3REF: Commit And Rollback Notification Callbacks
   4312 **
   4313 ** ^The sqlite3_commit_hook() interface registers a callback
   4314 ** function to be invoked whenever a transaction is [COMMIT | committed].
   4315 ** ^Any callback set by a previous call to sqlite3_commit_hook()
   4316 ** for the same database connection is overridden.
   4317 ** ^The sqlite3_rollback_hook() interface registers a callback
   4318 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
   4319 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
   4320 ** for the same database connection is overridden.
   4321 ** ^The pArg argument is passed through to the callback.
   4322 ** ^If the callback on a commit hook function returns non-zero,
   4323 ** then the commit is converted into a rollback.
   4324 **
   4325 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
   4326 ** return the P argument from the previous call of the same function
   4327 ** on the same [database connection] D, or NULL for
   4328 ** the first call for each function on D.
   4329 **
   4330 ** The callback implementation must not do anything that will modify
   4331 ** the database connection that invoked the callback.  Any actions
   4332 ** to modify the database connection must be deferred until after the
   4333 ** completion of the [sqlite3_step()] call that triggered the commit
   4334 ** or rollback hook in the first place.
   4335 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   4336 ** database connections for the meaning of "modify" in this paragraph.
   4337 **
   4338 ** ^Registering a NULL function disables the callback.
   4339 **
   4340 ** ^When the commit hook callback routine returns zero, the [COMMIT]
   4341 ** operation is allowed to continue normally.  ^If the commit hook
   4342 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
   4343 ** ^The rollback hook is invoked on a rollback that results from a commit
   4344 ** hook returning non-zero, just as it would be with any other rollback.
   4345 **
   4346 ** ^For the purposes of this API, a transaction is said to have been
   4347 ** rolled back if an explicit "ROLLBACK" statement is executed, or
   4348 ** an error or constraint causes an implicit rollback to occur.
   4349 ** ^The rollback callback is not invoked if a transaction is
   4350 ** automatically rolled back because the database connection is closed.
   4351 ** ^The rollback callback is not invoked if a transaction is
   4352 ** rolled back because a commit callback returned non-zero.
   4353 **
   4354 ** See also the [sqlite3_update_hook()] interface.
   4355 */
   4356 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
   4357 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
   4358 
   4359 /*
   4360 ** CAPI3REF: Data Change Notification Callbacks
   4361 **
   4362 ** ^The sqlite3_update_hook() interface registers a callback function
   4363 ** with the [database connection] identified by the first argument
   4364 ** to be invoked whenever a row is updated, inserted or deleted.
   4365 ** ^Any callback set by a previous call to this function
   4366 ** for the same database connection is overridden.
   4367 **
   4368 ** ^The second argument is a pointer to the function to invoke when a
   4369 ** row is updated, inserted or deleted.
   4370 ** ^The first argument to the callback is a copy of the third argument
   4371 ** to sqlite3_update_hook().
   4372 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
   4373 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
   4374 ** to be invoked.
   4375 ** ^The third and fourth arguments to the callback contain pointers to the
   4376 ** database and table name containing the affected row.
   4377 ** ^The final callback parameter is the [rowid] of the row.
   4378 ** ^In the case of an update, this is the [rowid] after the update takes place.
   4379 **
   4380 ** ^(The update hook is not invoked when internal system tables are
   4381 ** modified (i.e. sqlite_master and sqlite_sequence).)^
   4382 **
   4383 ** ^In the current implementation, the update hook
   4384 ** is not invoked when duplication rows are deleted because of an
   4385 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
   4386 ** invoked when rows are deleted using the [truncate optimization].
   4387 ** The exceptions defined in this paragraph might change in a future
   4388 ** release of SQLite.
   4389 **
   4390 ** The update hook implementation must not do anything that will modify
   4391 ** the database connection that invoked the update hook.  Any actions
   4392 ** to modify the database connection must be deferred until after the
   4393 ** completion of the [sqlite3_step()] call that triggered the update hook.
   4394 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   4395 ** database connections for the meaning of "modify" in this paragraph.
   4396 **
   4397 ** ^The sqlite3_update_hook(D,C,P) function
   4398 ** returns the P argument from the previous call
   4399 ** on the same [database connection] D, or NULL for
   4400 ** the first call on D.
   4401 **
   4402 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
   4403 ** interfaces.
   4404 */
   4405 SQLITE_API void *sqlite3_update_hook(
   4406   sqlite3*,
   4407   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
   4408   void*
   4409 );
   4410 
   4411 /*
   4412 ** CAPI3REF: Enable Or Disable Shared Pager Cache
   4413 ** KEYWORDS: {shared cache}
   4414 **
   4415 ** ^(This routine enables or disables the sharing of the database cache
   4416 ** and schema data structures between [database connection | connections]
   4417 ** to the same database. Sharing is enabled if the argument is true
   4418 ** and disabled if the argument is false.)^
   4419 **
   4420 ** ^Cache sharing is enabled and disabled for an entire process.
   4421 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
   4422 ** sharing was enabled or disabled for each thread separately.
   4423 **
   4424 ** ^(The cache sharing mode set by this interface effects all subsequent
   4425 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
   4426 ** Existing database connections continue use the sharing mode
   4427 ** that was in effect at the time they were opened.)^
   4428 **
   4429 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
   4430 ** successfully.  An [error code] is returned otherwise.)^
   4431 **
   4432 ** ^Shared cache is disabled by default. But this might change in
   4433 ** future releases of SQLite.  Applications that care about shared
   4434 ** cache setting should set it explicitly.
   4435 **
   4436 ** See Also:  [SQLite Shared-Cache Mode]
   4437 */
   4438 SQLITE_API int sqlite3_enable_shared_cache(int);
   4439 
   4440 /*
   4441 ** CAPI3REF: Attempt To Free Heap Memory
   4442 **
   4443 ** ^The sqlite3_release_memory() interface attempts to free N bytes
   4444 ** of heap memory by deallocating non-essential memory allocations
   4445 ** held by the database library.   Memory used to cache database
   4446 ** pages to improve performance is an example of non-essential memory.
   4447 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
   4448 ** which might be more or less than the amount requested.
   4449 */
   4450 SQLITE_API int sqlite3_release_memory(int);
   4451 
   4452 /*
   4453 ** CAPI3REF: Impose A Limit On Heap Size
   4454 **
   4455 ** ^The sqlite3_soft_heap_limit() interface places a "soft" limit
   4456 ** on the amount of heap memory that may be allocated by SQLite.
   4457 ** ^If an internal allocation is requested that would exceed the
   4458 ** soft heap limit, [sqlite3_release_memory()] is invoked one or
   4459 ** more times to free up some space before the allocation is performed.
   4460 **
   4461 ** ^The limit is called "soft" because if [sqlite3_release_memory()]
   4462 ** cannot free sufficient memory to prevent the limit from being exceeded,
   4463 ** the memory is allocated anyway and the current operation proceeds.
   4464 **
   4465 ** ^A negative or zero value for N means that there is no soft heap limit and
   4466 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
   4467 ** ^The default value for the soft heap limit is zero.
   4468 **
   4469 ** ^(SQLite makes a best effort to honor the soft heap limit.
   4470 ** But if the soft heap limit cannot be honored, execution will
   4471 ** continue without error or notification.)^  This is why the limit is
   4472 ** called a "soft" limit.  It is advisory only.
   4473 **
   4474 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
   4475 ** allocated by a single thread - the same thread in which this routine
   4476 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
   4477 ** applied to all threads. The value specified for the soft heap limit
   4478 ** is an upper bound on the total memory allocation for all threads. In
   4479 ** version 3.5.0 there is no mechanism for limiting the heap usage for
   4480 ** individual threads.
   4481 */
   4482 SQLITE_API void sqlite3_soft_heap_limit(int);
   4483 
   4484 /*
   4485 ** CAPI3REF: Extract Metadata About A Column Of A Table
   4486 **
   4487 ** ^This routine returns metadata about a specific column of a specific
   4488 ** database table accessible using the [database connection] handle
   4489 ** passed as the first function argument.
   4490 **
   4491 ** ^The column is identified by the second, third and fourth parameters to
   4492 ** this function. ^The second parameter is either the name of the database
   4493 ** (i.e. "main", "temp", or an attached database) containing the specified
   4494 ** table or NULL. ^If it is NULL, then all attached databases are searched
   4495 ** for the table using the same algorithm used by the database engine to
   4496 ** resolve unqualified table references.
   4497 **
   4498 ** ^The third and fourth parameters to this function are the table and column
   4499 ** name of the desired column, respectively. Neither of these parameters
   4500 ** may be NULL.
   4501 **
   4502 ** ^Metadata is returned by writing to the memory locations passed as the 5th
   4503 ** and subsequent parameters to this function. ^Any of these arguments may be
   4504 ** NULL, in which case the corresponding element of metadata is omitted.
   4505 **
   4506 ** ^(<blockquote>
   4507 ** <table border="1">
   4508 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
   4509 **
   4510 ** <tr><td> 5th <td> const char* <td> Data type
   4511 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
   4512 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
   4513 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
   4514 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
   4515 ** </table>
   4516 ** </blockquote>)^
   4517 **
   4518 ** ^The memory pointed to by the character pointers returned for the
   4519 ** declaration type and collation sequence is valid only until the next
   4520 ** call to any SQLite API function.
   4521 **
   4522 ** ^If the specified table is actually a view, an [error code] is returned.
   4523 **
   4524 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
   4525 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
   4526 ** parameters are set for the explicitly declared column. ^(If there is no
   4527 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
   4528 ** parameters are set as follows:
   4529 **
   4530 ** <pre>
   4531 **     data type: "INTEGER"
   4532 **     collation sequence: "BINARY"
   4533 **     not null: 0
   4534 **     primary key: 1
   4535 **     auto increment: 0
   4536 ** </pre>)^
   4537 **
   4538 ** ^(This function may load one or more schemas from database files. If an
   4539 ** error occurs during this process, or if the requested table or column
   4540 ** cannot be found, an [error code] is returned and an error message left
   4541 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
   4542 **
   4543 ** ^This API is only available if the library was compiled with the
   4544 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
   4545 */
   4546 SQLITE_API int sqlite3_table_column_metadata(
   4547   sqlite3 *db,                /* Connection handle */
   4548   const char *zDbName,        /* Database name or NULL */
   4549   const char *zTableName,     /* Table name */
   4550   const char *zColumnName,    /* Column name */
   4551   char const **pzDataType,    /* OUTPUT: Declared data type */
   4552   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
   4553   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
   4554   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
   4555   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
   4556 );
   4557 
   4558 /*
   4559 ** CAPI3REF: Load An Extension
   4560 **
   4561 ** ^This interface loads an SQLite extension library from the named file.
   4562 **
   4563 ** ^The sqlite3_load_extension() interface attempts to load an
   4564 ** SQLite extension library contained in the file zFile.
   4565 **
   4566 ** ^The entry point is zProc.
   4567 ** ^zProc may be 0, in which case the name of the entry point
   4568 ** defaults to "sqlite3_extension_init".
   4569 ** ^The sqlite3_load_extension() interface returns
   4570 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
   4571 ** ^If an error occurs and pzErrMsg is not 0, then the
   4572 ** [sqlite3_load_extension()] interface shall attempt to
   4573 ** fill *pzErrMsg with error message text stored in memory
   4574 ** obtained from [sqlite3_malloc()]. The calling function
   4575 ** should free this memory by calling [sqlite3_free()].
   4576 **
   4577 ** ^Extension loading must be enabled using
   4578 ** [sqlite3_enable_load_extension()] prior to calling this API,
   4579 ** otherwise an error will be returned.
   4580 **
   4581 ** See also the [load_extension() SQL function].
   4582 */
   4583 SQLITE_API int sqlite3_load_extension(
   4584   sqlite3 *db,          /* Load the extension into this database connection */
   4585   const char *zFile,    /* Name of the shared library containing extension */
   4586   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
   4587   char **pzErrMsg       /* Put error message here if not 0 */
   4588 );
   4589 
   4590 /*
   4591 ** CAPI3REF: Enable Or Disable Extension Loading
   4592 **
   4593 ** ^So as not to open security holes in older applications that are
   4594 ** unprepared to deal with extension loading, and as a means of disabling
   4595 ** extension loading while evaluating user-entered SQL, the following API
   4596 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
   4597 **
   4598 ** ^Extension loading is off by default. See ticket #1863.
   4599 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
   4600 ** to turn extension loading on and call it with onoff==0 to turn
   4601 ** it back off again.
   4602 */
   4603 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
   4604 
   4605 /*
   4606 ** CAPI3REF: Automatically Load An Extensions
   4607 **
   4608 ** ^This API can be invoked at program startup in order to register
   4609 ** one or more statically linked extensions that will be available
   4610 ** to all new [database connections].
   4611 **
   4612 ** ^(This routine stores a pointer to the extension entry point
   4613 ** in an array that is obtained from [sqlite3_malloc()].  That memory
   4614 ** is deallocated by [sqlite3_reset_auto_extension()].)^
   4615 **
   4616 ** ^This function registers an extension entry point that is
   4617 ** automatically invoked whenever a new [database connection]
   4618 ** is opened using [sqlite3_open()], [sqlite3_open16()],
   4619 ** or [sqlite3_open_v2()].
   4620 ** ^Duplicate extensions are detected so calling this routine
   4621 ** multiple times with the same extension is harmless.
   4622 ** ^Automatic extensions apply across all threads.
   4623 */
   4624 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
   4625 
   4626 /*
   4627 ** CAPI3REF: Reset Automatic Extension Loading
   4628 **
   4629 ** ^(This function disables all previously registered automatic
   4630 ** extensions. It undoes the effect of all prior
   4631 ** [sqlite3_auto_extension()] calls.)^
   4632 **
   4633 ** ^This function disables automatic extensions in all threads.
   4634 */
   4635 SQLITE_API void sqlite3_reset_auto_extension(void);
   4636 
   4637 /*
   4638 ****** EXPERIMENTAL - subject to change without notice **************
   4639 **
   4640 ** The interface to the virtual-table mechanism is currently considered
   4641 ** to be experimental.  The interface might change in incompatible ways.
   4642 ** If this is a problem for you, do not use the interface at this time.
   4643 **
   4644 ** When the virtual-table mechanism stabilizes, we will declare the
   4645 ** interface fixed, support it indefinitely, and remove this comment.
   4646 */
   4647 
   4648 /*
   4649 ** Structures used by the virtual table interface
   4650 */
   4651 typedef struct sqlite3_vtab sqlite3_vtab;
   4652 typedef struct sqlite3_index_info sqlite3_index_info;
   4653 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
   4654 typedef struct sqlite3_module sqlite3_module;
   4655 
   4656 /*
   4657 ** CAPI3REF: Virtual Table Object
   4658 ** KEYWORDS: sqlite3_module {virtual table module}
   4659 ** EXPERIMENTAL
   4660 **
   4661 ** This structure, sometimes called a a "virtual table module",
   4662 ** defines the implementation of a [virtual tables].
   4663 ** This structure consists mostly of methods for the module.
   4664 **
   4665 ** ^A virtual table module is created by filling in a persistent
   4666 ** instance of this structure and passing a pointer to that instance
   4667 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
   4668 ** ^The registration remains valid until it is replaced by a different
   4669 ** module or until the [database connection] closes.  The content
   4670 ** of this structure must not change while it is registered with
   4671 ** any database connection.
   4672 */
   4673 struct sqlite3_module {
   4674   int iVersion;
   4675   int (*xCreate)(sqlite3*, void *pAux,
   4676                int argc, const char *const*argv,
   4677                sqlite3_vtab **ppVTab, char**);
   4678   int (*xConnect)(sqlite3*, void *pAux,
   4679                int argc, const char *const*argv,
   4680                sqlite3_vtab **ppVTab, char**);
   4681   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
   4682   int (*xDisconnect)(sqlite3_vtab *pVTab);
   4683   int (*xDestroy)(sqlite3_vtab *pVTab);
   4684   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
   4685   int (*xClose)(sqlite3_vtab_cursor*);
   4686   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
   4687                 int argc, sqlite3_value **argv);
   4688   int (*xNext)(sqlite3_vtab_cursor*);
   4689   int (*xEof)(sqlite3_vtab_cursor*);
   4690   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
   4691   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
   4692   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
   4693   int (*xBegin)(sqlite3_vtab *pVTab);
   4694   int (*xSync)(sqlite3_vtab *pVTab);
   4695   int (*xCommit)(sqlite3_vtab *pVTab);
   4696   int (*xRollback)(sqlite3_vtab *pVTab);
   4697   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
   4698                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
   4699                        void **ppArg);
   4700   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
   4701 };
   4702 
   4703 /*
   4704 ** CAPI3REF: Virtual Table Indexing Information
   4705 ** KEYWORDS: sqlite3_index_info
   4706 ** EXPERIMENTAL
   4707 **
   4708 ** The sqlite3_index_info structure and its substructures is used to
   4709 ** pass information into and receive the reply from the [xBestIndex]
   4710 ** method of a [virtual table module].  The fields under **Inputs** are the
   4711 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
   4712 ** results into the **Outputs** fields.
   4713 **
   4714 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
   4715 **
   4716 ** <pre>column OP expr</pre>
   4717 **
   4718 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
   4719 ** stored in aConstraint[].op.)^  ^(The index of the column is stored in
   4720 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
   4721 ** expr on the right-hand side can be evaluated (and thus the constraint
   4722 ** is usable) and false if it cannot.)^
   4723 **
   4724 ** ^The optimizer automatically inverts terms of the form "expr OP column"
   4725 ** and makes other simplifications to the WHERE clause in an attempt to
   4726 ** get as many WHERE clause terms into the form shown above as possible.
   4727 ** ^The aConstraint[] array only reports WHERE clause terms that are
   4728 ** relevant to the particular virtual table being queried.
   4729 **
   4730 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
   4731 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
   4732 **
   4733 ** The [xBestIndex] method must fill aConstraintUsage[] with information
   4734 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
   4735 ** the right-hand side of the corresponding aConstraint[] is evaluated
   4736 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
   4737 ** is true, then the constraint is assumed to be fully handled by the
   4738 ** virtual table and is not checked again by SQLite.)^
   4739 **
   4740 ** ^The idxNum and idxPtr values are recorded and passed into the
   4741 ** [xFilter] method.
   4742 ** ^[sqlite3_free()] is used to free idxPtr if and only if
   4743 ** needToFreeIdxPtr is true.
   4744 **
   4745 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
   4746 ** the correct order to satisfy the ORDER BY clause so that no separate
   4747 ** sorting step is required.
   4748 **
   4749 ** ^The estimatedCost value is an estimate of the cost of doing the
   4750 ** particular lookup.  A full scan of a table with N entries should have
   4751 ** a cost of N.  A binary search of a table of N entries should have a
   4752 ** cost of approximately log(N).
   4753 */
   4754 struct sqlite3_index_info {
   4755   /* Inputs */
   4756   int nConstraint;           /* Number of entries in aConstraint */
   4757   struct sqlite3_index_constraint {
   4758      int iColumn;              /* Column on left-hand side of constraint */
   4759      unsigned char op;         /* Constraint operator */
   4760      unsigned char usable;     /* True if this constraint is usable */
   4761      int iTermOffset;          /* Used internally - xBestIndex should ignore */
   4762   } *aConstraint;            /* Table of WHERE clause constraints */
   4763   int nOrderBy;              /* Number of terms in the ORDER BY clause */
   4764   struct sqlite3_index_orderby {
   4765      int iColumn;              /* Column number */
   4766      unsigned char desc;       /* True for DESC.  False for ASC. */
   4767   } *aOrderBy;               /* The ORDER BY clause */
   4768   /* Outputs */
   4769   struct sqlite3_index_constraint_usage {
   4770     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
   4771     unsigned char omit;      /* Do not code a test for this constraint */
   4772   } *aConstraintUsage;
   4773   int idxNum;                /* Number used to identify the index */
   4774   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
   4775   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
   4776   int orderByConsumed;       /* True if output is already ordered */
   4777   double estimatedCost;      /* Estimated cost of using this index */
   4778 };
   4779 #define SQLITE_INDEX_CONSTRAINT_EQ    2
   4780 #define SQLITE_INDEX_CONSTRAINT_GT    4
   4781 #define SQLITE_INDEX_CONSTRAINT_LE    8
   4782 #define SQLITE_INDEX_CONSTRAINT_LT    16
   4783 #define SQLITE_INDEX_CONSTRAINT_GE    32
   4784 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
   4785 
   4786 /*
   4787 ** CAPI3REF: Register A Virtual Table Implementation
   4788 ** EXPERIMENTAL
   4789 **
   4790 ** ^These routines are used to register a new [virtual table module] name.
   4791 ** ^Module names must be registered before
   4792 ** creating a new [virtual table] using the module and before using a
   4793 ** preexisting [virtual table] for the module.
   4794 **
   4795 ** ^The module name is registered on the [database connection] specified
   4796 ** by the first parameter.  ^The name of the module is given by the
   4797 ** second parameter.  ^The third parameter is a pointer to
   4798 ** the implementation of the [virtual table module].   ^The fourth
   4799 ** parameter is an arbitrary client data pointer that is passed through
   4800 ** into the [xCreate] and [xConnect] methods of the virtual table module
   4801 ** when a new virtual table is be being created or reinitialized.
   4802 **
   4803 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
   4804 ** is a pointer to a destructor for the pClientData.  ^SQLite will
   4805 ** invoke the destructor function (if it is not NULL) when SQLite
   4806 ** no longer needs the pClientData pointer.  ^The sqlite3_create_module()
   4807 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
   4808 ** destructor.
   4809 */
   4810 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
   4811   sqlite3 *db,               /* SQLite connection to register module with */
   4812   const char *zName,         /* Name of the module */
   4813   const sqlite3_module *p,   /* Methods for the module */
   4814   void *pClientData          /* Client data for xCreate/xConnect */
   4815 );
   4816 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
   4817   sqlite3 *db,               /* SQLite connection to register module with */
   4818   const char *zName,         /* Name of the module */
   4819   const sqlite3_module *p,   /* Methods for the module */
   4820   void *pClientData,         /* Client data for xCreate/xConnect */
   4821   void(*xDestroy)(void*)     /* Module destructor function */
   4822 );
   4823 
   4824 /*
   4825 ** CAPI3REF: Virtual Table Instance Object
   4826 ** KEYWORDS: sqlite3_vtab
   4827 ** EXPERIMENTAL
   4828 **
   4829 ** Every [virtual table module] implementation uses a subclass
   4830 ** of this object to describe a particular instance
   4831 ** of the [virtual table].  Each subclass will
   4832 ** be tailored to the specific needs of the module implementation.
   4833 ** The purpose of this superclass is to define certain fields that are
   4834 ** common to all module implementations.
   4835 **
   4836 ** ^Virtual tables methods can set an error message by assigning a
   4837 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
   4838 ** take care that any prior string is freed by a call to [sqlite3_free()]
   4839 ** prior to assigning a new string to zErrMsg.  ^After the error message
   4840 ** is delivered up to the client application, the string will be automatically
   4841 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
   4842 */
   4843 struct sqlite3_vtab {
   4844   const sqlite3_module *pModule;  /* The module for this virtual table */
   4845   int nRef;                       /* NO LONGER USED */
   4846   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
   4847   /* Virtual table implementations will typically add additional fields */
   4848 };
   4849 
   4850 /*
   4851 ** CAPI3REF: Virtual Table Cursor Object
   4852 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
   4853 ** EXPERIMENTAL
   4854 **
   4855 ** Every [virtual table module] implementation uses a subclass of the
   4856 ** following structure to describe cursors that point into the
   4857 ** [virtual table] and are used
   4858 ** to loop through the virtual table.  Cursors are created using the
   4859 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
   4860 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
   4861 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
   4862 ** of the module.  Each module implementation will define
   4863 ** the content of a cursor structure to suit its own needs.
   4864 **
   4865 ** This superclass exists in order to define fields of the cursor that
   4866 ** are common to all implementations.
   4867 */
   4868 struct sqlite3_vtab_cursor {
   4869   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
   4870   /* Virtual table implementations will typically add additional fields */
   4871 };
   4872 
   4873 /*
   4874 ** CAPI3REF: Declare The Schema Of A Virtual Table
   4875 ** EXPERIMENTAL
   4876 **
   4877 ** ^The [xCreate] and [xConnect] methods of a
   4878 ** [virtual table module] call this interface
   4879 ** to declare the format (the names and datatypes of the columns) of
   4880 ** the virtual tables they implement.
   4881 */
   4882 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
   4883 
   4884 /*
   4885 ** CAPI3REF: Overload A Function For A Virtual Table
   4886 ** EXPERIMENTAL
   4887 **
   4888 ** ^(Virtual tables can provide alternative implementations of functions
   4889 ** using the [xFindFunction] method of the [virtual table module].
   4890 ** But global versions of those functions
   4891 ** must exist in order to be overloaded.)^
   4892 **
   4893 ** ^(This API makes sure a global version of a function with a particular
   4894 ** name and number of parameters exists.  If no such function exists
   4895 ** before this API is called, a new function is created.)^  ^The implementation
   4896 ** of the new function always causes an exception to be thrown.  So
   4897 ** the new function is not good for anything by itself.  Its only
   4898 ** purpose is to be a placeholder function that can be overloaded
   4899 ** by a [virtual table].
   4900 */
   4901 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
   4902 
   4903 /*
   4904 ** The interface to the virtual-table mechanism defined above (back up
   4905 ** to a comment remarkably similar to this one) is currently considered
   4906 ** to be experimental.  The interface might change in incompatible ways.
   4907 ** If this is a problem for you, do not use the interface at this time.
   4908 **
   4909 ** When the virtual-table mechanism stabilizes, we will declare the
   4910 ** interface fixed, support it indefinitely, and remove this comment.
   4911 **
   4912 ****** EXPERIMENTAL - subject to change without notice **************
   4913 */
   4914 
   4915 /*
   4916 ** CAPI3REF: A Handle To An Open BLOB
   4917 ** KEYWORDS: {BLOB handle} {BLOB handles}
   4918 **
   4919 ** An instance of this object represents an open BLOB on which
   4920 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
   4921 ** ^Objects of this type are created by [sqlite3_blob_open()]
   4922 ** and destroyed by [sqlite3_blob_close()].
   4923 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
   4924 ** can be used to read or write small subsections of the BLOB.
   4925 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
   4926 */
   4927 typedef struct sqlite3_blob sqlite3_blob;
   4928 
   4929 /*
   4930 ** CAPI3REF: Open A BLOB For Incremental I/O
   4931 **
   4932 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
   4933 ** in row iRow, column zColumn, table zTable in database zDb;
   4934 ** in other words, the same BLOB that would be selected by:
   4935 **
   4936 ** <pre>
   4937 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
   4938 ** </pre>)^
   4939 **
   4940 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
   4941 ** and write access. ^If it is zero, the BLOB is opened for read access.
   4942 ** ^It is not possible to open a column that is part of an index or primary
   4943 ** key for writing. ^If [foreign key constraints] are enabled, it is
   4944 ** not possible to open a column that is part of a [child key] for writing.
   4945 **
   4946 ** ^Note that the database name is not the filename that contains
   4947 ** the database but rather the symbolic name of the database that
   4948 ** appears after the AS keyword when the database is connected using [ATTACH].
   4949 ** ^For the main database file, the database name is "main".
   4950 ** ^For TEMP tables, the database name is "temp".
   4951 **
   4952 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
   4953 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
   4954 ** to be a null pointer.)^
   4955 ** ^This function sets the [database connection] error code and message
   4956 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
   4957 ** functions. ^Note that the *ppBlob variable is always initialized in a
   4958 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
   4959 ** regardless of the success or failure of this routine.
   4960 **
   4961 ** ^(If the row that a BLOB handle points to is modified by an
   4962 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
   4963 ** then the BLOB handle is marked as "expired".
   4964 ** This is true if any column of the row is changed, even a column
   4965 ** other than the one the BLOB handle is open on.)^
   4966 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
   4967 ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
   4968 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
   4969 ** rolled back by the expiration of the BLOB.  Such changes will eventually
   4970 ** commit if the transaction continues to completion.)^
   4971 **
   4972 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
   4973 ** the opened blob.  ^The size of a blob may not be changed by this
   4974 ** interface.  Use the [UPDATE] SQL command to change the size of a
   4975 ** blob.
   4976 **
   4977 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
   4978 ** and the built-in [zeroblob] SQL function can be used, if desired,
   4979 ** to create an empty, zero-filled blob in which to read or write using
   4980 ** this interface.
   4981 **
   4982 ** To avoid a resource leak, every open [BLOB handle] should eventually
   4983 ** be released by a call to [sqlite3_blob_close()].
   4984 */
   4985 SQLITE_API int sqlite3_blob_open(
   4986   sqlite3*,
   4987   const char *zDb,
   4988   const char *zTable,
   4989   const char *zColumn,
   4990   sqlite3_int64 iRow,
   4991   int flags,
   4992   sqlite3_blob **ppBlob
   4993 );
   4994 
   4995 /*
   4996 ** CAPI3REF: Close A BLOB Handle
   4997 **
   4998 ** ^Closes an open [BLOB handle].
   4999 **
   5000 ** ^Closing a BLOB shall cause the current transaction to commit
   5001 ** if there are no other BLOBs, no pending prepared statements, and the
   5002 ** database connection is in [autocommit mode].
   5003 ** ^If any writes were made to the BLOB, they might be held in cache
   5004 ** until the close operation if they will fit.
   5005 **
   5006 ** ^(Closing the BLOB often forces the changes
   5007 ** out to disk and so if any I/O errors occur, they will likely occur
   5008 ** at the time when the BLOB is closed.  Any errors that occur during
   5009 ** closing are reported as a non-zero return value.)^
   5010 **
   5011 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
   5012 ** an error code, the BLOB is still closed.)^
   5013 **
   5014 ** ^Calling this routine with a null pointer (such as would be returned
   5015 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
   5016 */
   5017 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
   5018 
   5019 /*
   5020 ** CAPI3REF: Return The Size Of An Open BLOB
   5021 **
   5022 ** ^Returns the size in bytes of the BLOB accessible via the
   5023 ** successfully opened [BLOB handle] in its only argument.  ^The
   5024 ** incremental blob I/O routines can only read or overwriting existing
   5025 ** blob content; they cannot change the size of a blob.
   5026 **
   5027 ** This routine only works on a [BLOB handle] which has been created
   5028 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   5029 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   5030 ** to this routine results in undefined and probably undesirable behavior.
   5031 */
   5032 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
   5033 
   5034 /*
   5035 ** CAPI3REF: Read Data From A BLOB Incrementally
   5036 **
   5037 ** ^(This function is used to read data from an open [BLOB handle] into a
   5038 ** caller-supplied buffer. N bytes of data are copied into buffer Z
   5039 ** from the open BLOB, starting at offset iOffset.)^
   5040 **
   5041 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
   5042 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
   5043 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
   5044 ** ^The size of the blob (and hence the maximum value of N+iOffset)
   5045 ** can be determined using the [sqlite3_blob_bytes()] interface.
   5046 **
   5047 ** ^An attempt to read from an expired [BLOB handle] fails with an
   5048 ** error code of [SQLITE_ABORT].
   5049 **
   5050 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
   5051 ** Otherwise, an [error code] or an [extended error code] is returned.)^
   5052 **
   5053 ** This routine only works on a [BLOB handle] which has been created
   5054 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   5055 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   5056 ** to this routine results in undefined and probably undesirable behavior.
   5057 **
   5058 ** See also: [sqlite3_blob_write()].
   5059 */
   5060 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
   5061 
   5062 /*
   5063 ** CAPI3REF: Write Data Into A BLOB Incrementally
   5064 **
   5065 ** ^This function is used to write data into an open [BLOB handle] from a
   5066 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
   5067 ** into the open BLOB, starting at offset iOffset.
   5068 **
   5069 ** ^If the [BLOB handle] passed as the first argument was not opened for
   5070 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
   5071 ** this function returns [SQLITE_READONLY].
   5072 **
   5073 ** ^This function may only modify the contents of the BLOB; it is
   5074 ** not possible to increase the size of a BLOB using this API.
   5075 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
   5076 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
   5077 ** less than zero [SQLITE_ERROR] is returned and no data is written.
   5078 ** The size of the BLOB (and hence the maximum value of N+iOffset)
   5079 ** can be determined using the [sqlite3_blob_bytes()] interface.
   5080 **
   5081 ** ^An attempt to write to an expired [BLOB handle] fails with an
   5082 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
   5083 ** before the [BLOB handle] expired are not rolled back by the
   5084 ** expiration of the handle, though of course those changes might
   5085 ** have been overwritten by the statement that expired the BLOB handle
   5086 ** or by other independent statements.
   5087 **
   5088 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
   5089 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
   5090 **
   5091 ** This routine only works on a [BLOB handle] which has been created
   5092 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   5093 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   5094 ** to this routine results in undefined and probably undesirable behavior.
   5095 **
   5096 ** See also: [sqlite3_blob_read()].
   5097 */
   5098 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
   5099 
   5100 /*
   5101 ** CAPI3REF: Virtual File System Objects
   5102 **
   5103 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
   5104 ** that SQLite uses to interact
   5105 ** with the underlying operating system.  Most SQLite builds come with a
   5106 ** single default VFS that is appropriate for the host computer.
   5107 ** New VFSes can be registered and existing VFSes can be unregistered.
   5108 ** The following interfaces are provided.
   5109 **
   5110 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
   5111 ** ^Names are case sensitive.
   5112 ** ^Names are zero-terminated UTF-8 strings.
   5113 ** ^If there is no match, a NULL pointer is returned.
   5114 ** ^If zVfsName is NULL then the default VFS is returned.
   5115 **
   5116 ** ^New VFSes are registered with sqlite3_vfs_register().
   5117 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
   5118 ** ^The same VFS can be registered multiple times without injury.
   5119 ** ^To make an existing VFS into the default VFS, register it again
   5120 ** with the makeDflt flag set.  If two different VFSes with the
   5121 ** same name are registered, the behavior is undefined.  If a
   5122 ** VFS is registered with a name that is NULL or an empty string,
   5123 ** then the behavior is undefined.
   5124 **
   5125 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
   5126 ** ^(If the default VFS is unregistered, another VFS is chosen as
   5127 ** the default.  The choice for the new VFS is arbitrary.)^
   5128 */
   5129 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
   5130 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
   5131 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
   5132 
   5133 /*
   5134 ** CAPI3REF: Mutexes
   5135 **
   5136 ** The SQLite core uses these routines for thread
   5137 ** synchronization. Though they are intended for internal
   5138 ** use by SQLite, code that links against SQLite is
   5139 ** permitted to use any of these routines.
   5140 **
   5141 ** The SQLite source code contains multiple implementations
   5142 ** of these mutex routines.  An appropriate implementation
   5143 ** is selected automatically at compile-time.  ^(The following
   5144 ** implementations are available in the SQLite core:
   5145 **
   5146 ** <ul>
   5147 ** <li>   SQLITE_MUTEX_OS2
   5148 ** <li>   SQLITE_MUTEX_PTHREAD
   5149 ** <li>   SQLITE_MUTEX_W32
   5150 ** <li>   SQLITE_MUTEX_NOOP
   5151 ** </ul>)^
   5152 **
   5153 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
   5154 ** that does no real locking and is appropriate for use in
   5155 ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
   5156 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
   5157 ** are appropriate for use on OS/2, Unix, and Windows.
   5158 **
   5159 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
   5160 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
   5161 ** implementation is included with the library. In this case the
   5162 ** application must supply a custom mutex implementation using the
   5163 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
   5164 ** before calling sqlite3_initialize() or any other public sqlite3_
   5165 ** function that calls sqlite3_initialize().)^
   5166 **
   5167 ** ^The sqlite3_mutex_alloc() routine allocates a new
   5168 ** mutex and returns a pointer to it. ^If it returns NULL
   5169 ** that means that a mutex could not be allocated.  ^SQLite
   5170 ** will unwind its stack and return an error.  ^(The argument
   5171 ** to sqlite3_mutex_alloc() is one of these integer constants:
   5172 **
   5173 ** <ul>
   5174 ** <li>  SQLITE_MUTEX_FAST
   5175 ** <li>  SQLITE_MUTEX_RECURSIVE
   5176 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   5177 ** <li>  SQLITE_MUTEX_STATIC_MEM
   5178 ** <li>  SQLITE_MUTEX_STATIC_MEM2
   5179 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   5180 ** <li>  SQLITE_MUTEX_STATIC_LRU
   5181 ** <li>  SQLITE_MUTEX_STATIC_LRU2
   5182 ** </ul>)^
   5183 **
   5184 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
   5185 ** cause sqlite3_mutex_alloc() to create
   5186 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   5187 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   5188 ** The mutex implementation does not need to make a distinction
   5189 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   5190 ** not want to.  ^SQLite will only request a recursive mutex in
   5191 ** cases where it really needs one.  ^If a faster non-recursive mutex
   5192 ** implementation is available on the host platform, the mutex subsystem
   5193 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   5194 **
   5195 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
   5196 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
   5197 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
   5198 ** used by the current version of SQLite.  Future versions of SQLite
   5199 ** may add additional static mutexes.  Static mutexes are for internal
   5200 ** use by SQLite only.  Applications that use SQLite mutexes should
   5201 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   5202 ** SQLITE_MUTEX_RECURSIVE.
   5203 **
   5204 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   5205 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   5206 ** returns a different mutex on every call.  ^But for the static
   5207 ** mutex types, the same mutex is returned on every call that has
   5208 ** the same type number.
   5209 **
   5210 ** ^The sqlite3_mutex_free() routine deallocates a previously
   5211 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
   5212 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
   5213 ** use when they are deallocated.  Attempting to deallocate a static
   5214 ** mutex results in undefined behavior.  ^SQLite never deallocates
   5215 ** a static mutex.
   5216 **
   5217 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   5218 ** to enter a mutex.  ^If another thread is already within the mutex,
   5219 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   5220 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
   5221 ** upon successful entry.  ^(Mutexes created using
   5222 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
   5223 ** In such cases the,
   5224 ** mutex must be exited an equal number of times before another thread
   5225 ** can enter.)^  ^(If the same thread tries to enter any other
   5226 ** kind of mutex more than once, the behavior is undefined.
   5227 ** SQLite will never exhibit
   5228 ** such behavior in its own use of mutexes.)^
   5229 **
   5230 ** ^(Some systems (for example, Windows 95) do not support the operation
   5231 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
   5232 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
   5233 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
   5234 **
   5235 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
   5236 ** previously entered by the same thread.   ^(The behavior
   5237 ** is undefined if the mutex is not currently entered by the
   5238 ** calling thread or is not currently allocated.  SQLite will
   5239 ** never do either.)^
   5240 **
   5241 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
   5242 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
   5243 ** behave as no-ops.
   5244 **
   5245 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
   5246 */
   5247 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
   5248 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
   5249 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
   5250 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
   5251 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
   5252 
   5253 /*
   5254 ** CAPI3REF: Mutex Methods Object
   5255 ** EXPERIMENTAL
   5256 **
   5257 ** An instance of this structure defines the low-level routines
   5258 ** used to allocate and use mutexes.
   5259 **
   5260 ** Usually, the default mutex implementations provided by SQLite are
   5261 ** sufficient, however the user has the option of substituting a custom
   5262 ** implementation for specialized deployments or systems for which SQLite
   5263 ** does not provide a suitable implementation. In this case, the user
   5264 ** creates and populates an instance of this structure to pass
   5265 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
   5266 ** Additionally, an instance of this structure can be used as an
   5267 ** output variable when querying the system for the current mutex
   5268 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
   5269 **
   5270 ** ^The xMutexInit method defined by this structure is invoked as
   5271 ** part of system initialization by the sqlite3_initialize() function.
   5272 ** ^The xMutexInit routine is calle by SQLite exactly once for each
   5273 ** effective call to [sqlite3_initialize()].
   5274 **
   5275 ** ^The xMutexEnd method defined by this structure is invoked as
   5276 ** part of system shutdown by the sqlite3_shutdown() function. The
   5277 ** implementation of this method is expected to release all outstanding
   5278 ** resources obtained by the mutex methods implementation, especially
   5279 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
   5280 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
   5281 **
   5282 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
   5283 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
   5284 ** xMutexNotheld) implement the following interfaces (respectively):
   5285 **
   5286 ** <ul>
   5287 **   <li>  [sqlite3_mutex_alloc()] </li>
   5288 **   <li>  [sqlite3_mutex_free()] </li>
   5289 **   <li>  [sqlite3_mutex_enter()] </li>
   5290 **   <li>  [sqlite3_mutex_try()] </li>
   5291 **   <li>  [sqlite3_mutex_leave()] </li>
   5292 **   <li>  [sqlite3_mutex_held()] </li>
   5293 **   <li>  [sqlite3_mutex_notheld()] </li>
   5294 ** </ul>)^
   5295 **
   5296 ** The only difference is that the public sqlite3_XXX functions enumerated
   5297 ** above silently ignore any invocations that pass a NULL pointer instead
   5298 ** of a valid mutex handle. The implementations of the methods defined
   5299 ** by this structure are not required to handle this case, the results
   5300 ** of passing a NULL pointer instead of a valid mutex handle are undefined
   5301 ** (i.e. it is acceptable to provide an implementation that segfaults if
   5302 ** it is passed a NULL pointer).
   5303 **
   5304 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
   5305 ** invoke xMutexInit() mutiple times within the same process and without
   5306 ** intervening calls to xMutexEnd().  Second and subsequent calls to
   5307 ** xMutexInit() must be no-ops.
   5308 **
   5309 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
   5310 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
   5311 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
   5312 ** memory allocation for a fast or recursive mutex.
   5313 **
   5314 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
   5315 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
   5316 ** If xMutexInit fails in any way, it is expected to clean up after itself
   5317 ** prior to returning.
   5318 */
   5319 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
   5320 struct sqlite3_mutex_methods {
   5321   int (*xMutexInit)(void);
   5322   int (*xMutexEnd)(void);
   5323   sqlite3_mutex *(*xMutexAlloc)(int);
   5324   void (*xMutexFree)(sqlite3_mutex *);
   5325   void (*xMutexEnter)(sqlite3_mutex *);
   5326   int (*xMutexTry)(sqlite3_mutex *);
   5327   void (*xMutexLeave)(sqlite3_mutex *);
   5328   int (*xMutexHeld)(sqlite3_mutex *);
   5329   int (*xMutexNotheld)(sqlite3_mutex *);
   5330 };
   5331 
   5332 /*
   5333 ** CAPI3REF: Mutex Verification Routines
   5334 **
   5335 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
   5336 ** are intended for use inside assert() statements.  ^The SQLite core
   5337 ** never uses these routines except inside an assert() and applications
   5338 ** are advised to follow the lead of the core.  ^The SQLite core only
   5339 ** provides implementations for these routines when it is compiled
   5340 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
   5341 ** are only required to provide these routines if SQLITE_DEBUG is
   5342 ** defined and if NDEBUG is not defined.
   5343 **
   5344 ** ^These routines should return true if the mutex in their argument
   5345 ** is held or not held, respectively, by the calling thread.
   5346 **
   5347 ** ^The implementation is not required to provided versions of these
   5348 ** routines that actually work. If the implementation does not provide working
   5349 ** versions of these routines, it should at least provide stubs that always
   5350 ** return true so that one does not get spurious assertion failures.
   5351 **
   5352 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
   5353 ** the routine should return 1.   This seems counter-intuitive since
   5354 ** clearly the mutex cannot be held if it does not exist.  But the
   5355 ** the reason the mutex does not exist is because the build is not
   5356 ** using mutexes.  And we do not want the assert() containing the
   5357 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
   5358 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
   5359 ** interface should also return 1 when given a NULL pointer.
   5360 */
   5361 #ifndef NDEBUG
   5362 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
   5363 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
   5364 #endif
   5365 
   5366 /*
   5367 ** CAPI3REF: Mutex Types
   5368 **
   5369 ** The [sqlite3_mutex_alloc()] interface takes a single argument
   5370 ** which is one of these integer constants.
   5371 **
   5372 ** The set of static mutexes may change from one SQLite release to the
   5373 ** next.  Applications that override the built-in mutex logic must be
   5374 ** prepared to accommodate additional static mutexes.
   5375 */
   5376 #define SQLITE_MUTEX_FAST             0
   5377 #define SQLITE_MUTEX_RECURSIVE        1
   5378 #define SQLITE_MUTEX_STATIC_MASTER    2
   5379 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
   5380 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
   5381 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
   5382 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
   5383 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
   5384 #define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
   5385 
   5386 /*
   5387 ** CAPI3REF: Retrieve the mutex for a database connection
   5388 **
   5389 ** ^This interface returns a pointer the [sqlite3_mutex] object that
   5390 ** serializes access to the [database connection] given in the argument
   5391 ** when the [threading mode] is Serialized.
   5392 ** ^If the [threading mode] is Single-thread or Multi-thread then this
   5393 ** routine returns a NULL pointer.
   5394 */
   5395 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
   5396 
   5397 /*
   5398 ** CAPI3REF: Low-Level Control Of Database Files
   5399 **
   5400 ** ^The [sqlite3_file_control()] interface makes a direct call to the
   5401 ** xFileControl method for the [sqlite3_io_methods] object associated
   5402 ** with a particular database identified by the second argument. ^The
   5403 ** name of the database "main" for the main database or "temp" for the
   5404 ** TEMP database, or the name that appears after the AS keyword for
   5405 ** databases that are added using the [ATTACH] SQL command.
   5406 ** ^A NULL pointer can be used in place of "main" to refer to the
   5407 ** main database file.
   5408 ** ^The third and fourth parameters to this routine
   5409 ** are passed directly through to the second and third parameters of
   5410 ** the xFileControl method.  ^The return value of the xFileControl
   5411 ** method becomes the return value of this routine.
   5412 **
   5413 ** ^If the second parameter (zDbName) does not match the name of any
   5414 ** open database file, then SQLITE_ERROR is returned.  ^This error
   5415 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
   5416 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
   5417 ** also return SQLITE_ERROR.  There is no way to distinguish between
   5418 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
   5419 ** xFileControl method.
   5420 **
   5421 ** See also: [SQLITE_FCNTL_LOCKSTATE]
   5422 */
   5423 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
   5424 
   5425 /*
   5426 ** CAPI3REF: Testing Interface
   5427 **
   5428 ** ^The sqlite3_test_control() interface is used to read out internal
   5429 ** state of SQLite and to inject faults into SQLite for testing
   5430 ** purposes.  ^The first parameter is an operation code that determines
   5431 ** the number, meaning, and operation of all subsequent parameters.
   5432 **
   5433 ** This interface is not for use by applications.  It exists solely
   5434 ** for verifying the correct operation of the SQLite library.  Depending
   5435 ** on how the SQLite library is compiled, this interface might not exist.
   5436 **
   5437 ** The details of the operation codes, their meanings, the parameters
   5438 ** they take, and what they do are all subject to change without notice.
   5439 ** Unlike most of the SQLite API, this function is not guaranteed to
   5440 ** operate consistently from one release to the next.
   5441 */
   5442 SQLITE_API int sqlite3_test_control(int op, ...);
   5443 
   5444 /*
   5445 ** CAPI3REF: Testing Interface Operation Codes
   5446 **
   5447 ** These constants are the valid operation code parameters used
   5448 ** as the first argument to [sqlite3_test_control()].
   5449 **
   5450 ** These parameters and their meanings are subject to change
   5451 ** without notice.  These values are for testing purposes only.
   5452 ** Applications should not use any of these parameters or the
   5453 ** [sqlite3_test_control()] interface.
   5454 */
   5455 #define SQLITE_TESTCTRL_FIRST                    5
   5456 #define SQLITE_TESTCTRL_PRNG_SAVE                5
   5457 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
   5458 #define SQLITE_TESTCTRL_PRNG_RESET               7
   5459 #define SQLITE_TESTCTRL_BITVEC_TEST              8
   5460 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
   5461 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
   5462 #define SQLITE_TESTCTRL_PENDING_BYTE            11
   5463 #define SQLITE_TESTCTRL_ASSERT                  12
   5464 #define SQLITE_TESTCTRL_ALWAYS                  13
   5465 #define SQLITE_TESTCTRL_RESERVE                 14
   5466 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
   5467 #define SQLITE_TESTCTRL_ISKEYWORD               16
   5468 #define SQLITE_TESTCTRL_LAST                    16
   5469 
   5470 /*
   5471 ** CAPI3REF: SQLite Runtime Status
   5472 ** EXPERIMENTAL
   5473 **
   5474 ** ^This interface is used to retrieve runtime status information
   5475 ** about the preformance of SQLite, and optionally to reset various
   5476 ** highwater marks.  ^The first argument is an integer code for
   5477 ** the specific parameter to measure.  ^(Recognized integer codes
   5478 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
   5479 ** ^The current value of the parameter is returned into *pCurrent.
   5480 ** ^The highest recorded value is returned in *pHighwater.  ^If the
   5481 ** resetFlag is true, then the highest record value is reset after
   5482 ** *pHighwater is written.  ^(Some parameters do not record the highest
   5483 ** value.  For those parameters
   5484 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
   5485 ** ^(Other parameters record only the highwater mark and not the current
   5486 ** value.  For these latter parameters nothing is written into *pCurrent.)^
   5487 **
   5488 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
   5489 ** non-zero [error code] on failure.
   5490 **
   5491 ** This routine is threadsafe but is not atomic.  This routine can be
   5492 ** called while other threads are running the same or different SQLite
   5493 ** interfaces.  However the values returned in *pCurrent and
   5494 ** *pHighwater reflect the status of SQLite at different points in time
   5495 ** and it is possible that another thread might change the parameter
   5496 ** in between the times when *pCurrent and *pHighwater are written.
   5497 **
   5498 ** See also: [sqlite3_db_status()]
   5499 */
   5500 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
   5501 
   5502 
   5503 /*
   5504 ** CAPI3REF: Status Parameters
   5505 ** EXPERIMENTAL
   5506 **
   5507 ** These integer constants designate various run-time status parameters
   5508 ** that can be returned by [sqlite3_status()].
   5509 **
   5510 ** <dl>
   5511 ** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
   5512 ** <dd>This parameter is the current amount of memory checked out
   5513 ** using [sqlite3_malloc()], either directly or indirectly.  The
   5514 ** figure includes calls made to [sqlite3_malloc()] by the application
   5515 ** and internal memory usage by the SQLite library.  Scratch memory
   5516 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
   5517 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
   5518 ** this parameter.  The amount returned is the sum of the allocation
   5519 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
   5520 **
   5521 ** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
   5522 ** <dd>This parameter records the largest memory allocation request
   5523 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
   5524 ** internal equivalents).  Only the value returned in the
   5525 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   5526 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   5527 **
   5528 ** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
   5529 ** <dd>This parameter returns the number of pages used out of the
   5530 ** [pagecache memory allocator] that was configured using
   5531 ** [SQLITE_CONFIG_PAGECACHE].  The
   5532 ** value returned is in pages, not in bytes.</dd>)^
   5533 **
   5534 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
   5535 ** <dd>This parameter returns the number of bytes of page cache
   5536 ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
   5537 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
   5538 ** returned value includes allocations that overflowed because they
   5539 ** where too large (they were larger than the "sz" parameter to
   5540 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
   5541 ** no space was left in the page cache.</dd>)^
   5542 **
   5543 ** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
   5544 ** <dd>This parameter records the largest memory allocation request
   5545 ** handed to [pagecache memory allocator].  Only the value returned in the
   5546 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   5547 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   5548 **
   5549 ** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
   5550 ** <dd>This parameter returns the number of allocations used out of the
   5551 ** [scratch memory allocator] configured using
   5552 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
   5553 ** in bytes.  Since a single thread may only have one scratch allocation
   5554 ** outstanding at time, this parameter also reports the number of threads
   5555 ** using scratch memory at the same time.</dd>)^
   5556 **
   5557 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
   5558 ** <dd>This parameter returns the number of bytes of scratch memory
   5559 ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
   5560 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
   5561 ** returned include overflows because the requested allocation was too
   5562 ** larger (that is, because the requested allocation was larger than the
   5563 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
   5564 ** slots were available.
   5565 ** </dd>)^
   5566 **
   5567 ** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
   5568 ** <dd>This parameter records the largest memory allocation request
   5569 ** handed to [scratch memory allocator].  Only the value returned in the
   5570 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   5571 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   5572 **
   5573 ** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
   5574 ** <dd>This parameter records the deepest parser stack.  It is only
   5575 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
   5576 ** </dl>
   5577 **
   5578 ** New status parameters may be added from time to time.
   5579 */
   5580 #define SQLITE_STATUS_MEMORY_USED          0
   5581 #define SQLITE_STATUS_PAGECACHE_USED       1
   5582 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
   5583 #define SQLITE_STATUS_SCRATCH_USED         3
   5584 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
   5585 #define SQLITE_STATUS_MALLOC_SIZE          5
   5586 #define SQLITE_STATUS_PARSER_STACK         6
   5587 #define SQLITE_STATUS_PAGECACHE_SIZE       7
   5588 #define SQLITE_STATUS_SCRATCH_SIZE         8
   5589 
   5590 /*
   5591 ** CAPI3REF: Database Connection Status
   5592 ** EXPERIMENTAL
   5593 **
   5594 ** ^This interface is used to retrieve runtime status information
   5595 ** about a single [database connection].  ^The first argument is the
   5596 ** database connection object to be interrogated.  ^The second argument
   5597 ** is the parameter to interrogate.  ^Currently, the only allowed value
   5598 ** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
   5599 ** Additional options will likely appear in future releases of SQLite.
   5600 **
   5601 ** ^The current value of the requested parameter is written into *pCur
   5602 ** and the highest instantaneous value is written into *pHiwtr.  ^If
   5603 ** the resetFlg is true, then the highest instantaneous value is
   5604 ** reset back down to the current value.
   5605 **
   5606 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
   5607 */
   5608 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
   5609 
   5610 /*
   5611 ** CAPI3REF: Status Parameters for database connections
   5612 ** EXPERIMENTAL
   5613 **
   5614 ** These constants are the available integer "verbs" that can be passed as
   5615 ** the second argument to the [sqlite3_db_status()] interface.
   5616 **
   5617 ** New verbs may be added in future releases of SQLite. Existing verbs
   5618 ** might be discontinued. Applications should check the return code from
   5619 ** [sqlite3_db_status()] to make sure that the call worked.
   5620 ** The [sqlite3_db_status()] interface will return a non-zero error code
   5621 ** if a discontinued or unsupported verb is invoked.
   5622 **
   5623 ** <dl>
   5624 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
   5625 ** <dd>This parameter returns the number of lookaside memory slots currently
   5626 ** checked out.</dd>)^
   5627 ** </dl>
   5628 */
   5629 #define SQLITE_DBSTATUS_LOOKASIDE_USED     0
   5630 
   5631 
   5632 /*
   5633 ** CAPI3REF: Prepared Statement Status
   5634 ** EXPERIMENTAL
   5635 **
   5636 ** ^(Each prepared statement maintains various
   5637 ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
   5638 ** of times it has performed specific operations.)^  These counters can
   5639 ** be used to monitor the performance characteristics of the prepared
   5640 ** statements.  For example, if the number of table steps greatly exceeds
   5641 ** the number of table searches or result rows, that would tend to indicate
   5642 ** that the prepared statement is using a full table scan rather than
   5643 ** an index.
   5644 **
   5645 ** ^(This interface is used to retrieve and reset counter values from
   5646 ** a [prepared statement].  The first argument is the prepared statement
   5647 ** object to be interrogated.  The second argument
   5648 ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
   5649 ** to be interrogated.)^
   5650 ** ^The current value of the requested counter is returned.
   5651 ** ^If the resetFlg is true, then the counter is reset to zero after this
   5652 ** interface call returns.
   5653 **
   5654 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
   5655 */
   5656 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
   5657 
   5658 /*
   5659 ** CAPI3REF: Status Parameters for prepared statements
   5660 ** EXPERIMENTAL
   5661 **
   5662 ** These preprocessor macros define integer codes that name counter
   5663 ** values associated with the [sqlite3_stmt_status()] interface.
   5664 ** The meanings of the various counters are as follows:
   5665 **
   5666 ** <dl>
   5667 ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
   5668 ** <dd>^This is the number of times that SQLite has stepped forward in
   5669 ** a table as part of a full table scan.  Large numbers for this counter
   5670 ** may indicate opportunities for performance improvement through
   5671 ** careful use of indices.</dd>
   5672 **
   5673 ** <dt>SQLITE_STMTSTATUS_SORT</dt>
   5674 ** <dd>^This is the number of sort operations that have occurred.
   5675 ** A non-zero value in this counter may indicate an opportunity to
   5676 ** improvement performance through careful use of indices.</dd>
   5677 **
   5678 ** </dl>
   5679 */
   5680 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
   5681 #define SQLITE_STMTSTATUS_SORT              2
   5682 
   5683 /*
   5684 ** CAPI3REF: Custom Page Cache Object
   5685 ** EXPERIMENTAL
   5686 **
   5687 ** The sqlite3_pcache type is opaque.  It is implemented by
   5688 ** the pluggable module.  The SQLite core has no knowledge of
   5689 ** its size or internal structure and never deals with the
   5690 ** sqlite3_pcache object except by holding and passing pointers
   5691 ** to the object.
   5692 **
   5693 ** See [sqlite3_pcache_methods] for additional information.
   5694 */
   5695 typedef struct sqlite3_pcache sqlite3_pcache;
   5696 
   5697 /*
   5698 ** CAPI3REF: Application Defined Page Cache.
   5699 ** KEYWORDS: {page cache}
   5700 ** EXPERIMENTAL
   5701 **
   5702 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
   5703 ** register an alternative page cache implementation by passing in an
   5704 ** instance of the sqlite3_pcache_methods structure.)^ The majority of the
   5705 ** heap memory used by SQLite is used by the page cache to cache data read
   5706 ** from, or ready to be written to, the database file. By implementing a
   5707 ** custom page cache using this API, an application can control more
   5708 ** precisely the amount of memory consumed by SQLite, the way in which
   5709 ** that memory is allocated and released, and the policies used to
   5710 ** determine exactly which parts of a database file are cached and for
   5711 ** how long.
   5712 **
   5713 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
   5714 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
   5715 ** the application may discard the parameter after the call to
   5716 ** [sqlite3_config()] returns.)^
   5717 **
   5718 ** ^The xInit() method is called once for each call to [sqlite3_initialize()]
   5719 ** (usually only once during the lifetime of the process). ^(The xInit()
   5720 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
   5721 ** ^The xInit() method can set up up global structures and/or any mutexes
   5722 ** required by the custom page cache implementation.
   5723 **
   5724 ** ^The xShutdown() method is called from within [sqlite3_shutdown()],
   5725 ** if the application invokes this API. It can be used to clean up
   5726 ** any outstanding resources before process shutdown, if required.
   5727 **
   5728 ** ^SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
   5729 ** the xInit method, so the xInit method need not be threadsafe.  ^The
   5730 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
   5731 ** not need to be threadsafe either.  All other methods must be threadsafe
   5732 ** in multithreaded applications.
   5733 **
   5734 ** ^SQLite will never invoke xInit() more than once without an intervening
   5735 ** call to xShutdown().
   5736 **
   5737 ** ^The xCreate() method is used to construct a new cache instance.  SQLite
   5738 ** will typically create one cache instance for each open database file,
   5739 ** though this is not guaranteed. ^The
   5740 ** first parameter, szPage, is the size in bytes of the pages that must
   5741 ** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
   5742 ** will the page size of the database file that is to be cached plus an
   5743 ** increment (here called "R") of about 100 or 200.  ^SQLite will use the
   5744 ** extra R bytes on each page to store metadata about the underlying
   5745 ** database page on disk.  The value of R depends
   5746 ** on the SQLite version, the target platform, and how SQLite was compiled.
   5747 ** ^R is constant for a particular build of SQLite.  ^The second argument to
   5748 ** xCreate(), bPurgeable, is true if the cache being created will
   5749 ** be used to cache database pages of a file stored on disk, or
   5750 ** false if it is used for an in-memory database. ^The cache implementation
   5751 ** does not have to do anything special based with the value of bPurgeable;
   5752 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
   5753 ** never invoke xUnpin() except to deliberately delete a page.
   5754 ** ^In other words, a cache created with bPurgeable set to false will
   5755 ** never contain any unpinned pages.
   5756 **
   5757 ** ^(The xCachesize() method may be called at any time by SQLite to set the
   5758 ** suggested maximum cache-size (number of pages stored by) the cache
   5759 ** instance passed as the first argument. This is the value configured using
   5760 ** the SQLite "[PRAGMA cache_size]" command.)^  ^As with the bPurgeable
   5761 ** parameter, the implementation is not required to do anything with this
   5762 ** value; it is advisory only.
   5763 **
   5764 ** ^The xPagecount() method should return the number of pages currently
   5765 ** stored in the cache.
   5766 **
   5767 ** ^The xFetch() method is used to fetch a page and return a pointer to it.
   5768 ** ^A 'page', in this context, is a buffer of szPage bytes aligned at an
   5769 ** 8-byte boundary. ^The page to be fetched is determined by the key. ^The
   5770 ** mimimum key value is 1. After it has been retrieved using xFetch, the page
   5771 ** is considered to be "pinned".
   5772 **
   5773 ** ^If the requested page is already in the page cache, then the page cache
   5774 ** implementation must return a pointer to the page buffer with its content
   5775 ** intact.  ^(If the requested page is not already in the cache, then the
   5776 ** behavior of the cache implementation is determined by the value of the
   5777 ** createFlag parameter passed to xFetch, according to the following table:
   5778 **
   5779 ** <table border=1 width=85% align=center>
   5780 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
   5781 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
   5782 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
   5783 **                 Otherwise return NULL.
   5784 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
   5785 **                 NULL if allocating a new page is effectively impossible.
   5786 ** </table>)^
   5787 **
   5788 ** SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  If
   5789 ** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
   5790 ** attempt to unpin one or more cache pages by spilling the content of
   5791 ** pinned pages to disk and synching the operating system disk cache. After
   5792 ** attempting to unpin pages, the xFetch() method will be invoked again with
   5793 ** a createFlag of 2.
   5794 **
   5795 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
   5796 ** as its second argument. ^(If the third parameter, discard, is non-zero,
   5797 ** then the page should be evicted from the cache. In this case SQLite
   5798 ** assumes that the next time the page is retrieved from the cache using
   5799 ** the xFetch() method, it will be zeroed.)^ ^If the discard parameter is
   5800 ** zero, then the page is considered to be unpinned. ^The cache implementation
   5801 ** may choose to evict unpinned pages at any time.
   5802 **
   5803 ** ^(The cache is not required to perform any reference counting. A single
   5804 ** call to xUnpin() unpins the page regardless of the number of prior calls
   5805 ** to xFetch().)^
   5806 **
   5807 ** ^The xRekey() method is used to change the key value associated with the
   5808 ** page passed as the second argument from oldKey to newKey. ^If the cache
   5809 ** previously contains an entry associated with newKey, it should be
   5810 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
   5811 ** to be pinned.
   5812 **
   5813 ** ^When SQLite calls the xTruncate() method, the cache must discard all
   5814 ** existing cache entries with page numbers (keys) greater than or equal
   5815 ** to the value of the iLimit parameter passed to xTruncate(). ^If any
   5816 ** of these pages are pinned, they are implicitly unpinned, meaning that
   5817 ** they can be safely discarded.
   5818 **
   5819 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
   5820 ** All resources associated with the specified cache should be freed. ^After
   5821 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
   5822 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
   5823 ** functions.
   5824 */
   5825 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
   5826 struct sqlite3_pcache_methods {
   5827   void *pArg;
   5828   int (*xInit)(void*);
   5829   void (*xShutdown)(void*);
   5830   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
   5831   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
   5832   int (*xPagecount)(sqlite3_pcache*);
   5833   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
   5834   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
   5835   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
   5836   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
   5837   void (*xDestroy)(sqlite3_pcache*);
   5838 };
   5839 
   5840 /*
   5841 ** CAPI3REF: Online Backup Object
   5842 ** EXPERIMENTAL
   5843 **
   5844 ** The sqlite3_backup object records state information about an ongoing
   5845 ** online backup operation.  ^The sqlite3_backup object is created by
   5846 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
   5847 ** [sqlite3_backup_finish()].
   5848 **
   5849 ** See Also: [Using the SQLite Online Backup API]
   5850 */
   5851 typedef struct sqlite3_backup sqlite3_backup;
   5852 
   5853 /*
   5854 ** CAPI3REF: Online Backup API.
   5855 ** EXPERIMENTAL
   5856 **
   5857 ** The backup API copies the content of one database into another.
   5858 ** It is useful either for creating backups of databases or
   5859 ** for copying in-memory databases to or from persistent files.
   5860 **
   5861 ** See Also: [Using the SQLite Online Backup API]
   5862 **
   5863 ** ^Exclusive access is required to the destination database for the
   5864 ** duration of the operation. ^However the source database is only
   5865 ** read-locked while it is actually being read; it is not locked
   5866 ** continuously for the entire backup operation. ^Thus, the backup may be
   5867 ** performed on a live source database without preventing other users from
   5868 ** reading or writing to the source database while the backup is underway.
   5869 **
   5870 ** ^(To perform a backup operation:
   5871 **   <ol>
   5872 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
   5873 **         backup,
   5874 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
   5875 **         the data between the two databases, and finally
   5876 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources
   5877 **         associated with the backup operation.
   5878 **   </ol>)^
   5879 ** There should be exactly one call to sqlite3_backup_finish() for each
   5880 ** successful call to sqlite3_backup_init().
   5881 **
   5882 ** <b>sqlite3_backup_init()</b>
   5883 **
   5884 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
   5885 ** [database connection] associated with the destination database
   5886 ** and the database name, respectively.
   5887 ** ^The database name is "main" for the main database, "temp" for the
   5888 ** temporary database, or the name specified after the AS keyword in
   5889 ** an [ATTACH] statement for an attached database.
   5890 ** ^The S and M arguments passed to
   5891 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
   5892 ** and database name of the source database, respectively.
   5893 ** ^The source and destination [database connections] (parameters S and D)
   5894 ** must be different or else sqlite3_backup_init(D,N,S,M) will file with
   5895 ** an error.
   5896 **
   5897 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
   5898 ** returned and an error code and error message are store3d in the
   5899 ** destination [database connection] D.
   5900 ** ^The error code and message for the failed call to sqlite3_backup_init()
   5901 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
   5902 ** [sqlite3_errmsg16()] functions.
   5903 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
   5904 ** [sqlite3_backup] object.
   5905 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
   5906 ** sqlite3_backup_finish() functions to perform the specified backup
   5907 ** operation.
   5908 **
   5909 ** <b>sqlite3_backup_step()</b>
   5910 **
   5911 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
   5912 ** the source and destination databases specified by [sqlite3_backup] object B.
   5913 ** ^If N is negative, all remaining source pages are copied.
   5914 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
   5915 ** are still more pages to be copied, then the function resturns [SQLITE_OK].
   5916 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
   5917 ** from source to destination, then it returns [SQLITE_DONE].
   5918 ** ^If an error occurs while running sqlite3_backup_step(B,N),
   5919 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
   5920 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
   5921 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
   5922 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
   5923 **
   5924 ** ^The sqlite3_backup_step() might return [SQLITE_READONLY] if the destination
   5925 ** database was opened read-only or if
   5926 ** the destination is an in-memory database with a different page size
   5927 ** from the source database.
   5928 **
   5929 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
   5930 ** the [sqlite3_busy_handler | busy-handler function]
   5931 ** is invoked (if one is specified). ^If the
   5932 ** busy-handler returns non-zero before the lock is available, then
   5933 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
   5934 ** sqlite3_backup_step() can be retried later. ^If the source
   5935 ** [database connection]
   5936 ** is being used to write to the source database when sqlite3_backup_step()
   5937 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
   5938 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
   5939 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
   5940 ** [SQLITE_READONLY] is returned, then
   5941 ** there is no point in retrying the call to sqlite3_backup_step(). These
   5942 ** errors are considered fatal.)^  The application must accept
   5943 ** that the backup operation has failed and pass the backup operation handle
   5944 ** to the sqlite3_backup_finish() to release associated resources.
   5945 **
   5946 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
   5947 ** on the destination file. ^The exclusive lock is not released until either
   5948 ** sqlite3_backup_finish() is called or the backup operation is complete
   5949 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
   5950 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
   5951 ** lasts for the duration of the sqlite3_backup_step() call.
   5952 ** ^Because the source database is not locked between calls to
   5953 ** sqlite3_backup_step(), the source database may be modified mid-way
   5954 ** through the backup process.  ^If the source database is modified by an
   5955 ** external process or via a database connection other than the one being
   5956 ** used by the backup operation, then the backup will be automatically
   5957 ** restarted by the next call to sqlite3_backup_step(). ^If the source
   5958 ** database is modified by the using the same database connection as is used
   5959 ** by the backup operation, then the backup database is automatically
   5960 ** updated at the same time.
   5961 **
   5962 ** <b>sqlite3_backup_finish()</b>
   5963 **
   5964 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
   5965 ** application wishes to abandon the backup operation, the application
   5966 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
   5967 ** ^The sqlite3_backup_finish() interfaces releases all
   5968 ** resources associated with the [sqlite3_backup] object.
   5969 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
   5970 ** active write-transaction on the destination database is rolled back.
   5971 ** The [sqlite3_backup] object is invalid
   5972 ** and may not be used following a call to sqlite3_backup_finish().
   5973 **
   5974 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
   5975 ** sqlite3_backup_step() errors occurred, regardless or whether or not
   5976 ** sqlite3_backup_step() completed.
   5977 ** ^If an out-of-memory condition or IO error occurred during any prior
   5978 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
   5979 ** sqlite3_backup_finish() returns the corresponding [error code].
   5980 **
   5981 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
   5982 ** is not a permanent error and does not affect the return value of
   5983 ** sqlite3_backup_finish().
   5984 **
   5985 ** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
   5986 **
   5987 ** ^Each call to sqlite3_backup_step() sets two values inside
   5988 ** the [sqlite3_backup] object: the number of pages still to be backed
   5989 ** up and the total number of pages in the source databae file.
   5990 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
   5991 ** retrieve these two values, respectively.
   5992 **
   5993 ** ^The values returned by these functions are only updated by
   5994 ** sqlite3_backup_step(). ^If the source database is modified during a backup
   5995 ** operation, then the values are not updated to account for any extra
   5996 ** pages that need to be updated or the size of the source database file
   5997 ** changing.
   5998 **
   5999 ** <b>Concurrent Usage of Database Handles</b>
   6000 **
   6001 ** ^The source [database connection] may be used by the application for other
   6002 ** purposes while a backup operation is underway or being initialized.
   6003 ** ^If SQLite is compiled and configured to support threadsafe database
   6004 ** connections, then the source database connection may be used concurrently
   6005 ** from within other threads.
   6006 **
   6007 ** However, the application must guarantee that the destination
   6008 ** [database connection] is not passed to any other API (by any thread) after
   6009 ** sqlite3_backup_init() is called and before the corresponding call to
   6010 ** sqlite3_backup_finish().  SQLite does not currently check to see
   6011 ** if the application incorrectly accesses the destination [database connection]
   6012 ** and so no error code is reported, but the operations may malfunction
   6013 ** nevertheless.  Use of the destination database connection while a
   6014 ** backup is in progress might also also cause a mutex deadlock.
   6015 **
   6016 ** If running in [shared cache mode], the application must
   6017 ** guarantee that the shared cache used by the destination database
   6018 ** is not accessed while the backup is running. In practice this means
   6019 ** that the application must guarantee that the disk file being
   6020 ** backed up to is not accessed by any connection within the process,
   6021 ** not just the specific connection that was passed to sqlite3_backup_init().
   6022 **
   6023 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
   6024 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
   6025 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
   6026 ** APIs are not strictly speaking threadsafe. If they are invoked at the
   6027 ** same time as another thread is invoking sqlite3_backup_step() it is
   6028 ** possible that they return invalid values.
   6029 */
   6030 SQLITE_API sqlite3_backup *sqlite3_backup_init(
   6031   sqlite3 *pDest,                        /* Destination database handle */
   6032   const char *zDestName,                 /* Destination database name */
   6033   sqlite3 *pSource,                      /* Source database handle */
   6034   const char *zSourceName                /* Source database name */
   6035 );
   6036 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
   6037 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
   6038 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
   6039 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
   6040 
   6041 /*
   6042 ** CAPI3REF: Unlock Notification
   6043 ** EXPERIMENTAL
   6044 **
   6045 ** ^When running in shared-cache mode, a database operation may fail with
   6046 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
   6047 ** individual tables within the shared-cache cannot be obtained. See
   6048 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
   6049 ** ^This API may be used to register a callback that SQLite will invoke
   6050 ** when the connection currently holding the required lock relinquishes it.
   6051 ** ^This API is only available if the library was compiled with the
   6052 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
   6053 **
   6054 ** See Also: [Using the SQLite Unlock Notification Feature].
   6055 **
   6056 ** ^Shared-cache locks are released when a database connection concludes
   6057 ** its current transaction, either by committing it or rolling it back.
   6058 **
   6059 ** ^When a connection (known as the blocked connection) fails to obtain a
   6060 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
   6061 ** identity of the database connection (the blocking connection) that
   6062 ** has locked the required resource is stored internally. ^After an
   6063 ** application receives an SQLITE_LOCKED error, it may call the
   6064 ** sqlite3_unlock_notify() method with the blocked connection handle as
   6065 ** the first argument to register for a callback that will be invoked
   6066 ** when the blocking connections current transaction is concluded. ^The
   6067 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
   6068 ** call that concludes the blocking connections transaction.
   6069 **
   6070 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
   6071 ** there is a chance that the blocking connection will have already
   6072 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
   6073 ** If this happens, then the specified callback is invoked immediately,
   6074 ** from within the call to sqlite3_unlock_notify().)^
   6075 **
   6076 ** ^If the blocked connection is attempting to obtain a write-lock on a
   6077 ** shared-cache table, and more than one other connection currently holds
   6078 ** a read-lock on the same table, then SQLite arbitrarily selects one of
   6079 ** the other connections to use as the blocking connection.
   6080 **
   6081 ** ^(There may be at most one unlock-notify callback registered by a
   6082 ** blocked connection. If sqlite3_unlock_notify() is called when the
   6083 ** blocked connection already has a registered unlock-notify callback,
   6084 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
   6085 ** called with a NULL pointer as its second argument, then any existing
   6086 ** unlock-notify callback is cancelled. ^The blocked connections
   6087 ** unlock-notify callback may also be canceled by closing the blocked
   6088 ** connection using [sqlite3_close()].
   6089 **
   6090 ** The unlock-notify callback is not reentrant. If an application invokes
   6091 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
   6092 ** crash or deadlock may be the result.
   6093 **
   6094 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
   6095 ** returns SQLITE_OK.
   6096 **
   6097 ** <b>Callback Invocation Details</b>
   6098 **
   6099 ** When an unlock-notify callback is registered, the application provides a
   6100 ** single void* pointer that is passed to the callback when it is invoked.
   6101 ** However, the signature of the callback function allows SQLite to pass
   6102 ** it an array of void* context pointers. The first argument passed to
   6103 ** an unlock-notify callback is a pointer to an array of void* pointers,
   6104 ** and the second is the number of entries in the array.
   6105 **
   6106 ** When a blocking connections transaction is concluded, there may be
   6107 ** more than one blocked connection that has registered for an unlock-notify
   6108 ** callback. ^If two or more such blocked connections have specified the
   6109 ** same callback function, then instead of invoking the callback function
   6110 ** multiple times, it is invoked once with the set of void* context pointers
   6111 ** specified by the blocked connections bundled together into an array.
   6112 ** This gives the application an opportunity to prioritize any actions
   6113 ** related to the set of unblocked database connections.
   6114 **
   6115 ** <b>Deadlock Detection</b>
   6116 **
   6117 ** Assuming that after registering for an unlock-notify callback a
   6118 ** database waits for the callback to be issued before taking any further
   6119 ** action (a reasonable assumption), then using this API may cause the
   6120 ** application to deadlock. For example, if connection X is waiting for
   6121 ** connection Y's transaction to be concluded, and similarly connection
   6122 ** Y is waiting on connection X's transaction, then neither connection
   6123 ** will proceed and the system may remain deadlocked indefinitely.
   6124 **
   6125 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
   6126 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
   6127 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
   6128 ** unlock-notify callback is registered. The system is said to be in
   6129 ** a deadlocked state if connection A has registered for an unlock-notify
   6130 ** callback on the conclusion of connection B's transaction, and connection
   6131 ** B has itself registered for an unlock-notify callback when connection
   6132 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
   6133 ** the system is also considered to be deadlocked if connection B has
   6134 ** registered for an unlock-notify callback on the conclusion of connection
   6135 ** C's transaction, where connection C is waiting on connection A. ^Any
   6136 ** number of levels of indirection are allowed.
   6137 **
   6138 ** <b>The "DROP TABLE" Exception</b>
   6139 **
   6140 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
   6141 ** always appropriate to call sqlite3_unlock_notify(). There is however,
   6142 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
   6143 ** SQLite checks if there are any currently executing SELECT statements
   6144 ** that belong to the same connection. If there are, SQLITE_LOCKED is
   6145 ** returned. In this case there is no "blocking connection", so invoking
   6146 ** sqlite3_unlock_notify() results in the unlock-notify callback being
   6147 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
   6148 ** or "DROP INDEX" query, an infinite loop might be the result.
   6149 **
   6150 ** One way around this problem is to check the extended error code returned
   6151 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
   6152 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
   6153 ** the special "DROP TABLE/INDEX" case, the extended error code is just
   6154 ** SQLITE_LOCKED.)^
   6155 */
   6156 SQLITE_API int sqlite3_unlock_notify(
   6157   sqlite3 *pBlocked,                          /* Waiting connection */
   6158   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
   6159   void *pNotifyArg                            /* Argument to pass to xNotify */
   6160 );
   6161 
   6162 
   6163 /*
   6164 ** CAPI3REF: String Comparison
   6165 ** EXPERIMENTAL
   6166 **
   6167 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
   6168 ** compare the contents of two buffers containing UTF-8 strings in a
   6169 ** case-indendent fashion, using the same definition of case independence
   6170 ** that SQLite uses internally when comparing identifiers.
   6171 */
   6172 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
   6173 
   6174 /*
   6175 ** CAPI3REF: Error Logging Interface
   6176 ** EXPERIMENTAL
   6177 **
   6178 ** ^The [sqlite3_log()] interface writes a message into the error log
   6179 ** established by the [SQLITE_CONFIG_ERRORLOG] option to [sqlite3_config()].
   6180 **
   6181 ** The sqlite3_log() interface is intended for use by extensions such as
   6182 ** virtual tables, collating functions, and SQL functions.  While there is
   6183 ** nothing to prevent an application from calling sqlite3_log(), doing so
   6184 ** is considered bad form.
   6185 **
   6186 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
   6187 ** will not use dynamically allocated memory.  The log message is stored in
   6188 ** a fixed-length buffer on the stack.  If the log message is longer than
   6189 ** a few hundred characters, it will be truncated to the length of the
   6190 ** buffer.
   6191 */
   6192 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
   6193 
   6194 /*
   6195 ** Undo the hack that converts floating point types to integer for
   6196 ** builds on processors without floating point support.
   6197 */
   6198 #ifdef SQLITE_OMIT_FLOATING_POINT
   6199 # undef double
   6200 #endif
   6201 
   6202 #if 0
   6203 }  /* End of the 'extern "C"' block */
   6204 #endif
   6205 #endif
   6206 
   6207 
   6208 /************** End of sqlite3.h *********************************************/
   6209 // Begin Android Add
   6210 #define SQLITE_BeginImmediate 0x00200000  /* Default BEGIN to IMMEDIATE */
   6211 #define fdatasync fsync
   6212 #undef __APPLE__
   6213 // End Android Add
   6214 /************** Continuing where we left off in sqliteInt.h ******************/
   6215 /************** Include hash.h in the middle of sqliteInt.h ******************/
   6216 /************** Begin file hash.h ********************************************/
   6217 /*
   6218 ** 2001 September 22
   6219 **
   6220 ** The author disclaims copyright to this source code.  In place of
   6221 ** a legal notice, here is a blessing:
   6222 **
   6223 **    May you do good and not evil.
   6224 **    May you find forgiveness for yourself and forgive others.
   6225 **    May you share freely, never taking more than you give.
   6226 **
   6227 *************************************************************************
   6228 ** This is the header file for the generic hash-table implemenation
   6229 ** used in SQLite.
   6230 */
   6231 #ifndef _SQLITE_HASH_H_
   6232 #define _SQLITE_HASH_H_
   6233 
   6234 /* Forward declarations of structures. */
   6235 typedef struct Hash Hash;
   6236 typedef struct HashElem HashElem;
   6237 
   6238 /* A complete hash table is an instance of the following structure.
   6239 ** The internals of this structure are intended to be opaque -- client
   6240 ** code should not attempt to access or modify the fields of this structure
   6241 ** directly.  Change this structure only by using the routines below.
   6242 ** However, some of the "procedures" and "functions" for modifying and
   6243 ** accessing this structure are really macros, so we can't really make
   6244 ** this structure opaque.
   6245 **
   6246 ** All elements of the hash table are on a single doubly-linked list.
   6247 ** Hash.first points to the head of this list.
   6248 **
   6249 ** There are Hash.htsize buckets.  Each bucket points to a spot in
   6250 ** the global doubly-linked list.  The contents of the bucket are the
   6251 ** element pointed to plus the next _ht.count-1 elements in the list.
   6252 **
   6253 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
   6254 ** by a linear search of the global list.  For small tables, the
   6255 ** Hash.ht table is never allocated because if there are few elements
   6256 ** in the table, it is faster to do a linear search than to manage
   6257 ** the hash table.
   6258 */
   6259 struct Hash {
   6260   unsigned int htsize;      /* Number of buckets in the hash table */
   6261   unsigned int count;       /* Number of entries in this table */
   6262   HashElem *first;          /* The first element of the array */
   6263   struct _ht {              /* the hash table */
   6264     int count;                 /* Number of entries with this hash */
   6265     HashElem *chain;           /* Pointer to first entry with this hash */
   6266   } *ht;
   6267 };
   6268 
   6269 /* Each element in the hash table is an instance of the following
   6270 ** structure.  All elements are stored on a single doubly-linked list.
   6271 **
   6272 ** Again, this structure is intended to be opaque, but it can't really
   6273 ** be opaque because it is used by macros.
   6274 */
   6275 struct HashElem {
   6276   HashElem *next, *prev;       /* Next and previous elements in the table */
   6277   void *data;                  /* Data associated with this element */
   6278   const char *pKey; int nKey;  /* Key associated with this element */
   6279 };
   6280 
   6281 /*
   6282 ** Access routines.  To delete, insert a NULL pointer.
   6283 */
   6284 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
   6285 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
   6286 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
   6287 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
   6288 
   6289 /*
   6290 ** Macros for looping over all elements of a hash table.  The idiom is
   6291 ** like this:
   6292 **
   6293 **   Hash h;
   6294 **   HashElem *p;
   6295 **   ...
   6296 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
   6297 **     SomeStructure *pData = sqliteHashData(p);
   6298 **     // do something with pData
   6299 **   }
   6300 */
   6301 #define sqliteHashFirst(H)  ((H)->first)
   6302 #define sqliteHashNext(E)   ((E)->next)
   6303 #define sqliteHashData(E)   ((E)->data)
   6304 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
   6305 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
   6306 
   6307 /*
   6308 ** Number of entries in a hash table
   6309 */
   6310 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
   6311 
   6312 #endif /* _SQLITE_HASH_H_ */
   6313 
   6314 /************** End of hash.h ************************************************/
   6315 /************** Continuing where we left off in sqliteInt.h ******************/
   6316 /************** Include parse.h in the middle of sqliteInt.h *****************/
   6317 /************** Begin file parse.h *******************************************/
   6318 #define TK_SEMI                            1
   6319 #define TK_EXPLAIN                         2
   6320 #define TK_QUERY                           3
   6321 #define TK_PLAN                            4
   6322 #define TK_BEGIN                           5
   6323 #define TK_TRANSACTION                     6
   6324 #define TK_DEFERRED                        7
   6325 #define TK_IMMEDIATE                       8
   6326 #define TK_EXCLUSIVE                       9
   6327 #define TK_COMMIT                         10
   6328 #define TK_END                            11
   6329 #define TK_ROLLBACK                       12
   6330 #define TK_SAVEPOINT                      13
   6331 #define TK_RELEASE                        14
   6332 #define TK_TO                             15
   6333 #define TK_TABLE                          16
   6334 #define TK_CREATE                         17
   6335 #define TK_IF                             18
   6336 #define TK_NOT                            19
   6337 #define TK_EXISTS                         20
   6338 #define TK_TEMP                           21
   6339 #define TK_LP                             22
   6340 #define TK_RP                             23
   6341 #define TK_AS                             24
   6342 #define TK_COMMA                          25
   6343 #define TK_ID                             26
   6344 #define TK_INDEXED                        27
   6345 #define TK_ABORT                          28
   6346 #define TK_ACTION                         29
   6347 #define TK_AFTER                          30
   6348 #define TK_ANALYZE                        31
   6349 #define TK_ASC                            32
   6350 #define TK_ATTACH                         33
   6351 #define TK_BEFORE                         34
   6352 #define TK_BY                             35
   6353 #define TK_CASCADE                        36
   6354 #define TK_CAST                           37
   6355 #define TK_COLUMNKW                       38
   6356 #define TK_CONFLICT                       39
   6357 #define TK_DATABASE                       40
   6358 #define TK_DESC                           41
   6359 #define TK_DETACH                         42
   6360 #define TK_EACH                           43
   6361 #define TK_FAIL                           44
   6362 #define TK_FOR                            45
   6363 #define TK_IGNORE                         46
   6364 #define TK_INITIALLY                      47
   6365 #define TK_INSTEAD                        48
   6366 #define TK_LIKE_KW                        49
   6367 #define TK_MATCH                          50
   6368 #define TK_NO                             51
   6369 #define TK_KEY                            52
   6370 #define TK_OF                             53
   6371 #define TK_OFFSET                         54
   6372 #define TK_PRAGMA                         55
   6373 #define TK_RAISE                          56
   6374 #define TK_REPLACE                        57
   6375 #define TK_RESTRICT                       58
   6376 #define TK_ROW                            59
   6377 #define TK_TRIGGER                        60
   6378 #define TK_VACUUM                         61
   6379 #define TK_VIEW                           62
   6380 #define TK_VIRTUAL                        63
   6381 #define TK_REINDEX                        64
   6382 #define TK_RENAME                         65
   6383 #define TK_CTIME_KW                       66
   6384 #define TK_ANY                            67
   6385 #define TK_OR                             68
   6386 #define TK_AND                            69
   6387 #define TK_IS                             70
   6388 #define TK_BETWEEN                        71
   6389 #define TK_IN                             72
   6390 #define TK_ISNULL                         73
   6391 #define TK_NOTNULL                        74
   6392 #define TK_NE                             75
   6393 #define TK_EQ                             76
   6394 #define TK_GT                             77
   6395 #define TK_LE                             78
   6396 #define TK_LT                             79
   6397 #define TK_GE                             80
   6398 #define TK_ESCAPE                         81
   6399 #define TK_BITAND                         82
   6400 #define TK_BITOR                          83
   6401 #define TK_LSHIFT                         84
   6402 #define TK_RSHIFT                         85
   6403 #define TK_PLUS                           86
   6404 #define TK_MINUS                          87
   6405 #define TK_STAR                           88
   6406 #define TK_SLASH                          89
   6407 #define TK_REM                            90
   6408 #define TK_CONCAT                         91
   6409 #define TK_COLLATE                        92
   6410 #define TK_BITNOT                         93
   6411 #define TK_STRING                         94
   6412 #define TK_JOIN_KW                        95
   6413 #define TK_CONSTRAINT                     96
   6414 #define TK_DEFAULT                        97
   6415 #define TK_NULL                           98
   6416 #define TK_PRIMARY                        99
   6417 #define TK_UNIQUE                         100
   6418 #define TK_CHECK                          101
   6419 #define TK_REFERENCES                     102
   6420 #define TK_AUTOINCR                       103
   6421 #define TK_ON                             104
   6422 #define TK_INSERT                         105
   6423 #define TK_DELETE                         106
   6424 #define TK_UPDATE                         107
   6425 #define TK_SET                            108
   6426 #define TK_DEFERRABLE                     109
   6427 #define TK_FOREIGN                        110
   6428 #define TK_DROP                           111
   6429 #define TK_UNION                          112
   6430 #define TK_ALL                            113
   6431 #define TK_EXCEPT                         114
   6432 #define TK_INTERSECT                      115
   6433 #define TK_SELECT                         116
   6434 #define TK_DISTINCT                       117
   6435 #define TK_DOT                            118
   6436 #define TK_FROM                           119
   6437 #define TK_JOIN                           120
   6438 #define TK_USING                          121
   6439 #define TK_ORDER                          122
   6440 #define TK_GROUP                          123
   6441 #define TK_HAVING                         124
   6442 #define TK_LIMIT                          125
   6443 #define TK_WHERE                          126
   6444 #define TK_INTO                           127
   6445 #define TK_VALUES                         128
   6446 #define TK_INTEGER                        129
   6447 #define TK_FLOAT                          130
   6448 #define TK_BLOB                           131
   6449 #define TK_REGISTER                       132
   6450 #define TK_VARIABLE                       133
   6451 #define TK_CASE                           134
   6452 #define TK_WHEN                           135
   6453 #define TK_THEN                           136
   6454 #define TK_ELSE                           137
   6455 #define TK_INDEX                          138
   6456 #define TK_ALTER                          139
   6457 #define TK_ADD                            140
   6458 #define TK_TO_TEXT                        141
   6459 #define TK_TO_BLOB                        142
   6460 #define TK_TO_NUMERIC                     143
   6461 #define TK_TO_INT                         144
   6462 #define TK_TO_REAL                        145
   6463 #define TK_ISNOT                          146
   6464 #define TK_END_OF_FILE                    147
   6465 #define TK_ILLEGAL                        148
   6466 #define TK_SPACE                          149
   6467 #define TK_UNCLOSED_STRING                150
   6468 #define TK_FUNCTION                       151
   6469 #define TK_COLUMN                         152
   6470 #define TK_AGG_FUNCTION                   153
   6471 #define TK_AGG_COLUMN                     154
   6472 #define TK_CONST_FUNC                     155
   6473 #define TK_UMINUS                         156
   6474 #define TK_UPLUS                          157
   6475 
   6476 /************** End of parse.h ***********************************************/
   6477 /************** Continuing where we left off in sqliteInt.h ******************/
   6478 #include <stdio.h>
   6479 #include <stdlib.h>
   6480 #include <string.h>
   6481 #include <assert.h>
   6482 #include <stddef.h>
   6483 
   6484 /*
   6485 ** If compiling for a processor that lacks floating point support,
   6486 ** substitute integer for floating-point
   6487 */
   6488 #ifdef SQLITE_OMIT_FLOATING_POINT
   6489 # define double sqlite_int64
   6490 # define LONGDOUBLE_TYPE sqlite_int64
   6491 # ifndef SQLITE_BIG_DBL
   6492 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
   6493 # endif
   6494 # define SQLITE_OMIT_DATETIME_FUNCS 1
   6495 # define SQLITE_OMIT_TRACE 1
   6496 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   6497 # undef SQLITE_HAVE_ISNAN
   6498 #endif
   6499 #ifndef SQLITE_BIG_DBL
   6500 # define SQLITE_BIG_DBL (1e99)
   6501 #endif
   6502 
   6503 /*
   6504 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
   6505 ** afterward. Having this macro allows us to cause the C compiler
   6506 ** to omit code used by TEMP tables without messy #ifndef statements.
   6507 */
   6508 #ifdef SQLITE_OMIT_TEMPDB
   6509 #define OMIT_TEMPDB 1
   6510 #else
   6511 #define OMIT_TEMPDB 0
   6512 #endif
   6513 
   6514 /*
   6515 ** If the following macro is set to 1, then NULL values are considered
   6516 ** distinct when determining whether or not two entries are the same
   6517 ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
   6518 ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
   6519 ** is the way things are suppose to work.
   6520 **
   6521 ** If the following macro is set to 0, the NULLs are indistinct for
   6522 ** a UNIQUE index.  In this mode, you can only have a single NULL entry
   6523 ** for a column declared UNIQUE.  This is the way Informix and SQL Server
   6524 ** work.
   6525 */
   6526 #define NULL_DISTINCT_FOR_UNIQUE 1
   6527 
   6528 /*
   6529 ** The "file format" number is an integer that is incremented whenever
   6530 ** the VDBE-level file format changes.  The following macros define the
   6531 ** the default file format for new databases and the maximum file format
   6532 ** that the library can read.
   6533 */
   6534 #define SQLITE_MAX_FILE_FORMAT 4
   6535 #ifndef SQLITE_DEFAULT_FILE_FORMAT
   6536 # define SQLITE_DEFAULT_FILE_FORMAT 1
   6537 #endif
   6538 
   6539 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
   6540 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
   6541 #endif
   6542 
   6543 /*
   6544 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
   6545 ** on the command-line
   6546 */
   6547 #ifndef SQLITE_TEMP_STORE
   6548 # define SQLITE_TEMP_STORE 1
   6549 #endif
   6550 
   6551 /*
   6552 ** GCC does not define the offsetof() macro so we'll have to do it
   6553 ** ourselves.
   6554 */
   6555 #ifndef offsetof
   6556 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
   6557 #endif
   6558 
   6559 /*
   6560 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
   6561 ** not, there are still machines out there that use EBCDIC.)
   6562 */
   6563 #if 'A' == '\301'
   6564 # define SQLITE_EBCDIC 1
   6565 #else
   6566 # define SQLITE_ASCII 1
   6567 #endif
   6568 
   6569 /*
   6570 ** Integers of known sizes.  These typedefs might change for architectures
   6571 ** where the sizes very.  Preprocessor macros are available so that the
   6572 ** types can be conveniently redefined at compile-type.  Like this:
   6573 **
   6574 **         cc '-DUINTPTR_TYPE=long long int' ...
   6575 */
   6576 #ifndef UINT32_TYPE
   6577 # ifdef HAVE_UINT32_T
   6578 #  define UINT32_TYPE uint32_t
   6579 # else
   6580 #  define UINT32_TYPE unsigned int
   6581 # endif
   6582 #endif
   6583 #ifndef UINT16_TYPE
   6584 # ifdef HAVE_UINT16_T
   6585 #  define UINT16_TYPE uint16_t
   6586 # else
   6587 #  define UINT16_TYPE unsigned short int
   6588 # endif
   6589 #endif
   6590 #ifndef INT16_TYPE
   6591 # ifdef HAVE_INT16_T
   6592 #  define INT16_TYPE int16_t
   6593 # else
   6594 #  define INT16_TYPE short int
   6595 # endif
   6596 #endif
   6597 #ifndef UINT8_TYPE
   6598 # ifdef HAVE_UINT8_T
   6599 #  define UINT8_TYPE uint8_t
   6600 # else
   6601 #  define UINT8_TYPE unsigned char
   6602 # endif
   6603 #endif
   6604 #ifndef INT8_TYPE
   6605 # ifdef HAVE_INT8_T
   6606 #  define INT8_TYPE int8_t
   6607 # else
   6608 #  define INT8_TYPE signed char
   6609 # endif
   6610 #endif
   6611 #ifndef LONGDOUBLE_TYPE
   6612 # define LONGDOUBLE_TYPE long double
   6613 #endif
   6614 typedef sqlite_int64 i64;          /* 8-byte signed integer */
   6615 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
   6616 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
   6617 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
   6618 typedef INT16_TYPE i16;            /* 2-byte signed integer */
   6619 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
   6620 typedef INT8_TYPE i8;              /* 1-byte signed integer */
   6621 
   6622 /*
   6623 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
   6624 ** that can be stored in a u32 without loss of data.  The value
   6625 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
   6626 ** have to specify the value in the less intuitive manner shown:
   6627 */
   6628 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
   6629 
   6630 /*
   6631 ** Macros to determine whether the machine is big or little endian,
   6632 ** evaluated at runtime.
   6633 */
   6634 #ifdef SQLITE_AMALGAMATION
   6635 SQLITE_PRIVATE const int sqlite3one = 1;
   6636 #else
   6637 SQLITE_PRIVATE const int sqlite3one;
   6638 #endif
   6639 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
   6640                              || defined(__x86_64) || defined(__x86_64__)
   6641 # define SQLITE_BIGENDIAN    0
   6642 # define SQLITE_LITTLEENDIAN 1
   6643 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
   6644 #else
   6645 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
   6646 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
   6647 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
   6648 #endif
   6649 
   6650 /*
   6651 ** Constants for the largest and smallest possible 64-bit signed integers.
   6652 ** These macros are designed to work correctly on both 32-bit and 64-bit
   6653 ** compilers.
   6654 */
   6655 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
   6656 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
   6657 
   6658 /*
   6659 ** Round up a number to the next larger multiple of 8.  This is used
   6660 ** to force 8-byte alignment on 64-bit architectures.
   6661 */
   6662 #define ROUND8(x)     (((x)+7)&~7)
   6663 
   6664 /*
   6665 ** Round down to the nearest multiple of 8
   6666 */
   6667 #define ROUNDDOWN8(x) ((x)&~7)
   6668 
   6669 /*
   6670 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
   6671 ** macro is used only within assert() to verify that the code gets
   6672 ** all alignment restrictions correct.
   6673 **
   6674 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
   6675 ** underlying malloc() implemention might return us 4-byte aligned
   6676 ** pointers.  In that case, only verify 4-byte alignment.
   6677 */
   6678 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
   6679 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
   6680 #else
   6681 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
   6682 #endif
   6683 
   6684 
   6685 /*
   6686 ** An instance of the following structure is used to store the busy-handler
   6687 ** callback for a given sqlite handle.
   6688 **
   6689 ** The sqlite.busyHandler member of the sqlite struct contains the busy
   6690 ** callback for the database handle. Each pager opened via the sqlite
   6691 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
   6692 ** callback is currently invoked only from within pager.c.
   6693 */
   6694 typedef struct BusyHandler BusyHandler;
   6695 struct BusyHandler {
   6696   int (*xFunc)(void *,int);  /* The busy callback */
   6697   void *pArg;                /* First arg to busy callback */
   6698   int nBusy;                 /* Incremented with each busy call */
   6699 };
   6700 
   6701 /*
   6702 ** Name of the master database table.  The master database table
   6703 ** is a special table that holds the names and attributes of all
   6704 ** user tables and indices.
   6705 */
   6706 #define MASTER_NAME       "sqlite_master"
   6707 #define TEMP_MASTER_NAME  "sqlite_temp_master"
   6708 
   6709 /*
   6710 ** The root-page of the master database table.
   6711 */
   6712 #define MASTER_ROOT       1
   6713 
   6714 /*
   6715 ** The name of the schema table.
   6716 */
   6717 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
   6718 
   6719 /*
   6720 ** A convenience macro that returns the number of elements in
   6721 ** an array.
   6722 */
   6723 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
   6724 
   6725 /*
   6726 ** The following value as a destructor means to use sqlite3DbFree().
   6727 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
   6728 */
   6729 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
   6730 
   6731 /*
   6732 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
   6733 ** not support Writable Static Data (WSD) such as global and static variables.
   6734 ** All variables must either be on the stack or dynamically allocated from
   6735 ** the heap.  When WSD is unsupported, the variable declarations scattered
   6736 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
   6737 ** macro is used for this purpose.  And instead of referencing the variable
   6738 ** directly, we use its constant as a key to lookup the run-time allocated
   6739 ** buffer that holds real variable.  The constant is also the initializer
   6740 ** for the run-time allocated buffer.
   6741 **
   6742 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
   6743 ** macros become no-ops and have zero performance impact.
   6744 */
   6745 #ifdef SQLITE_OMIT_WSD
   6746   #define SQLITE_WSD const
   6747   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
   6748   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
   6749 SQLITE_API   int sqlite3_wsd_init(int N, int J);
   6750 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
   6751 #else
   6752   #define SQLITE_WSD
   6753   #define GLOBAL(t,v) v
   6754   #define sqlite3GlobalConfig sqlite3Config
   6755 #endif
   6756 
   6757 /*
   6758 ** The following macros are used to suppress compiler warnings and to
   6759 ** make it clear to human readers when a function parameter is deliberately
   6760 ** left unused within the body of a function. This usually happens when
   6761 ** a function is called via a function pointer. For example the
   6762 ** implementation of an SQL aggregate step callback may not use the
   6763 ** parameter indicating the number of arguments passed to the aggregate,
   6764 ** if it knows that this is enforced elsewhere.
   6765 **
   6766 ** When a function parameter is not used at all within the body of a function,
   6767 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
   6768 ** However, these macros may also be used to suppress warnings related to
   6769 ** parameters that may or may not be used depending on compilation options.
   6770 ** For example those parameters only used in assert() statements. In these
   6771 ** cases the parameters are named as per the usual conventions.
   6772 */
   6773 #define UNUSED_PARAMETER(x) (void)(x)
   6774 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
   6775 
   6776 /*
   6777 ** Forward references to structures
   6778 */
   6779 typedef struct AggInfo AggInfo;
   6780 typedef struct AuthContext AuthContext;
   6781 typedef struct AutoincInfo AutoincInfo;
   6782 typedef struct Bitvec Bitvec;
   6783 typedef struct RowSet RowSet;
   6784 typedef struct CollSeq CollSeq;
   6785 typedef struct Column Column;
   6786 typedef struct Db Db;
   6787 typedef struct Schema Schema;
   6788 typedef struct Expr Expr;
   6789 typedef struct ExprList ExprList;
   6790 typedef struct ExprSpan ExprSpan;
   6791 typedef struct FKey FKey;
   6792 typedef struct FuncDef FuncDef;
   6793 typedef struct FuncDefHash FuncDefHash;
   6794 typedef struct IdList IdList;
   6795 typedef struct Index Index;
   6796 typedef struct IndexSample IndexSample;
   6797 typedef struct KeyClass KeyClass;
   6798 typedef struct KeyInfo KeyInfo;
   6799 typedef struct Lookaside Lookaside;
   6800 typedef struct LookasideSlot LookasideSlot;
   6801 typedef struct Module Module;
   6802 typedef struct NameContext NameContext;
   6803 typedef struct Parse Parse;
   6804 typedef struct Savepoint Savepoint;
   6805 typedef struct Select Select;
   6806 typedef struct SrcList SrcList;
   6807 typedef struct StrAccum StrAccum;
   6808 typedef struct Table Table;
   6809 typedef struct TableLock TableLock;
   6810 typedef struct Token Token;
   6811 typedef struct TriggerPrg TriggerPrg;
   6812 typedef struct TriggerStep TriggerStep;
   6813 typedef struct Trigger Trigger;
   6814 typedef struct UnpackedRecord UnpackedRecord;
   6815 typedef struct VTable VTable;
   6816 typedef struct Walker Walker;
   6817 typedef struct WherePlan WherePlan;
   6818 typedef struct WhereInfo WhereInfo;
   6819 typedef struct WhereLevel WhereLevel;
   6820 
   6821 /*
   6822 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
   6823 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
   6824 ** pointer types (i.e. FuncDef) defined above.
   6825 */
   6826 /************** Include btree.h in the middle of sqliteInt.h *****************/
   6827 /************** Begin file btree.h *******************************************/
   6828 /*
   6829 ** 2001 September 15
   6830 **
   6831 ** The author disclaims copyright to this source code.  In place of
   6832 ** a legal notice, here is a blessing:
   6833 **
   6834 **    May you do good and not evil.
   6835 **    May you find forgiveness for yourself and forgive others.
   6836 **    May you share freely, never taking more than you give.
   6837 **
   6838 *************************************************************************
   6839 ** This header file defines the interface that the sqlite B-Tree file
   6840 ** subsystem.  See comments in the source code for a detailed description
   6841 ** of what each interface routine does.
   6842 */
   6843 #ifndef _BTREE_H_
   6844 #define _BTREE_H_
   6845 
   6846 /* TODO: This definition is just included so other modules compile. It
   6847 ** needs to be revisited.
   6848 */
   6849 #define SQLITE_N_BTREE_META 10
   6850 
   6851 /*
   6852 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
   6853 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
   6854 */
   6855 #ifndef SQLITE_DEFAULT_AUTOVACUUM
   6856   #define SQLITE_DEFAULT_AUTOVACUUM 0
   6857 #endif
   6858 
   6859 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
   6860 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
   6861 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
   6862 
   6863 /*
   6864 ** Forward declarations of structure
   6865 */
   6866 typedef struct Btree Btree;
   6867 typedef struct BtCursor BtCursor;
   6868 typedef struct BtShared BtShared;
   6869 typedef struct BtreeMutexArray BtreeMutexArray;
   6870 
   6871 /*
   6872 ** This structure records all of the Btrees that need to hold
   6873 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
   6874 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
   6875 ** we can always lock and unlock them all quickly.
   6876 */
   6877 struct BtreeMutexArray {
   6878   int nMutex;
   6879   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
   6880 };
   6881 
   6882 
   6883 SQLITE_PRIVATE int sqlite3BtreeOpen(
   6884   const char *zFilename,   /* Name of database file to open */
   6885   sqlite3 *db,             /* Associated database connection */
   6886   Btree **ppBtree,         /* Return open Btree* here */
   6887   int flags,               /* Flags */
   6888   int vfsFlags             /* Flags passed through to VFS open */
   6889 );
   6890 
   6891 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
   6892 ** following values.
   6893 **
   6894 ** NOTE:  These values must match the corresponding PAGER_ values in
   6895 ** pager.h.
   6896 */
   6897 #define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
   6898 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
   6899 #define BTREE_MEMORY        4  /* In-memory DB.  No argument */
   6900 #define BTREE_READONLY      8  /* Open the database in read-only mode */
   6901 #define BTREE_READWRITE    16  /* Open for both reading and writing */
   6902 #define BTREE_CREATE       32  /* Create the database if it does not exist */
   6903 
   6904 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
   6905 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
   6906 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
   6907 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
   6908 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
   6909 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
   6910 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
   6911 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
   6912 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
   6913 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
   6914 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
   6915 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
   6916 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
   6917 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
   6918 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
   6919 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
   6920 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
   6921 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
   6922 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
   6923 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
   6924 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
   6925 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
   6926 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
   6927 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
   6928 
   6929 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
   6930 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
   6931 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
   6932 
   6933 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
   6934 
   6935 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
   6936 ** of the following flags:
   6937 */
   6938 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
   6939 #define BTREE_ZERODATA   2    /* Table has keys only - no data */
   6940 #define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
   6941 
   6942 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
   6943 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
   6944 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
   6945 
   6946 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
   6947 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
   6948 
   6949 /*
   6950 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
   6951 ** should be one of the following values. The integer values are assigned
   6952 ** to constants so that the offset of the corresponding field in an
   6953 ** SQLite database header may be found using the following formula:
   6954 **
   6955 **   offset = 36 + (idx * 4)
   6956 **
   6957 ** For example, the free-page-count field is located at byte offset 36 of
   6958 ** the database file header. The incr-vacuum-flag field is located at
   6959 ** byte offset 64 (== 36+4*7).
   6960 */
   6961 #define BTREE_FREE_PAGE_COUNT     0
   6962 #define BTREE_SCHEMA_VERSION      1
   6963 #define BTREE_FILE_FORMAT         2
   6964 #define BTREE_DEFAULT_CACHE_SIZE  3
   6965 #define BTREE_LARGEST_ROOT_PAGE   4
   6966 #define BTREE_TEXT_ENCODING       5
   6967 #define BTREE_USER_VERSION        6
   6968 #define BTREE_INCR_VACUUM         7
   6969 
   6970 SQLITE_PRIVATE int sqlite3BtreeCursor(
   6971   Btree*,                              /* BTree containing table to open */
   6972   int iTable,                          /* Index of root page */
   6973   int wrFlag,                          /* 1 for writing.  0 for read-only */
   6974   struct KeyInfo*,                     /* First argument to compare function */
   6975   BtCursor *pCursor                    /* Space to write cursor structure */
   6976 );
   6977 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
   6978 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
   6979 
   6980 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
   6981 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
   6982   BtCursor*,
   6983   UnpackedRecord *pUnKey,
   6984   i64 intKey,
   6985   int bias,
   6986   int *pRes
   6987 );
   6988 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
   6989 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
   6990 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
   6991                                   const void *pData, int nData,
   6992                                   int nZero, int bias, int seekResult);
   6993 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
   6994 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
   6995 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
   6996 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
   6997 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
   6998 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
   6999 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
   7000 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
   7001 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
   7002 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
   7003 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
   7004 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
   7005 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
   7006 
   7007 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
   7008 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
   7009 
   7010 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
   7011 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
   7012 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
   7013 
   7014 #ifndef NDEBUG
   7015 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
   7016 #endif
   7017 
   7018 #ifndef SQLITE_OMIT_BTREECOUNT
   7019 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
   7020 #endif
   7021 
   7022 #ifdef SQLITE_TEST
   7023 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
   7024 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
   7025 #endif
   7026 
   7027 /*
   7028 ** If we are not using shared cache, then there is no need to
   7029 ** use mutexes to access the BtShared structures.  So make the
   7030 ** Enter and Leave procedures no-ops.
   7031 */
   7032 #ifndef SQLITE_OMIT_SHARED_CACHE
   7033 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
   7034 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
   7035 #else
   7036 # define sqlite3BtreeEnter(X)
   7037 # define sqlite3BtreeEnterAll(X)
   7038 #endif
   7039 
   7040 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
   7041 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
   7042 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
   7043 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
   7044 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
   7045 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
   7046 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
   7047 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
   7048 #ifndef NDEBUG
   7049   /* These routines are used inside assert() statements only. */
   7050 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
   7051 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
   7052 #endif
   7053 #else
   7054 
   7055 # define sqlite3BtreeLeave(X)
   7056 # define sqlite3BtreeEnterCursor(X)
   7057 # define sqlite3BtreeLeaveCursor(X)
   7058 # define sqlite3BtreeLeaveAll(X)
   7059 # define sqlite3BtreeMutexArrayEnter(X)
   7060 # define sqlite3BtreeMutexArrayLeave(X)
   7061 # define sqlite3BtreeMutexArrayInsert(X,Y)
   7062 
   7063 # define sqlite3BtreeHoldsMutex(X) 1
   7064 # define sqlite3BtreeHoldsAllMutexes(X) 1
   7065 #endif
   7066 
   7067 
   7068 #endif /* _BTREE_H_ */
   7069 
   7070 /************** End of btree.h ***********************************************/
   7071 /************** Continuing where we left off in sqliteInt.h ******************/
   7072 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
   7073 /************** Begin file vdbe.h ********************************************/
   7074 /*
   7075 ** 2001 September 15
   7076 **
   7077 ** The author disclaims copyright to this source code.  In place of
   7078 ** a legal notice, here is a blessing:
   7079 **
   7080 **    May you do good and not evil.
   7081 **    May you find forgiveness for yourself and forgive others.
   7082 **    May you share freely, never taking more than you give.
   7083 **
   7084 *************************************************************************
   7085 ** Header file for the Virtual DataBase Engine (VDBE)
   7086 **
   7087 ** This header defines the interface to the virtual database engine
   7088 ** or VDBE.  The VDBE implements an abstract machine that runs a
   7089 ** simple program to access and modify the underlying database.
   7090 */
   7091 #ifndef _SQLITE_VDBE_H_
   7092 #define _SQLITE_VDBE_H_
   7093 
   7094 /*
   7095 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
   7096 ** in the source file sqliteVdbe.c are allowed to see the insides
   7097 ** of this structure.
   7098 */
   7099 typedef struct Vdbe Vdbe;
   7100 
   7101 /*
   7102 ** The names of the following types declared in vdbeInt.h are required
   7103 ** for the VdbeOp definition.
   7104 */
   7105 typedef struct VdbeFunc VdbeFunc;
   7106 typedef struct Mem Mem;
   7107 typedef struct SubProgram SubProgram;
   7108 
   7109 /*
   7110 ** A single instruction of the virtual machine has an opcode
   7111 ** and as many as three operands.  The instruction is recorded
   7112 ** as an instance of the following structure:
   7113 */
   7114 struct VdbeOp {
   7115   u8 opcode;          /* What operation to perform */
   7116   signed char p4type; /* One of the P4_xxx constants for p4 */
   7117   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
   7118   u8 p5;              /* Fifth parameter is an unsigned character */
   7119   int p1;             /* First operand */
   7120   int p2;             /* Second parameter (often the jump destination) */
   7121   int p3;             /* The third parameter */
   7122   union {             /* fourth parameter */
   7123     int i;                 /* Integer value if p4type==P4_INT32 */
   7124     void *p;               /* Generic pointer */
   7125     char *z;               /* Pointer to data for string (char array) types */
   7126     i64 *pI64;             /* Used when p4type is P4_INT64 */
   7127     double *pReal;         /* Used when p4type is P4_REAL */
   7128     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
   7129     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
   7130     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
   7131     Mem *pMem;             /* Used when p4type is P4_MEM */
   7132     VTable *pVtab;         /* Used when p4type is P4_VTAB */
   7133     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
   7134     int *ai;               /* Used when p4type is P4_INTARRAY */
   7135     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
   7136   } p4;
   7137 #ifdef SQLITE_DEBUG
   7138   char *zComment;          /* Comment to improve readability */
   7139 #endif
   7140 #ifdef VDBE_PROFILE
   7141   int cnt;                 /* Number of times this instruction was executed */
   7142   u64 cycles;              /* Total time spent executing this instruction */
   7143 #endif
   7144 };
   7145 typedef struct VdbeOp VdbeOp;
   7146 
   7147 
   7148 /*
   7149 ** A sub-routine used to implement a trigger program.
   7150 */
   7151 struct SubProgram {
   7152   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
   7153   int nOp;                      /* Elements in aOp[] */
   7154   int nMem;                     /* Number of memory cells required */
   7155   int nCsr;                     /* Number of cursors required */
   7156   int nRef;                     /* Number of pointers to this structure */
   7157   void *token;                  /* id that may be used to recursive triggers */
   7158 };
   7159 
   7160 /*
   7161 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
   7162 ** it takes up less space.
   7163 */
   7164 struct VdbeOpList {
   7165   u8 opcode;          /* What operation to perform */
   7166   signed char p1;     /* First operand */
   7167   signed char p2;     /* Second parameter (often the jump destination) */
   7168   signed char p3;     /* Third parameter */
   7169 };
   7170 typedef struct VdbeOpList VdbeOpList;
   7171 
   7172 /*
   7173 ** Allowed values of VdbeOp.p4type
   7174 */
   7175 #define P4_NOTUSED    0   /* The P4 parameter is not used */
   7176 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
   7177 #define P4_STATIC   (-2)  /* Pointer to a static string */
   7178 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
   7179 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
   7180 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
   7181 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
   7182 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
   7183 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
   7184 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
   7185 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
   7186 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
   7187 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
   7188 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
   7189 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
   7190 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
   7191 
   7192 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
   7193 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
   7194 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
   7195 ** gets freed when the Vdbe is finalized so it still should be obtained
   7196 ** from a single sqliteMalloc().  But no copy is made and the calling
   7197 ** function should *not* try to free the KeyInfo.
   7198 */
   7199 #define P4_KEYINFO_HANDOFF (-16)
   7200 #define P4_KEYINFO_STATIC  (-17)
   7201 
   7202 /*
   7203 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
   7204 ** number of columns of data returned by the statement.
   7205 */
   7206 #define COLNAME_NAME     0
   7207 #define COLNAME_DECLTYPE 1
   7208 #define COLNAME_DATABASE 2
   7209 #define COLNAME_TABLE    3
   7210 #define COLNAME_COLUMN   4
   7211 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   7212 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
   7213 #else
   7214 # ifdef SQLITE_OMIT_DECLTYPE
   7215 #   define COLNAME_N      1      /* Store only the name */
   7216 # else
   7217 #   define COLNAME_N      2      /* Store the name and decltype */
   7218 # endif
   7219 #endif
   7220 
   7221 /*
   7222 ** The following macro converts a relative address in the p2 field
   7223 ** of a VdbeOp structure into a negative number so that
   7224 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
   7225 ** the macro again restores the address.
   7226 */
   7227 #define ADDR(X)  (-1-(X))
   7228 
   7229 /*
   7230 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
   7231 ** header file that defines a number for each opcode used by the VDBE.
   7232 */
   7233 /************** Include opcodes.h in the middle of vdbe.h ********************/
   7234 /************** Begin file opcodes.h *****************************************/
   7235 /* Automatically generated.  Do not edit */
   7236 /* See the mkopcodeh.awk script for details */
   7237 #define OP_Goto                                 1
   7238 #define OP_Gosub                                2
   7239 #define OP_Return                               3
   7240 #define OP_Yield                                4
   7241 #define OP_HaltIfNull                           5
   7242 #define OP_Halt                                 6
   7243 #define OP_Integer                              7
   7244 #define OP_Int64                                8
   7245 #define OP_Real                               130   /* same as TK_FLOAT    */
   7246 #define OP_String8                             94   /* same as TK_STRING   */
   7247 #define OP_String                               9
   7248 #define OP_Null                                10
   7249 #define OP_Blob                                11
   7250 #define OP_Variable                            12
   7251 #define OP_Move                                13
   7252 #define OP_Copy                                14
   7253 #define OP_SCopy                               15
   7254 #define OP_ResultRow                           16
   7255 #define OP_Concat                              91   /* same as TK_CONCAT   */
   7256 #define OP_Add                                 86   /* same as TK_PLUS     */
   7257 #define OP_Subtract                            87   /* same as TK_MINUS    */
   7258 #define OP_Multiply                            88   /* same as TK_STAR     */
   7259 #define OP_Divide                              89   /* same as TK_SLASH    */
   7260 #define OP_Remainder                           90   /* same as TK_REM      */
   7261 #define OP_CollSeq                             17
   7262 #define OP_Function                            18
   7263 #define OP_BitAnd                              82   /* same as TK_BITAND   */
   7264 #define OP_BitOr                               83   /* same as TK_BITOR    */
   7265 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
   7266 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
   7267 #define OP_AddImm                              20
   7268 #define OP_MustBeInt                           21
   7269 #define OP_RealAffinity                        22
   7270 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
   7271 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
   7272 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
   7273 #define OP_ToInt                              144   /* same as TK_TO_INT   */
   7274 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
   7275 #define OP_Eq                                  76   /* same as TK_EQ       */
   7276 #define OP_Ne                                  75   /* same as TK_NE       */
   7277 #define OP_Lt                                  79   /* same as TK_LT       */
   7278 #define OP_Le                                  78   /* same as TK_LE       */
   7279 #define OP_Gt                                  77   /* same as TK_GT       */
   7280 #define OP_Ge                                  80   /* same as TK_GE       */
   7281 #define OP_Permutation                         23
   7282 #define OP_Compare                             24
   7283 #define OP_Jump                                25
   7284 #define OP_And                                 69   /* same as TK_AND      */
   7285 #define OP_Or                                  68   /* same as TK_OR       */
   7286 #define OP_Not                                 19   /* same as TK_NOT      */
   7287 #define OP_BitNot                              93   /* same as TK_BITNOT   */
   7288 #define OP_If                                  26
   7289 #define OP_IfNot                               27
   7290 #define OP_IsNull                              73   /* same as TK_ISNULL   */
   7291 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
   7292 #define OP_Column                              28
   7293 #define OP_Affinity                            29
   7294 #define OP_MakeRecord                          30
   7295 #define OP_Count                               31
   7296 #define OP_Savepoint                           32
   7297 #define OP_AutoCommit                          33
   7298 #define OP_Transaction                         34
   7299 #define OP_ReadCookie                          35
   7300 #define OP_SetCookie                           36
   7301 #define OP_VerifyCookie                        37
   7302 #define OP_OpenRead                            38
   7303 #define OP_OpenWrite                           39
   7304 #define OP_OpenEphemeral                       40
   7305 #define OP_OpenPseudo                          41
   7306 #define OP_Close                               42
   7307 #define OP_SeekLt                              43
   7308 #define OP_SeekLe                              44
   7309 #define OP_SeekGe                              45
   7310 #define OP_SeekGt                              46
   7311 #define OP_Seek                                47
   7312 #define OP_NotFound                            48
   7313 #define OP_Found                               49
   7314 #define OP_IsUnique                            50
   7315 #define OP_NotExists                           51
   7316 #define OP_Sequence                            52
   7317 #define OP_NewRowid                            53
   7318 #define OP_Insert                              54
   7319 #define OP_InsertInt                           55
   7320 #define OP_Delete                              56
   7321 #define OP_ResetCount                          57
   7322 #define OP_RowKey                              58
   7323 #define OP_RowData                             59
   7324 #define OP_Rowid                               60
   7325 #define OP_NullRow                             61
   7326 #define OP_Last                                62
   7327 #define OP_Sort                                63
   7328 #define OP_Rewind                              64
   7329 #define OP_Prev                                65
   7330 #define OP_Next                                66
   7331 #define OP_IdxInsert                           67
   7332 #define OP_IdxDelete                           70
   7333 #define OP_IdxRowid                            71
   7334 #define OP_IdxLT                               72
   7335 #define OP_IdxGE                               81
   7336 #define OP_Destroy                             92
   7337 #define OP_Clear                               95
   7338 #define OP_CreateIndex                         96
   7339 #define OP_CreateTable                         97
   7340 #define OP_ParseSchema                         98
   7341 #define OP_LoadAnalysis                        99
   7342 #define OP_DropTable                          100
   7343 #define OP_DropIndex                          101
   7344 #define OP_DropTrigger                        102
   7345 #define OP_IntegrityCk                        103
   7346 #define OP_RowSetAdd                          104
   7347 #define OP_RowSetRead                         105
   7348 #define OP_RowSetTest                         106
   7349 #define OP_Program                            107
   7350 #define OP_Param                              108
   7351 #define OP_FkCounter                          109
   7352 #define OP_FkIfZero                           110
   7353 #define OP_MemMax                             111
   7354 #define OP_IfPos                              112
   7355 #define OP_IfNeg                              113
   7356 #define OP_IfZero                             114
   7357 #define OP_AggStep                            115
   7358 #define OP_AggFinal                           116
   7359 #define OP_Vacuum                             117
   7360 #define OP_IncrVacuum                         118
   7361 #define OP_Expire                             119
   7362 #define OP_TableLock                          120
   7363 #define OP_VBegin                             121
   7364 #define OP_VCreate                            122
   7365 #define OP_VDestroy                           123
   7366 #define OP_VOpen                              124
   7367 #define OP_VFilter                            125
   7368 #define OP_VColumn                            126
   7369 #define OP_VNext                              127
   7370 #define OP_VRename                            128
   7371 #define OP_VUpdate                            129
   7372 #define OP_Pagecount                          131
   7373 #define OP_Trace                              132
   7374 #define OP_Noop                               133
   7375 #define OP_Explain                            134
   7376 
   7377 /* The following opcode values are never used */
   7378 #define OP_NotUsed_135                        135
   7379 #define OP_NotUsed_136                        136
   7380 #define OP_NotUsed_137                        137
   7381 #define OP_NotUsed_138                        138
   7382 #define OP_NotUsed_139                        139
   7383 #define OP_NotUsed_140                        140
   7384 
   7385 
   7386 /* Properties such as "out2" or "jump" that are specified in
   7387 ** comments following the "case" for each opcode in the vdbe.c
   7388 ** are encoded into bitvectors as follows:
   7389 */
   7390 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
   7391 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
   7392 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
   7393 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
   7394 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
   7395 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
   7396 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
   7397 #define OPFLG_INITIALIZER {\
   7398 /*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
   7399 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x24,\
   7400 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
   7401 /*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
   7402 /*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
   7403 /*  40 */ 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x08,\
   7404 /*  48 */ 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00, 0x00,\
   7405 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x01,\
   7406 /*  64 */ 0x01, 0x01, 0x01, 0x08, 0x4c, 0x4c, 0x00, 0x02,\
   7407 /*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
   7408 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
   7409 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x02, 0x24, 0x02, 0x00,\
   7410 /*  96 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
   7411 /* 104 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
   7412 /* 112 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00,\
   7413 /* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01,\
   7414 /* 128 */ 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00,\
   7415 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
   7416 /* 144 */ 0x04, 0x04,}
   7417 
   7418 /************** End of opcodes.h *********************************************/
   7419 /************** Continuing where we left off in vdbe.h ***********************/
   7420 
   7421 /*
   7422 ** Prototypes for the VDBE interface.  See comments on the implementation
   7423 ** for a description of what each of these routines does.
   7424 */
   7425 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
   7426 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
   7427 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
   7428 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
   7429 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
   7430 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
   7431 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
   7432 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
   7433 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
   7434 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
   7435 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
   7436 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
   7437 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
   7438 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
   7439 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
   7440 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
   7441 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
   7442 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
   7443 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
   7444 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
   7445 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
   7446 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
   7447 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
   7448 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
   7449 #ifdef SQLITE_DEBUG
   7450 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
   7451 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
   7452 #endif
   7453 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
   7454 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
   7455 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
   7456 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
   7457 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
   7458 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
   7459 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
   7460 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
   7461 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
   7462 SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *, SubProgram *, int);
   7463 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
   7464 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
   7465 #ifndef SQLITE_OMIT_TRACE
   7466 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
   7467 #endif
   7468 
   7469 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
   7470 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
   7471 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
   7472 
   7473 
   7474 #ifndef NDEBUG
   7475 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
   7476 # define VdbeComment(X)  sqlite3VdbeComment X
   7477 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
   7478 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
   7479 #else
   7480 # define VdbeComment(X)
   7481 # define VdbeNoopComment(X)
   7482 #endif
   7483 
   7484 #endif
   7485 
   7486 /************** End of vdbe.h ************************************************/
   7487 /************** Continuing where we left off in sqliteInt.h ******************/
   7488 /************** Include pager.h in the middle of sqliteInt.h *****************/
   7489 /************** Begin file pager.h *******************************************/
   7490 /*
   7491 ** 2001 September 15
   7492 **
   7493 ** The author disclaims copyright to this source code.  In place of
   7494 ** a legal notice, here is a blessing:
   7495 **
   7496 **    May you do good and not evil.
   7497 **    May you find forgiveness for yourself and forgive others.
   7498 **    May you share freely, never taking more than you give.
   7499 **
   7500 *************************************************************************
   7501 ** This header file defines the interface that the sqlite page cache
   7502 ** subsystem.  The page cache subsystem reads and writes a file a page
   7503 ** at a time and provides a journal for rollback.
   7504 */
   7505 
   7506 #ifndef _PAGER_H_
   7507 #define _PAGER_H_
   7508 
   7509 /*
   7510 ** Default maximum size for persistent journal files. A negative
   7511 ** value means no limit. This value may be overridden using the
   7512 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
   7513 */
   7514 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
   7515   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
   7516 #endif
   7517 
   7518 /*
   7519 ** The type used to represent a page number.  The first page in a file
   7520 ** is called page 1.  0 is used to represent "not a page".
   7521 */
   7522 typedef u32 Pgno;
   7523 
   7524 /*
   7525 ** Each open file is managed by a separate instance of the "Pager" structure.
   7526 */
   7527 typedef struct Pager Pager;
   7528 
   7529 /*
   7530 ** Handle type for pages.
   7531 */
   7532 typedef struct PgHdr DbPage;
   7533 
   7534 /*
   7535 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
   7536 ** reserved for working around a windows/posix incompatibility). It is
   7537 ** used in the journal to signify that the remainder of the journal file
   7538 ** is devoted to storing a master journal name - there are no more pages to
   7539 ** roll back. See comments for function writeMasterJournal() in pager.c
   7540 ** for details.
   7541 */
   7542 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
   7543 
   7544 /*
   7545 ** Allowed values for the flags parameter to sqlite3PagerOpen().
   7546 **
   7547 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
   7548 */
   7549 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
   7550 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
   7551 
   7552 /*
   7553 ** Valid values for the second argument to sqlite3PagerLockingMode().
   7554 */
   7555 #define PAGER_LOCKINGMODE_QUERY      -1
   7556 #define PAGER_LOCKINGMODE_NORMAL      0
   7557 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
   7558 
   7559 /*
   7560 ** Valid values for the second argument to sqlite3PagerJournalMode().
   7561 */
   7562 #define PAGER_JOURNALMODE_QUERY      -1
   7563 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
   7564 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
   7565 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
   7566 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
   7567 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
   7568 
   7569 /*
   7570 ** The remainder of this file contains the declarations of the functions
   7571 ** that make up the Pager sub-system API. See source code comments for
   7572 ** a detailed description of each routine.
   7573 */
   7574 
   7575 /* Open and close a Pager connection. */
   7576 SQLITE_PRIVATE int sqlite3PagerOpen(
   7577   sqlite3_vfs*,
   7578   Pager **ppPager,
   7579   const char*,
   7580   int,
   7581   int,
   7582   int,
   7583   void(*)(DbPage*)
   7584 );
   7585 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
   7586 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
   7587 
   7588 /* Functions used to configure a Pager object. */
   7589 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
   7590 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*, int);
   7591 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
   7592 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
   7593 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
   7594 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
   7595 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
   7596 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
   7597 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
   7598 
   7599 /* Functions used to obtain and release page references. */
   7600 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
   7601 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
   7602 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
   7603 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
   7604 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
   7605 
   7606 /* Operations on page references. */
   7607 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
   7608 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
   7609 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
   7610 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
   7611 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
   7612 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
   7613 
   7614 /* Functions used to manage pager transactions and savepoints. */
   7615 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
   7616 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
   7617 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
   7618 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
   7619 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
   7620 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
   7621 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
   7622 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
   7623 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
   7624 
   7625 /* Functions used to query pager state and configuration. */
   7626 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
   7627 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
   7628 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
   7629 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
   7630 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
   7631 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
   7632 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
   7633 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
   7634 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
   7635 
   7636 /* Functions used to truncate the database file. */
   7637 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
   7638 
   7639 /* Functions to support testing and debugging. */
   7640 #if !defined(NDEBUG) || defined(SQLITE_TEST)
   7641 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
   7642 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
   7643 #endif
   7644 #ifdef SQLITE_TEST
   7645 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
   7646 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
   7647   void disable_simulated_io_errors(void);
   7648   void enable_simulated_io_errors(void);
   7649 #else
   7650 # define disable_simulated_io_errors()
   7651 # define enable_simulated_io_errors()
   7652 #endif
   7653 
   7654 #endif /* _PAGER_H_ */
   7655 
   7656 /************** End of pager.h ***********************************************/
   7657 /************** Continuing where we left off in sqliteInt.h ******************/
   7658 /************** Include pcache.h in the middle of sqliteInt.h ****************/
   7659 /************** Begin file pcache.h ******************************************/
   7660 /*
   7661 ** 2008 August 05
   7662 **
   7663 ** The author disclaims copyright to this source code.  In place of
   7664 ** a legal notice, here is a blessing:
   7665 **
   7666 **    May you do good and not evil.
   7667 **    May you find forgiveness for yourself and forgive others.
   7668 **    May you share freely, never taking more than you give.
   7669 **
   7670 *************************************************************************
   7671 ** This header file defines the interface that the sqlite page cache
   7672 ** subsystem.
   7673 */
   7674 
   7675 #ifndef _PCACHE_H_
   7676 
   7677 typedef struct PgHdr PgHdr;
   7678 typedef struct PCache PCache;
   7679 
   7680 /*
   7681 ** Every page in the cache is controlled by an instance of the following
   7682 ** structure.
   7683 */
   7684 struct PgHdr {
   7685   void *pData;                   /* Content of this page */
   7686   void *pExtra;                  /* Extra content */
   7687   PgHdr *pDirty;                 /* Transient list of dirty pages */
   7688   Pgno pgno;                     /* Page number for this page */
   7689   Pager *pPager;                 /* The pager this page is part of */
   7690 #ifdef SQLITE_CHECK_PAGES
   7691   u32 pageHash;                  /* Hash of page content */
   7692 #endif
   7693   u16 flags;                     /* PGHDR flags defined below */
   7694 
   7695   /**********************************************************************
   7696   ** Elements above are public.  All that follows is private to pcache.c
   7697   ** and should not be accessed by other modules.
   7698   */
   7699   i16 nRef;                      /* Number of users of this page */
   7700   PCache *pCache;                /* Cache that owns this page */
   7701 
   7702   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
   7703   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
   7704 };
   7705 
   7706 /* Bit values for PgHdr.flags */
   7707 #define PGHDR_DIRTY             0x002  /* Page has changed */
   7708 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
   7709                                        ** writing this page to the database */
   7710 #define PGHDR_NEED_READ         0x008  /* Content is unread */
   7711 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
   7712 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
   7713 
   7714 /* Initialize and shutdown the page cache subsystem */
   7715 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
   7716 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
   7717 
   7718 /* Page cache buffer management:
   7719 ** These routines implement SQLITE_CONFIG_PAGECACHE.
   7720 */
   7721 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
   7722 
   7723 /* Create a new pager cache.
   7724 ** Under memory stress, invoke xStress to try to make pages clean.
   7725 ** Only clean and unpinned pages can be reclaimed.
   7726 */
   7727 SQLITE_PRIVATE void sqlite3PcacheOpen(
   7728   int szPage,                    /* Size of every page */
   7729   int szExtra,                   /* Extra space associated with each page */
   7730   int bPurgeable,                /* True if pages are on backing store */
   7731   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
   7732   void *pStress,                 /* Argument to xStress */
   7733   PCache *pToInit                /* Preallocated space for the PCache */
   7734 );
   7735 
   7736 /* Modify the page-size after the cache has been created. */
   7737 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
   7738 
   7739 /* Return the size in bytes of a PCache object.  Used to preallocate
   7740 ** storage space.
   7741 */
   7742 SQLITE_PRIVATE int sqlite3PcacheSize(void);
   7743 
   7744 /* One release per successful fetch.  Page is pinned until released.
   7745 ** Reference counted.
   7746 */
   7747 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
   7748 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
   7749 
   7750 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
   7751 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
   7752 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
   7753 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
   7754 
   7755 /* Change a page number.  Used by incr-vacuum. */
   7756 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
   7757 
   7758 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
   7759 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
   7760 
   7761 /* Get a list of all dirty pages in the cache, sorted by page number */
   7762 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
   7763 
   7764 /* Reset and close the cache object */
   7765 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
   7766 
   7767 /* Clear flags from pages of the page cache */
   7768 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
   7769 
   7770 /* Discard the contents of the cache */
   7771 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
   7772 
   7773 /* Return the total number of outstanding page references */
   7774 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
   7775 
   7776 /* Increment the reference count of an existing page */
   7777 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
   7778 
   7779 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
   7780 
   7781 /* Return the total number of pages stored in the cache */
   7782 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
   7783 
   7784 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
   7785 /* Iterate through all dirty pages currently stored in the cache. This
   7786 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
   7787 ** library is built.
   7788 */
   7789 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
   7790 #endif
   7791 
   7792 /* Set and get the suggested cache-size for the specified pager-cache.
   7793 **
   7794 ** If no global maximum is configured, then the system attempts to limit
   7795 ** the total number of pages cached by purgeable pager-caches to the sum
   7796 ** of the suggested cache-sizes.
   7797 */
   7798 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
   7799 #ifdef SQLITE_TEST
   7800 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
   7801 #endif
   7802 
   7803 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   7804 /* Try to return memory used by the pcache module to the main memory heap */
   7805 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
   7806 #endif
   7807 
   7808 #ifdef SQLITE_TEST
   7809 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
   7810 #endif
   7811 
   7812 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
   7813 
   7814 #endif /* _PCACHE_H_ */
   7815 
   7816 /************** End of pcache.h **********************************************/
   7817 /************** Continuing where we left off in sqliteInt.h ******************/
   7818 
   7819 /************** Include os.h in the middle of sqliteInt.h ********************/
   7820 /************** Begin file os.h **********************************************/
   7821 /*
   7822 ** 2001 September 16
   7823 **
   7824 ** The author disclaims copyright to this source code.  In place of
   7825 ** a legal notice, here is a blessing:
   7826 **
   7827 **    May you do good and not evil.
   7828 **    May you find forgiveness for yourself and forgive others.
   7829 **    May you share freely, never taking more than you give.
   7830 **
   7831 ******************************************************************************
   7832 **
   7833 ** This header file (together with is companion C source-code file
   7834 ** "os.c") attempt to abstract the underlying operating system so that
   7835 ** the SQLite library will work on both POSIX and windows systems.
   7836 **
   7837 ** This header file is #include-ed by sqliteInt.h and thus ends up
   7838 ** being included by every source file.
   7839 */
   7840 #ifndef _SQLITE_OS_H_
   7841 #define _SQLITE_OS_H_
   7842 
   7843 /*
   7844 ** Figure out if we are dealing with Unix, Windows, or some other
   7845 ** operating system.  After the following block of preprocess macros,
   7846 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
   7847 ** will defined to either 1 or 0.  One of the four will be 1.  The other
   7848 ** three will be 0.
   7849 */
   7850 #if defined(SQLITE_OS_OTHER)
   7851 # if SQLITE_OS_OTHER==1
   7852 #   undef SQLITE_OS_UNIX
   7853 #   define SQLITE_OS_UNIX 0
   7854 #   undef SQLITE_OS_WIN
   7855 #   define SQLITE_OS_WIN 0
   7856 #   undef SQLITE_OS_OS2
   7857 #   define SQLITE_OS_OS2 0
   7858 # else
   7859 #   undef SQLITE_OS_OTHER
   7860 # endif
   7861 #endif
   7862 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
   7863 # define SQLITE_OS_OTHER 0
   7864 # ifndef SQLITE_OS_WIN
   7865 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
   7866 #     define SQLITE_OS_WIN 1
   7867 #     define SQLITE_OS_UNIX 0
   7868 #     define SQLITE_OS_OS2 0
   7869 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
   7870 #     define SQLITE_OS_WIN 0
   7871 #     define SQLITE_OS_UNIX 0
   7872 #     define SQLITE_OS_OS2 1
   7873 #   else
   7874 #     define SQLITE_OS_WIN 0
   7875 #     define SQLITE_OS_UNIX 1
   7876 #     define SQLITE_OS_OS2 0
   7877 #  endif
   7878 # else
   7879 #  define SQLITE_OS_UNIX 0
   7880 #  define SQLITE_OS_OS2 0
   7881 # endif
   7882 #else
   7883 # ifndef SQLITE_OS_WIN
   7884 #  define SQLITE_OS_WIN 0
   7885 # endif
   7886 #endif
   7887 
   7888 /*
   7889 ** Determine if we are dealing with WindowsCE - which has a much
   7890 ** reduced API.
   7891 */
   7892 #if defined(_WIN32_WCE)
   7893 # define SQLITE_OS_WINCE 1
   7894 #else
   7895 # define SQLITE_OS_WINCE 0
   7896 #endif
   7897 
   7898 
   7899 /*
   7900 ** Define the maximum size of a temporary filename
   7901 */
   7902 #if SQLITE_OS_WIN
   7903 # include <windows.h>
   7904 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
   7905 #elif SQLITE_OS_OS2
   7906 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
   7907 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
   7908 # endif
   7909 # define INCL_DOSDATETIME
   7910 # define INCL_DOSFILEMGR
   7911 # define INCL_DOSERRORS
   7912 # define INCL_DOSMISC
   7913 # define INCL_DOSPROCESS
   7914 # define INCL_DOSMODULEMGR
   7915 # define INCL_DOSSEMAPHORES
   7916 # include <os2.h>
   7917 # include <uconv.h>
   7918 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
   7919 #else
   7920 # define SQLITE_TEMPNAME_SIZE 200
   7921 #endif
   7922 
   7923 /* If the SET_FULLSYNC macro is not defined above, then make it
   7924 ** a no-op
   7925 */
   7926 #ifndef SET_FULLSYNC
   7927 # define SET_FULLSYNC(x,y)
   7928 #endif
   7929 
   7930 /*
   7931 ** The default size of a disk sector
   7932 */
   7933 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
   7934 # define SQLITE_DEFAULT_SECTOR_SIZE 512
   7935 #endif
   7936 
   7937 /*
   7938 ** Temporary files are named starting with this prefix followed by 16 random
   7939 ** alphanumeric characters, and no file extension. They are stored in the
   7940 ** OS's standard temporary file directory, and are deleted prior to exit.
   7941 ** If sqlite is being embedded in another program, you may wish to change the
   7942 ** prefix to reflect your program's name, so that if your program exits
   7943 ** prematurely, old temporary files can be easily identified. This can be done
   7944 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
   7945 **
   7946 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
   7947 ** Mcafee started using SQLite in their anti-virus product and it
   7948 ** started putting files with the "sqlite" name in the c:/temp folder.
   7949 ** This annoyed many windows users.  Those users would then do a
   7950 ** Google search for "sqlite", find the telephone numbers of the
   7951 ** developers and call to wake them up at night and complain.
   7952 ** For this reason, the default name prefix is changed to be "sqlite"
   7953 ** spelled backwards.  So the temp files are still identified, but
   7954 ** anybody smart enough to figure out the code is also likely smart
   7955 ** enough to know that calling the developer will not help get rid
   7956 ** of the file.
   7957 */
   7958 #ifndef SQLITE_TEMP_FILE_PREFIX
   7959 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
   7960 #endif
   7961 
   7962 /*
   7963 ** The following values may be passed as the second argument to
   7964 ** sqlite3OsLock(). The various locks exhibit the following semantics:
   7965 **
   7966 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
   7967 ** RESERVED:  A single process may hold a RESERVED lock on a file at
   7968 **            any time. Other processes may hold and obtain new SHARED locks.
   7969 ** PENDING:   A single process may hold a PENDING lock on a file at
   7970 **            any one time. Existing SHARED locks may persist, but no new
   7971 **            SHARED locks may be obtained by other processes.
   7972 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
   7973 **
   7974 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
   7975 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
   7976 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
   7977 ** sqlite3OsLock().
   7978 */
   7979 #define NO_LOCK         0
   7980 #define SHARED_LOCK     1
   7981 #define RESERVED_LOCK   2
   7982 #define PENDING_LOCK    3
   7983 #define EXCLUSIVE_LOCK  4
   7984 
   7985 /*
   7986 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
   7987 **
   7988 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
   7989 ** those functions are not available.  So we use only LockFile() and
   7990 ** UnlockFile().
   7991 **
   7992 ** LockFile() prevents not just writing but also reading by other processes.
   7993 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
   7994 ** byte out of a specific range of bytes. The lock byte is obtained at
   7995 ** random so two separate readers can probably access the file at the
   7996 ** same time, unless they are unlucky and choose the same lock byte.
   7997 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
   7998 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
   7999 ** a single byte of the file that is designated as the reserved lock byte.
   8000 ** A PENDING_LOCK is obtained by locking a designated byte different from
   8001 ** the RESERVED_LOCK byte.
   8002 **
   8003 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
   8004 ** which means we can use reader/writer locks.  When reader/writer locks
   8005 ** are used, the lock is placed on the same range of bytes that is used
   8006 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
   8007 ** will support two or more Win95 readers or two or more WinNT readers.
   8008 ** But a single Win95 reader will lock out all WinNT readers and a single
   8009 ** WinNT reader will lock out all other Win95 readers.
   8010 **
   8011 ** The following #defines specify the range of bytes used for locking.
   8012 ** SHARED_SIZE is the number of bytes available in the pool from which
   8013 ** a random byte is selected for a shared lock.  The pool of bytes for
   8014 ** shared locks begins at SHARED_FIRST.
   8015 **
   8016 ** The same locking strategy and
   8017 ** byte ranges are used for Unix.  This leaves open the possiblity of having
   8018 ** clients on win95, winNT, and unix all talking to the same shared file
   8019 ** and all locking correctly.  To do so would require that samba (or whatever
   8020 ** tool is being used for file sharing) implements locks correctly between
   8021 ** windows and unix.  I'm guessing that isn't likely to happen, but by
   8022 ** using the same locking range we are at least open to the possibility.
   8023 **
   8024 ** Locking in windows is manditory.  For this reason, we cannot store
   8025 ** actual data in the bytes used for locking.  The pager never allocates
   8026 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
   8027 ** that all locks will fit on a single page even at the minimum page size.
   8028 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
   8029 ** is set high so that we don't have to allocate an unused page except
   8030 ** for very large databases.  But one should test the page skipping logic
   8031 ** by setting PENDING_BYTE low and running the entire regression suite.
   8032 **
   8033 ** Changing the value of PENDING_BYTE results in a subtly incompatible
   8034 ** file format.  Depending on how it is changed, you might not notice
   8035 ** the incompatibility right away, even running a full regression test.
   8036 ** The default location of PENDING_BYTE is the first byte past the
   8037 ** 1GB boundary.
   8038 **
   8039 */
   8040 #define PENDING_BYTE      sqlite3PendingByte
   8041 #define RESERVED_BYTE     (PENDING_BYTE+1)
   8042 #define SHARED_FIRST      (PENDING_BYTE+2)
   8043 #define SHARED_SIZE       510
   8044 
   8045 /*
   8046 ** Wrapper around OS specific sqlite3_os_init() function.
   8047 */
   8048 SQLITE_PRIVATE int sqlite3OsInit(void);
   8049 
   8050 /*
   8051 ** Functions for accessing sqlite3_file methods
   8052 */
   8053 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
   8054 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
   8055 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
   8056 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
   8057 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
   8058 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
   8059 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
   8060 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
   8061 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
   8062 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
   8063 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
   8064 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
   8065 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
   8066 
   8067 /*
   8068 ** Functions for accessing sqlite3_vfs methods
   8069 */
   8070 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
   8071 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
   8072 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
   8073 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
   8074 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   8075 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
   8076 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
   8077 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
   8078 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
   8079 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   8080 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
   8081 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
   8082 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
   8083 
   8084 /*
   8085 ** Convenience functions for opening and closing files using
   8086 ** sqlite3_malloc() to obtain space for the file-handle structure.
   8087 */
   8088 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
   8089 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
   8090 
   8091 #endif /* _SQLITE_OS_H_ */
   8092 
   8093 /************** End of os.h **************************************************/
   8094 /************** Continuing where we left off in sqliteInt.h ******************/
   8095 /************** Include mutex.h in the middle of sqliteInt.h *****************/
   8096 /************** Begin file mutex.h *******************************************/
   8097 /*
   8098 ** 2007 August 28
   8099 **
   8100 ** The author disclaims copyright to this source code.  In place of
   8101 ** a legal notice, here is a blessing:
   8102 **
   8103 **    May you do good and not evil.
   8104 **    May you find forgiveness for yourself and forgive others.
   8105 **    May you share freely, never taking more than you give.
   8106 **
   8107 *************************************************************************
   8108 **
   8109 ** This file contains the common header for all mutex implementations.
   8110 ** The sqliteInt.h header #includes this file so that it is available
   8111 ** to all source files.  We break it out in an effort to keep the code
   8112 ** better organized.
   8113 **
   8114 ** NOTE:  source files should *not* #include this header file directly.
   8115 ** Source files should #include the sqliteInt.h file and let that file
   8116 ** include this one indirectly.
   8117 */
   8118 
   8119 
   8120 /*
   8121 ** Figure out what version of the code to use.  The choices are
   8122 **
   8123 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
   8124 **                             mutexes implemention cannot be overridden
   8125 **                             at start-time.
   8126 **
   8127 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
   8128 **                             mutual exclusion is provided.  But this
   8129 **                             implementation can be overridden at
   8130 **                             start-time.
   8131 **
   8132 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
   8133 **
   8134 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
   8135 **
   8136 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
   8137 */
   8138 #if !SQLITE_THREADSAFE
   8139 # define SQLITE_MUTEX_OMIT
   8140 #endif
   8141 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
   8142 #  if SQLITE_OS_UNIX
   8143 #    define SQLITE_MUTEX_PTHREADS
   8144 #  elif SQLITE_OS_WIN
   8145 #    define SQLITE_MUTEX_W32
   8146 #  elif SQLITE_OS_OS2
   8147 #    define SQLITE_MUTEX_OS2
   8148 #  else
   8149 #    define SQLITE_MUTEX_NOOP
   8150 #  endif
   8151 #endif
   8152 
   8153 #ifdef SQLITE_MUTEX_OMIT
   8154 /*
   8155 ** If this is a no-op implementation, implement everything as macros.
   8156 */
   8157 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
   8158 #define sqlite3_mutex_free(X)
   8159 #define sqlite3_mutex_enter(X)
   8160 #define sqlite3_mutex_try(X)      SQLITE_OK
   8161 #define sqlite3_mutex_leave(X)
   8162 #define sqlite3_mutex_held(X)     1
   8163 #define sqlite3_mutex_notheld(X)  1
   8164 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
   8165 #define sqlite3MutexInit()        SQLITE_OK
   8166 #define sqlite3MutexEnd()
   8167 #endif /* defined(SQLITE_MUTEX_OMIT) */
   8168 
   8169 /************** End of mutex.h ***********************************************/
   8170 /************** Continuing where we left off in sqliteInt.h ******************/
   8171 
   8172 
   8173 /*
   8174 ** Each database file to be accessed by the system is an instance
   8175 ** of the following structure.  There are normally two of these structures
   8176 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
   8177 ** aDb[1] is the database file used to hold temporary tables.  Additional
   8178 ** databases may be attached.
   8179 */
   8180 struct Db {
   8181   char *zName;         /* Name of this database */
   8182   Btree *pBt;          /* The B*Tree structure for this database file */
   8183   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
   8184   u8 safety_level;     /* How aggressive at syncing data to disk */
   8185   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
   8186 };
   8187 
   8188 /*
   8189 ** An instance of the following structure stores a database schema.
   8190 **
   8191 ** If there are no virtual tables configured in this schema, the
   8192 ** Schema.db variable is set to NULL. After the first virtual table
   8193 ** has been added, it is set to point to the database connection
   8194 ** used to create the connection. Once a virtual table has been
   8195 ** added to the Schema structure and the Schema.db variable populated,
   8196 ** only that database connection may use the Schema to prepare
   8197 ** statements.
   8198 */
   8199 struct Schema {
   8200   int schema_cookie;   /* Database schema version number for this file */
   8201   Hash tblHash;        /* All tables indexed by name */
   8202   Hash idxHash;        /* All (named) indices indexed by name */
   8203   Hash trigHash;       /* All triggers indexed by name */
   8204   Hash fkeyHash;       /* All foreign keys by referenced table name */
   8205   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
   8206   u8 file_format;      /* Schema format version for this file */
   8207   u8 enc;              /* Text encoding used by this database */
   8208   u16 flags;           /* Flags associated with this schema */
   8209   int cache_size;      /* Number of pages to use in the cache */
   8210 #ifndef SQLITE_OMIT_VIRTUALTABLE
   8211   sqlite3 *db;         /* "Owner" connection. See comment above */
   8212 #endif
   8213 };
   8214 
   8215 /*
   8216 ** These macros can be used to test, set, or clear bits in the
   8217 ** Db.flags field.
   8218 */
   8219 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
   8220 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
   8221 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
   8222 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
   8223 
   8224 /*
   8225 ** Allowed values for the DB.flags field.
   8226 **
   8227 ** The DB_SchemaLoaded flag is set after the database schema has been
   8228 ** read into internal hash tables.
   8229 **
   8230 ** DB_UnresetViews means that one or more views have column names that
   8231 ** have been filled out.  If the schema changes, these column names might
   8232 ** changes and so the view will need to be reset.
   8233 */
   8234 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
   8235 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
   8236 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
   8237 
   8238 /*
   8239 ** The number of different kinds of things that can be limited
   8240 ** using the sqlite3_limit() interface.
   8241 */
   8242 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
   8243 
   8244 /*
   8245 ** Lookaside malloc is a set of fixed-size buffers that can be used
   8246 ** to satisfy small transient memory allocation requests for objects
   8247 ** associated with a particular database connection.  The use of
   8248 ** lookaside malloc provides a significant performance enhancement
   8249 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
   8250 ** SQL statements.
   8251 **
   8252 ** The Lookaside structure holds configuration information about the
   8253 ** lookaside malloc subsystem.  Each available memory allocation in
   8254 ** the lookaside subsystem is stored on a linked list of LookasideSlot
   8255 ** objects.
   8256 **
   8257 ** Lookaside allocations are only allowed for objects that are associated
   8258 ** with a particular database connection.  Hence, schema information cannot
   8259 ** be stored in lookaside because in shared cache mode the schema information
   8260 ** is shared by multiple database connections.  Therefore, while parsing
   8261 ** schema information, the Lookaside.bEnabled flag is cleared so that
   8262 ** lookaside allocations are not used to construct the schema objects.
   8263 */
   8264 struct Lookaside {
   8265   u16 sz;                 /* Size of each buffer in bytes */
   8266   u8 bEnabled;            /* False to disable new lookaside allocations */
   8267   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
   8268   int nOut;               /* Number of buffers currently checked out */
   8269   int mxOut;              /* Highwater mark for nOut */
   8270   LookasideSlot *pFree;   /* List of available buffers */
   8271   void *pStart;           /* First byte of available memory space */
   8272   void *pEnd;             /* First byte past end of available space */
   8273 };
   8274 struct LookasideSlot {
   8275   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
   8276 };
   8277 
   8278 /*
   8279 ** A hash table for function definitions.
   8280 **
   8281 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
   8282 ** Collisions are on the FuncDef.pHash chain.
   8283 */
   8284 struct FuncDefHash {
   8285   FuncDef *a[23];       /* Hash table for functions */
   8286 };
   8287 
   8288 /*
   8289 ** Each database is an instance of the following structure.
   8290 **
   8291 ** The sqlite.lastRowid records the last insert rowid generated by an
   8292 ** insert statement.  Inserts on views do not affect its value.  Each
   8293 ** trigger has its own context, so that lastRowid can be updated inside
   8294 ** triggers as usual.  The previous value will be restored once the trigger
   8295 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
   8296 ** longer (since after version 2.8.12) reset to -1.
   8297 **
   8298 ** The sqlite.nChange does not count changes within triggers and keeps no
   8299 ** context.  It is reset at start of sqlite3_exec.
   8300 ** The sqlite.lsChange represents the number of changes made by the last
   8301 ** insert, update, or delete statement.  It remains constant throughout the
   8302 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
   8303 ** context stack just like lastRowid so that the count of changes
   8304 ** within a trigger is not seen outside the trigger.  Changes to views do not
   8305 ** affect the value of lsChange.
   8306 ** The sqlite.csChange keeps track of the number of current changes (since
   8307 ** the last statement) and is used to update sqlite_lsChange.
   8308 **
   8309 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
   8310 ** store the most recent error code and, if applicable, string. The
   8311 ** internal function sqlite3Error() is used to set these variables
   8312 ** consistently.
   8313 */
   8314 struct sqlite3 {
   8315   sqlite3_vfs *pVfs;            /* OS Interface */
   8316   int nDb;                      /* Number of backends currently in use */
   8317   Db *aDb;                      /* All backends */
   8318   int flags;                    /* Miscellaneous flags. See below */
   8319   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
   8320   int errCode;                  /* Most recent error code (SQLITE_*) */
   8321   int errMask;                  /* & result codes with this before returning */
   8322   u8 autoCommit;                /* The auto-commit flag. */
   8323   u8 temp_store;                /* 1: file 2: memory 0: default */
   8324   u8 mallocFailed;              /* True if we have seen a malloc failure */
   8325   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
   8326   u8 dfltJournalMode;           /* Default journal mode for attached dbs */
   8327   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
   8328   u8 suppressErr;               /* Do not issue error messages if true */
   8329   int nextPagesize;             /* Pagesize after VACUUM if >0 */
   8330   int nTable;                   /* Number of tables in the database */
   8331   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
   8332   i64 lastRowid;                /* ROWID of most recent insert (see above) */
   8333   u32 magic;                    /* Magic number for detect library misuse */
   8334   int nChange;                  /* Value returned by sqlite3_changes() */
   8335   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
   8336   sqlite3_mutex *mutex;         /* Connection mutex */
   8337   int aLimit[SQLITE_N_LIMIT];   /* Limits */
   8338   struct sqlite3InitInfo {      /* Information used during initialization */
   8339     int iDb;                    /* When back is being initialized */
   8340     int newTnum;                /* Rootpage of table being initialized */
   8341     u8 busy;                    /* TRUE if currently initializing */
   8342     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
   8343   } init;
   8344   int nExtension;               /* Number of loaded extensions */
   8345   void **aExtension;            /* Array of shared library handles */
   8346   struct Vdbe *pVdbe;           /* List of active virtual machines */
   8347   int activeVdbeCnt;            /* Number of VDBEs currently executing */
   8348   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
   8349   void (*xTrace)(void*,const char*);        /* Trace function */
   8350   void *pTraceArg;                          /* Argument to the trace function */
   8351   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
   8352   void *pProfileArg;                        /* Argument to profile function */
   8353   void *pCommitArg;                 /* Argument to xCommitCallback() */
   8354   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
   8355   void *pRollbackArg;               /* Argument to xRollbackCallback() */
   8356   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
   8357   void *pUpdateArg;
   8358   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
   8359   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
   8360   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
   8361   void *pCollNeededArg;
   8362   sqlite3_value *pErr;          /* Most recent error message */
   8363   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
   8364   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
   8365   union {
   8366     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
   8367     double notUsed1;            /* Spacer */
   8368   } u1;
   8369   Lookaside lookaside;          /* Lookaside malloc configuration */
   8370 #ifndef SQLITE_OMIT_AUTHORIZATION
   8371   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   8372                                 /* Access authorization function */
   8373   void *pAuthArg;               /* 1st argument to the access auth function */
   8374 #endif
   8375 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   8376   int (*xProgress)(void *);     /* The progress callback */
   8377   void *pProgressArg;           /* Argument to the progress callback */
   8378   int nProgressOps;             /* Number of opcodes for progress callback */
   8379 #endif
   8380 #ifndef SQLITE_OMIT_VIRTUALTABLE
   8381   Hash aModule;                 /* populated by sqlite3_create_module() */
   8382   Table *pVTab;                 /* vtab with active Connect/Create method */
   8383   VTable **aVTrans;             /* Virtual tables with open transactions */
   8384   int nVTrans;                  /* Allocated size of aVTrans */
   8385   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
   8386 #endif
   8387   FuncDefHash aFunc;            /* Hash table of connection functions */
   8388   Hash aCollSeq;                /* All collating sequences */
   8389   BusyHandler busyHandler;      /* Busy callback */
   8390   int busyTimeout;              /* Busy handler timeout, in msec */
   8391   Db aDbStatic[2];              /* Static space for the 2 default backends */
   8392   Savepoint *pSavepoint;        /* List of active savepoints */
   8393   int nSavepoint;               /* Number of non-transaction savepoints */
   8394   int nStatement;               /* Number of nested statement-transactions  */
   8395   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
   8396   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
   8397 
   8398 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   8399   /* The following variables are all protected by the STATIC_MASTER
   8400   ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
   8401   **
   8402   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
   8403   ** unlock so that it can proceed.
   8404   **
   8405   ** When X.pBlockingConnection==Y, that means that something that X tried
   8406   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
   8407   ** held by Y.
   8408   */
   8409   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
   8410   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
   8411   void *pUnlockArg;                     /* Argument to xUnlockNotify */
   8412   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
   8413   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
   8414 #endif
   8415 };
   8416 
   8417 /*
   8418 ** A macro to discover the encoding of a database.
   8419 */
   8420 #define ENC(db) ((db)->aDb[0].pSchema->enc)
   8421 
   8422 /*
   8423 ** Possible values for the sqlite3.flags.
   8424 */
   8425 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
   8426 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
   8427 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
   8428 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
   8429 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
   8430                                           /*   DELETE, or UPDATE and return */
   8431                                           /*   the count using a callback. */
   8432 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
   8433                                           /*   result set is empty */
   8434 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
   8435 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
   8436 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
   8437 #define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when
   8438                                           ** accessing read-only databases */
   8439 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
   8440 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
   8441 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
   8442 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
   8443 #define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
   8444 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
   8445 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
   8446 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
   8447 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
   8448 
   8449 /*
   8450 ** Bits of the sqlite3.flags field that are used by the
   8451 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
   8452 ** These must be the low-order bits of the flags field.
   8453 */
   8454 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
   8455 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
   8456 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
   8457 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
   8458 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
   8459 #define SQLITE_OptMask        0x1f        /* Mask of all disablable opts */
   8460 
   8461 /*
   8462 ** Possible values for the sqlite.magic field.
   8463 ** The numbers are obtained at random and have no special meaning, other
   8464 ** than being distinct from one another.
   8465 */
   8466 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
   8467 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
   8468 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
   8469 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
   8470 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
   8471 
   8472 /*
   8473 ** Each SQL function is defined by an instance of the following
   8474 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
   8475 ** hash table.  When multiple functions have the same name, the hash table
   8476 ** points to a linked list of these structures.
   8477 */
   8478 struct FuncDef {
   8479   i16 nArg;            /* Number of arguments.  -1 means unlimited */
   8480   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
   8481   u8 flags;            /* Some combination of SQLITE_FUNC_* */
   8482   void *pUserData;     /* User data parameter */
   8483   FuncDef *pNext;      /* Next function with same name */
   8484   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
   8485   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
   8486   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
   8487   char *zName;         /* SQL name of the function. */
   8488   FuncDef *pHash;      /* Next with a different name but the same hash */
   8489 };
   8490 
   8491 /*
   8492 ** Possible values for FuncDef.flags
   8493 */
   8494 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
   8495 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
   8496 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
   8497 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
   8498 #define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
   8499 #define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
   8500 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
   8501 
   8502 /*
   8503 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
   8504 ** used to create the initializers for the FuncDef structures.
   8505 **
   8506 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
   8507 **     Used to create a scalar function definition of a function zName
   8508 **     implemented by C function xFunc that accepts nArg arguments. The
   8509 **     value passed as iArg is cast to a (void*) and made available
   8510 **     as the user-data (sqlite3_user_data()) for the function. If
   8511 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
   8512 **
   8513 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
   8514 **     Used to create an aggregate function definition implemented by
   8515 **     the C functions xStep and xFinal. The first four parameters
   8516 **     are interpreted in the same way as the first 4 parameters to
   8517 **     FUNCTION().
   8518 **
   8519 **   LIKEFUNC(zName, nArg, pArg, flags)
   8520 **     Used to create a scalar function definition of a function zName
   8521 **     that accepts nArg arguments and is implemented by a call to C
   8522 **     function likeFunc. Argument pArg is cast to a (void *) and made
   8523 **     available as the function user-data (sqlite3_user_data()). The
   8524 **     FuncDef.flags variable is set to the value passed as the flags
   8525 **     parameter.
   8526 */
   8527 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
   8528   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
   8529    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
   8530 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
   8531   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
   8532    pArg, 0, xFunc, 0, 0, #zName, 0}
   8533 #define LIKEFUNC(zName, nArg, arg, flags) \
   8534   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
   8535 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
   8536   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
   8537    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
   8538 
   8539 /*
   8540 ** All current savepoints are stored in a linked list starting at
   8541 ** sqlite3.pSavepoint. The first element in the list is the most recently
   8542 ** opened savepoint. Savepoints are added to the list by the vdbe
   8543 ** OP_Savepoint instruction.
   8544 */
   8545 struct Savepoint {
   8546   char *zName;                        /* Savepoint name (nul-terminated) */
   8547   i64 nDeferredCons;                  /* Number of deferred fk violations */
   8548   Savepoint *pNext;                   /* Parent savepoint (if any) */
   8549 };
   8550 
   8551 /*
   8552 ** The following are used as the second parameter to sqlite3Savepoint(),
   8553 ** and as the P1 argument to the OP_Savepoint instruction.
   8554 */
   8555 #define SAVEPOINT_BEGIN      0
   8556 #define SAVEPOINT_RELEASE    1
   8557 #define SAVEPOINT_ROLLBACK   2
   8558 
   8559 
   8560 /*
   8561 ** Each SQLite module (virtual table definition) is defined by an
   8562 ** instance of the following structure, stored in the sqlite3.aModule
   8563 ** hash table.
   8564 */
   8565 struct Module {
   8566   const sqlite3_module *pModule;       /* Callback pointers */
   8567   const char *zName;                   /* Name passed to create_module() */
   8568   void *pAux;                          /* pAux passed to create_module() */
   8569   void (*xDestroy)(void *);            /* Module destructor function */
   8570 };
   8571 
   8572 /*
   8573 ** information about each column of an SQL table is held in an instance
   8574 ** of this structure.
   8575 */
   8576 struct Column {
   8577   char *zName;     /* Name of this column */
   8578   Expr *pDflt;     /* Default value of this column */
   8579   char *zDflt;     /* Original text of the default value */
   8580   char *zType;     /* Data type for this column */
   8581   char *zColl;     /* Collating sequence.  If NULL, use the default */
   8582   u8 notNull;      /* True if there is a NOT NULL constraint */
   8583   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
   8584   char affinity;   /* One of the SQLITE_AFF_... values */
   8585 #ifndef SQLITE_OMIT_VIRTUALTABLE
   8586   u8 isHidden;     /* True if this column is 'hidden' */
   8587 #endif
   8588 };
   8589 
   8590 /*
   8591 ** A "Collating Sequence" is defined by an instance of the following
   8592 ** structure. Conceptually, a collating sequence consists of a name and
   8593 ** a comparison routine that defines the order of that sequence.
   8594 **
   8595 ** There may two separate implementations of the collation function, one
   8596 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
   8597 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
   8598 ** native byte order. When a collation sequence is invoked, SQLite selects
   8599 ** the version that will require the least expensive encoding
   8600 ** translations, if any.
   8601 **
   8602 ** The CollSeq.pUser member variable is an extra parameter that passed in
   8603 ** as the first argument to the UTF-8 comparison function, xCmp.
   8604 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
   8605 ** xCmp16.
   8606 **
   8607 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
   8608 ** collating sequence is undefined.  Indices built on an undefined
   8609 ** collating sequence may not be read or written.
   8610 */
   8611 struct CollSeq {
   8612   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
   8613   u8 enc;               /* Text encoding handled by xCmp() */
   8614   u8 type;              /* One of the SQLITE_COLL_... values below */
   8615   void *pUser;          /* First argument to xCmp() */
   8616   int (*xCmp)(void*,int, const void*, int, const void*);
   8617   void (*xDel)(void*);  /* Destructor for pUser */
   8618 };
   8619 
   8620 /*
   8621 ** Allowed values of CollSeq.type:
   8622 */
   8623 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
   8624 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
   8625 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
   8626 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
   8627 
   8628 /*
   8629 ** A sort order can be either ASC or DESC.
   8630 */
   8631 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
   8632 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
   8633 
   8634 /*
   8635 ** Column affinity types.
   8636 **
   8637 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
   8638 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
   8639 ** the speed a little by numbering the values consecutively.
   8640 **
   8641 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
   8642 ** when multiple affinity types are concatenated into a string and
   8643 ** used as the P4 operand, they will be more readable.
   8644 **
   8645 ** Note also that the numeric types are grouped together so that testing
   8646 ** for a numeric type is a single comparison.
   8647 */
   8648 #define SQLITE_AFF_TEXT     'a'
   8649 #define SQLITE_AFF_NONE     'b'
   8650 #define SQLITE_AFF_NUMERIC  'c'
   8651 #define SQLITE_AFF_INTEGER  'd'
   8652 #define SQLITE_AFF_REAL     'e'
   8653 
   8654 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
   8655 
   8656 /*
   8657 ** The SQLITE_AFF_MASK values masks off the significant bits of an
   8658 ** affinity value.
   8659 */
   8660 #define SQLITE_AFF_MASK     0x67
   8661 
   8662 /*
   8663 ** Additional bit values that can be ORed with an affinity without
   8664 ** changing the affinity.
   8665 */
   8666 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
   8667 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
   8668 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
   8669 
   8670 /*
   8671 ** An object of this type is created for each virtual table present in
   8672 ** the database schema.
   8673 **
   8674 ** If the database schema is shared, then there is one instance of this
   8675 ** structure for each database connection (sqlite3*) that uses the shared
   8676 ** schema. This is because each database connection requires its own unique
   8677 ** instance of the sqlite3_vtab* handle used to access the virtual table
   8678 ** implementation. sqlite3_vtab* handles can not be shared between
   8679 ** database connections, even when the rest of the in-memory database
   8680 ** schema is shared, as the implementation often stores the database
   8681 ** connection handle passed to it via the xConnect() or xCreate() method
   8682 ** during initialization internally. This database connection handle may
   8683 ** then used by the virtual table implementation to access real tables
   8684 ** within the database. So that they appear as part of the callers
   8685 ** transaction, these accesses need to be made via the same database
   8686 ** connection as that used to execute SQL operations on the virtual table.
   8687 **
   8688 ** All VTable objects that correspond to a single table in a shared
   8689 ** database schema are initially stored in a linked-list pointed to by
   8690 ** the Table.pVTable member variable of the corresponding Table object.
   8691 ** When an sqlite3_prepare() operation is required to access the virtual
   8692 ** table, it searches the list for the VTable that corresponds to the
   8693 ** database connection doing the preparing so as to use the correct
   8694 ** sqlite3_vtab* handle in the compiled query.
   8695 **
   8696 ** When an in-memory Table object is deleted (for example when the
   8697 ** schema is being reloaded for some reason), the VTable objects are not
   8698 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
   8699 ** immediately. Instead, they are moved from the Table.pVTable list to
   8700 ** another linked list headed by the sqlite3.pDisconnect member of the
   8701 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
   8702 ** next time a statement is prepared using said sqlite3*. This is done
   8703 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
   8704 ** Refer to comments above function sqlite3VtabUnlockList() for an
   8705 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
   8706 ** list without holding the corresponding sqlite3.mutex mutex.
   8707 **
   8708 ** The memory for objects of this type is always allocated by
   8709 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
   8710 ** the first argument.
   8711 */
   8712 struct VTable {
   8713   sqlite3 *db;              /* Database connection associated with this table */
   8714   Module *pMod;             /* Pointer to module implementation */
   8715   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
   8716   int nRef;                 /* Number of pointers to this structure */
   8717   VTable *pNext;            /* Next in linked list (see above) */
   8718 };
   8719 
   8720 /*
   8721 ** Each SQL table is represented in memory by an instance of the
   8722 ** following structure.
   8723 **
   8724 ** Table.zName is the name of the table.  The case of the original
   8725 ** CREATE TABLE statement is stored, but case is not significant for
   8726 ** comparisons.
   8727 **
   8728 ** Table.nCol is the number of columns in this table.  Table.aCol is a
   8729 ** pointer to an array of Column structures, one for each column.
   8730 **
   8731 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
   8732 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
   8733 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
   8734 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
   8735 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
   8736 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
   8737 ** the table has any PRIMARY KEY, INTEGER or otherwise.
   8738 **
   8739 ** Table.tnum is the page number for the root BTree page of the table in the
   8740 ** database file.  If Table.iDb is the index of the database table backend
   8741 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
   8742 ** holds temporary tables and indices.  If TF_Ephemeral is set
   8743 ** then the table is stored in a file that is automatically deleted
   8744 ** when the VDBE cursor to the table is closed.  In this case Table.tnum
   8745 ** refers VDBE cursor number that holds the table open, not to the root
   8746 ** page number.  Transient tables are used to hold the results of a
   8747 ** sub-query that appears instead of a real table name in the FROM clause
   8748 ** of a SELECT statement.
   8749 */
   8750 struct Table {
   8751   sqlite3 *dbMem;      /* DB connection used for lookaside allocations. */
   8752   char *zName;         /* Name of the table or view */
   8753   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
   8754   int nCol;            /* Number of columns in this table */
   8755   Column *aCol;        /* Information about each column */
   8756   Index *pIndex;       /* List of SQL indexes on this table. */
   8757   int tnum;            /* Root BTree node for this table (see note above) */
   8758   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
   8759   u16 nRef;            /* Number of pointers to this Table */
   8760   u8 tabFlags;         /* Mask of TF_* values */
   8761   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
   8762   FKey *pFKey;         /* Linked list of all foreign keys in this table */
   8763   char *zColAff;       /* String defining the affinity of each column */
   8764 #ifndef SQLITE_OMIT_CHECK
   8765   Expr *pCheck;        /* The AND of all CHECK constraints */
   8766 #endif
   8767 #ifndef SQLITE_OMIT_ALTERTABLE
   8768   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
   8769 #endif
   8770 #ifndef SQLITE_OMIT_VIRTUALTABLE
   8771   VTable *pVTable;     /* List of VTable objects. */
   8772   int nModuleArg;      /* Number of arguments to the module */
   8773   char **azModuleArg;  /* Text of all module args. [0] is module name */
   8774 #endif
   8775   Trigger *pTrigger;   /* List of triggers stored in pSchema */
   8776   Schema *pSchema;     /* Schema that contains this table */
   8777   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
   8778 };
   8779 
   8780 /*
   8781 ** Allowed values for Tabe.tabFlags.
   8782 */
   8783 #define TF_Readonly        0x01    /* Read-only system table */
   8784 #define TF_Ephemeral       0x02    /* An ephemeral table */
   8785 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
   8786 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
   8787 #define TF_Virtual         0x10    /* Is a virtual table */
   8788 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
   8789 
   8790 
   8791 
   8792 /*
   8793 ** Test to see whether or not a table is a virtual table.  This is
   8794 ** done as a macro so that it will be optimized out when virtual
   8795 ** table support is omitted from the build.
   8796 */
   8797 #ifndef SQLITE_OMIT_VIRTUALTABLE
   8798 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
   8799 #  define IsHiddenColumn(X) ((X)->isHidden)
   8800 #else
   8801 #  define IsVirtual(X)      0
   8802 #  define IsHiddenColumn(X) 0
   8803 #endif
   8804 
   8805 /*
   8806 ** Each foreign key constraint is an instance of the following structure.
   8807 **
   8808 ** A foreign key is associated with two tables.  The "from" table is
   8809 ** the table that contains the REFERENCES clause that creates the foreign
   8810 ** key.  The "to" table is the table that is named in the REFERENCES clause.
   8811 ** Consider this example:
   8812 **
   8813 **     CREATE TABLE ex1(
   8814 **       a INTEGER PRIMARY KEY,
   8815 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
   8816 **     );
   8817 **
   8818 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
   8819 **
   8820 ** Each REFERENCES clause generates an instance of the following structure
   8821 ** which is attached to the from-table.  The to-table need not exist when
   8822 ** the from-table is created.  The existence of the to-table is not checked.
   8823 */
   8824 struct FKey {
   8825   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
   8826   FKey *pNextFrom;  /* Next foreign key in pFrom */
   8827   char *zTo;        /* Name of table that the key points to (aka: Parent) */
   8828   FKey *pNextTo;    /* Next foreign key on table named zTo */
   8829   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
   8830   int nCol;         /* Number of columns in this key */
   8831   /* EV: R-30323-21917 */
   8832   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
   8833   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
   8834   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
   8835   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
   8836     int iFrom;         /* Index of column in pFrom */
   8837     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
   8838   } aCol[1];        /* One entry for each of nCol column s */
   8839 };
   8840 
   8841 /*
   8842 ** SQLite supports many different ways to resolve a constraint
   8843 ** error.  ROLLBACK processing means that a constraint violation
   8844 ** causes the operation in process to fail and for the current transaction
   8845 ** to be rolled back.  ABORT processing means the operation in process
   8846 ** fails and any prior changes from that one operation are backed out,
   8847 ** but the transaction is not rolled back.  FAIL processing means that
   8848 ** the operation in progress stops and returns an error code.  But prior
   8849 ** changes due to the same operation are not backed out and no rollback
   8850 ** occurs.  IGNORE means that the particular row that caused the constraint
   8851 ** error is not inserted or updated.  Processing continues and no error
   8852 ** is returned.  REPLACE means that preexisting database rows that caused
   8853 ** a UNIQUE constraint violation are removed so that the new insert or
   8854 ** update can proceed.  Processing continues and no error is reported.
   8855 **
   8856 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
   8857 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
   8858 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
   8859 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
   8860 ** referenced table row is propagated into the row that holds the
   8861 ** foreign key.
   8862 **
   8863 ** The following symbolic values are used to record which type
   8864 ** of action to take.
   8865 */
   8866 #define OE_None     0   /* There is no constraint to check */
   8867 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
   8868 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
   8869 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
   8870 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
   8871 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
   8872 
   8873 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
   8874 #define OE_SetNull  7   /* Set the foreign key value to NULL */
   8875 #define OE_SetDflt  8   /* Set the foreign key value to its default */
   8876 #define OE_Cascade  9   /* Cascade the changes */
   8877 
   8878 #define OE_Default  99  /* Do whatever the default action is */
   8879 
   8880 
   8881 /*
   8882 ** An instance of the following structure is passed as the first
   8883 ** argument to sqlite3VdbeKeyCompare and is used to control the
   8884 ** comparison of the two index keys.
   8885 */
   8886 struct KeyInfo {
   8887   sqlite3 *db;        /* The database connection */
   8888   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
   8889   u16 nField;         /* Number of entries in aColl[] */
   8890   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
   8891   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
   8892 };
   8893 
   8894 /*
   8895 ** An instance of the following structure holds information about a
   8896 ** single index record that has already been parsed out into individual
   8897 ** values.
   8898 **
   8899 ** A record is an object that contains one or more fields of data.
   8900 ** Records are used to store the content of a table row and to store
   8901 ** the key of an index.  A blob encoding of a record is created by
   8902 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
   8903 ** OP_Column opcode.
   8904 **
   8905 ** This structure holds a record that has already been disassembled
   8906 ** into its constituent fields.
   8907 */
   8908 struct UnpackedRecord {
   8909   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
   8910   u16 nField;         /* Number of entries in apMem[] */
   8911   u16 flags;          /* Boolean settings.  UNPACKED_... below */
   8912   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
   8913   Mem *aMem;          /* Values */
   8914 };
   8915 
   8916 /*
   8917 ** Allowed values of UnpackedRecord.flags
   8918 */
   8919 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
   8920 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
   8921 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
   8922 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
   8923 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
   8924 #define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
   8925 
   8926 /*
   8927 ** Each SQL index is represented in memory by an
   8928 ** instance of the following structure.
   8929 **
   8930 ** The columns of the table that are to be indexed are described
   8931 ** by the aiColumn[] field of this structure.  For example, suppose
   8932 ** we have the following table and index:
   8933 **
   8934 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
   8935 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
   8936 **
   8937 ** In the Table structure describing Ex1, nCol==3 because there are
   8938 ** three columns in the table.  In the Index structure describing
   8939 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
   8940 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
   8941 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
   8942 ** The second column to be indexed (c1) has an index of 0 in
   8943 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
   8944 **
   8945 ** The Index.onError field determines whether or not the indexed columns
   8946 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
   8947 ** it means this is not a unique index.  Otherwise it is a unique index
   8948 ** and the value of Index.onError indicate the which conflict resolution
   8949 ** algorithm to employ whenever an attempt is made to insert a non-unique
   8950 ** element.
   8951 */
   8952 struct Index {
   8953   char *zName;     /* Name of this index */
   8954   int nColumn;     /* Number of columns in the table used by this index */
   8955   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
   8956   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
   8957   Table *pTable;   /* The SQL table being indexed */
   8958   int tnum;        /* Page containing root of this index in database file */
   8959   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
   8960   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
   8961   char *zColAff;   /* String defining the affinity of each column */
   8962   Index *pNext;    /* The next index associated with the same table */
   8963   Schema *pSchema; /* Schema containing this index */
   8964   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
   8965   char **azColl;   /* Array of collation sequence names for index */
   8966   IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
   8967 };
   8968 
   8969 /*
   8970 ** Each sample stored in the sqlite_stat2 table is represented in memory
   8971 ** using a structure of this type.
   8972 */
   8973 struct IndexSample {
   8974   union {
   8975     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
   8976     double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
   8977   } u;
   8978   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
   8979   u8 nByte;         /* Size in byte of text or blob. */
   8980 };
   8981 
   8982 /*
   8983 ** Each token coming out of the lexer is an instance of
   8984 ** this structure.  Tokens are also used as part of an expression.
   8985 **
   8986 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
   8987 ** may contain random values.  Do not make any assumptions about Token.dyn
   8988 ** and Token.n when Token.z==0.
   8989 */
   8990 struct Token {
   8991   const char *z;     /* Text of the token.  Not NULL-terminated! */
   8992   unsigned int n;    /* Number of characters in this token */
   8993 };
   8994 
   8995 /*
   8996 ** An instance of this structure contains information needed to generate
   8997 ** code for a SELECT that contains aggregate functions.
   8998 **
   8999 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
   9000 ** pointer to this structure.  The Expr.iColumn field is the index in
   9001 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
   9002 ** code for that node.
   9003 **
   9004 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
   9005 ** original Select structure that describes the SELECT statement.  These
   9006 ** fields do not need to be freed when deallocating the AggInfo structure.
   9007 */
   9008 struct AggInfo {
   9009   u8 directMode;          /* Direct rendering mode means take data directly
   9010                           ** from source tables rather than from accumulators */
   9011   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
   9012                           ** than the source table */
   9013   int sortingIdx;         /* Cursor number of the sorting index */
   9014   ExprList *pGroupBy;     /* The group by clause */
   9015   int nSortingColumn;     /* Number of columns in the sorting index */
   9016   struct AggInfo_col {    /* For each column used in source tables */
   9017     Table *pTab;             /* Source table */
   9018     int iTable;              /* Cursor number of the source table */
   9019     int iColumn;             /* Column number within the source table */
   9020     int iSorterColumn;       /* Column number in the sorting index */
   9021     int iMem;                /* Memory location that acts as accumulator */
   9022     Expr *pExpr;             /* The original expression */
   9023   } *aCol;
   9024   int nColumn;            /* Number of used entries in aCol[] */
   9025   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
   9026   int nAccumulator;       /* Number of columns that show through to the output.
   9027                           ** Additional columns are used only as parameters to
   9028                           ** aggregate functions */
   9029   struct AggInfo_func {   /* For each aggregate function */
   9030     Expr *pExpr;             /* Expression encoding the function */
   9031     FuncDef *pFunc;          /* The aggregate function implementation */
   9032     int iMem;                /* Memory location that acts as accumulator */
   9033     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
   9034   } *aFunc;
   9035   int nFunc;              /* Number of entries in aFunc[] */
   9036   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
   9037 };
   9038 
   9039 /*
   9040 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
   9041 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
   9042 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
   9043 ** it uses less memory in the Expr object, which is a big memory user
   9044 ** in systems with lots of prepared statements.  And few applications
   9045 ** need more than about 10 or 20 variables.  But some extreme users want
   9046 ** to have prepared statements with over 32767 variables, and for them
   9047 ** the option is available (at compile-time).
   9048 */
   9049 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
   9050 typedef i16 ynVar;
   9051 #else
   9052 typedef int ynVar;
   9053 #endif
   9054 
   9055 /*
   9056 ** Each node of an expression in the parse tree is an instance
   9057 ** of this structure.
   9058 **
   9059 ** Expr.op is the opcode. The integer parser token codes are reused
   9060 ** as opcodes here. For example, the parser defines TK_GE to be an integer
   9061 ** code representing the ">=" operator. This same integer code is reused
   9062 ** to represent the greater-than-or-equal-to operator in the expression
   9063 ** tree.
   9064 **
   9065 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
   9066 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
   9067 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
   9068 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
   9069 ** then Expr.token contains the name of the function.
   9070 **
   9071 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
   9072 ** binary operator. Either or both may be NULL.
   9073 **
   9074 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
   9075 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
   9076 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
   9077 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
   9078 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
   9079 ** valid.
   9080 **
   9081 ** An expression of the form ID or ID.ID refers to a column in a table.
   9082 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
   9083 ** the integer cursor number of a VDBE cursor pointing to that table and
   9084 ** Expr.iColumn is the column number for the specific column.  If the
   9085 ** expression is used as a result in an aggregate SELECT, then the
   9086 ** value is also stored in the Expr.iAgg column in the aggregate so that
   9087 ** it can be accessed after all aggregates are computed.
   9088 **
   9089 ** If the expression is an unbound variable marker (a question mark
   9090 ** character '?' in the original SQL) then the Expr.iTable holds the index
   9091 ** number for that variable.
   9092 **
   9093 ** If the expression is a subquery then Expr.iColumn holds an integer
   9094 ** register number containing the result of the subquery.  If the
   9095 ** subquery gives a constant result, then iTable is -1.  If the subquery
   9096 ** gives a different answer at different times during statement processing
   9097 ** then iTable is the address of a subroutine that computes the subquery.
   9098 **
   9099 ** If the Expr is of type OP_Column, and the table it is selecting from
   9100 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
   9101 ** corresponding table definition.
   9102 **
   9103 ** ALLOCATION NOTES:
   9104 **
   9105 ** Expr objects can use a lot of memory space in database schema.  To
   9106 ** help reduce memory requirements, sometimes an Expr object will be
   9107 ** truncated.  And to reduce the number of memory allocations, sometimes
   9108 ** two or more Expr objects will be stored in a single memory allocation,
   9109 ** together with Expr.zToken strings.
   9110 **
   9111 ** If the EP_Reduced and EP_TokenOnly flags are set when
   9112 ** an Expr object is truncated.  When EP_Reduced is set, then all
   9113 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
   9114 ** are contained within the same memory allocation.  Note, however, that
   9115 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
   9116 ** allocated, regardless of whether or not EP_Reduced is set.
   9117 */
   9118 struct Expr {
   9119   u8 op;                 /* Operation performed by this node */
   9120   char affinity;         /* The affinity of the column or 0 if not a column */
   9121   u16 flags;             /* Various flags.  EP_* See below */
   9122   union {
   9123     char *zToken;          /* Token value. Zero terminated and dequoted */
   9124     int iValue;            /* Integer value if EP_IntValue */
   9125   } u;
   9126 
   9127   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
   9128   ** space is allocated for the fields below this point. An attempt to
   9129   ** access them will result in a segfault or malfunction.
   9130   *********************************************************************/
   9131 
   9132   Expr *pLeft;           /* Left subnode */
   9133   Expr *pRight;          /* Right subnode */
   9134   union {
   9135     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
   9136     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
   9137   } x;
   9138   CollSeq *pColl;        /* The collation type of the column or 0 */
   9139 
   9140   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
   9141   ** space is allocated for the fields below this point. An attempt to
   9142   ** access them will result in a segfault or malfunction.
   9143   *********************************************************************/
   9144 
   9145   int iTable;            /* TK_COLUMN: cursor number of table holding column
   9146                          ** TK_REGISTER: register number
   9147                          ** TK_TRIGGER: 1 -> new, 0 -> old */
   9148   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
   9149                          ** TK_VARIABLE: variable number (always >= 1). */
   9150   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
   9151   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
   9152   u8 flags2;             /* Second set of flags.  EP2_... */
   9153   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
   9154   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
   9155   Table *pTab;           /* Table for TK_COLUMN expressions. */
   9156 #if SQLITE_MAX_EXPR_DEPTH>0
   9157   int nHeight;           /* Height of the tree headed by this node */
   9158 #endif
   9159 };
   9160 
   9161 /*
   9162 ** The following are the meanings of bits in the Expr.flags field.
   9163 */
   9164 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
   9165 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
   9166 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
   9167 #define EP_Error      0x0008  /* Expression contains one or more errors */
   9168 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
   9169 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
   9170 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
   9171 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
   9172 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
   9173 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
   9174 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
   9175 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
   9176 
   9177 #define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
   9178 #define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
   9179 #define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
   9180 
   9181 /*
   9182 ** The following are the meanings of bits in the Expr.flags2 field.
   9183 */
   9184 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
   9185 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
   9186 
   9187 /*
   9188 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
   9189 ** flag on an expression structure.  This flag is used for VV&A only.  The
   9190 ** routine is implemented as a macro that only works when in debugging mode,
   9191 ** so as not to burden production code.
   9192 */
   9193 #ifdef SQLITE_DEBUG
   9194 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
   9195 #else
   9196 # define ExprSetIrreducible(X)
   9197 #endif
   9198 
   9199 /*
   9200 ** These macros can be used to test, set, or clear bits in the
   9201 ** Expr.flags field.
   9202 */
   9203 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
   9204 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
   9205 #define ExprSetProperty(E,P)     (E)->flags|=(P)
   9206 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
   9207 
   9208 /*
   9209 ** Macros to determine the number of bytes required by a normal Expr
   9210 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
   9211 ** and an Expr struct with the EP_TokenOnly flag set.
   9212 */
   9213 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
   9214 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
   9215 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
   9216 
   9217 /*
   9218 ** Flags passed to the sqlite3ExprDup() function. See the header comment
   9219 ** above sqlite3ExprDup() for details.
   9220 */
   9221 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
   9222 
   9223 /*
   9224 ** A list of expressions.  Each expression may optionally have a
   9225 ** name.  An expr/name combination can be used in several ways, such
   9226 ** as the list of "expr AS ID" fields following a "SELECT" or in the
   9227 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
   9228 ** also be used as the argument to a function, in which case the a.zName
   9229 ** field is not used.
   9230 */
   9231 struct ExprList {
   9232   int nExpr;             /* Number of expressions on the list */
   9233   int nAlloc;            /* Number of entries allocated below */
   9234   int iECursor;          /* VDBE Cursor associated with this ExprList */
   9235   struct ExprList_item {
   9236     Expr *pExpr;           /* The list of expressions */
   9237     char *zName;           /* Token associated with this expression */
   9238     char *zSpan;           /* Original text of the expression */
   9239     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
   9240     u8 done;               /* A flag to indicate when processing is finished */
   9241     u16 iCol;              /* For ORDER BY, column number in result set */
   9242     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
   9243   } *a;                  /* One entry for each expression */
   9244 };
   9245 
   9246 /*
   9247 ** An instance of this structure is used by the parser to record both
   9248 ** the parse tree for an expression and the span of input text for an
   9249 ** expression.
   9250 */
   9251 struct ExprSpan {
   9252   Expr *pExpr;          /* The expression parse tree */
   9253   const char *zStart;   /* First character of input text */
   9254   const char *zEnd;     /* One character past the end of input text */
   9255 };
   9256 
   9257 /*
   9258 ** An instance of this structure can hold a simple list of identifiers,
   9259 ** such as the list "a,b,c" in the following statements:
   9260 **
   9261 **      INSERT INTO t(a,b,c) VALUES ...;
   9262 **      CREATE INDEX idx ON t(a,b,c);
   9263 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
   9264 **
   9265 ** The IdList.a.idx field is used when the IdList represents the list of
   9266 ** column names after a table name in an INSERT statement.  In the statement
   9267 **
   9268 **     INSERT INTO t(a,b,c) ...
   9269 **
   9270 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
   9271 */
   9272 struct IdList {
   9273   struct IdList_item {
   9274     char *zName;      /* Name of the identifier */
   9275     int idx;          /* Index in some Table.aCol[] of a column named zName */
   9276   } *a;
   9277   int nId;         /* Number of identifiers on the list */
   9278   int nAlloc;      /* Number of entries allocated for a[] below */
   9279 };
   9280 
   9281 /*
   9282 ** The bitmask datatype defined below is used for various optimizations.
   9283 **
   9284 ** Changing this from a 64-bit to a 32-bit type limits the number of
   9285 ** tables in a join to 32 instead of 64.  But it also reduces the size
   9286 ** of the library by 738 bytes on ix86.
   9287 */
   9288 typedef u64 Bitmask;
   9289 
   9290 /*
   9291 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
   9292 */
   9293 #define BMS  ((int)(sizeof(Bitmask)*8))
   9294 
   9295 /*
   9296 ** The following structure describes the FROM clause of a SELECT statement.
   9297 ** Each table or subquery in the FROM clause is a separate element of
   9298 ** the SrcList.a[] array.
   9299 **
   9300 ** With the addition of multiple database support, the following structure
   9301 ** can also be used to describe a particular table such as the table that
   9302 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
   9303 ** such a table must be a simple name: ID.  But in SQLite, the table can
   9304 ** now be identified by a database name, a dot, then the table name: ID.ID.
   9305 **
   9306 ** The jointype starts out showing the join type between the current table
   9307 ** and the next table on the list.  The parser builds the list this way.
   9308 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
   9309 ** jointype expresses the join between the table and the previous table.
   9310 */
   9311 struct SrcList {
   9312   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
   9313   i16 nAlloc;      /* Number of entries allocated in a[] below */
   9314   struct SrcList_item {
   9315     char *zDatabase;  /* Name of database holding this table */
   9316     char *zName;      /* Name of the table */
   9317     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
   9318     Table *pTab;      /* An SQL table corresponding to zName */
   9319     Select *pSelect;  /* A SELECT statement used in place of a table name */
   9320     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
   9321     u8 jointype;      /* Type of join between this able and the previous */
   9322     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
   9323     int iCursor;      /* The VDBE cursor number used to access this table */
   9324     Expr *pOn;        /* The ON clause of a join */
   9325     IdList *pUsing;   /* The USING clause of a join */
   9326     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
   9327     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
   9328     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
   9329   } a[1];             /* One entry for each identifier on the list */
   9330 };
   9331 
   9332 /*
   9333 ** Permitted values of the SrcList.a.jointype field
   9334 */
   9335 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
   9336 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
   9337 #define JT_NATURAL   0x0004    /* True for a "natural" join */
   9338 #define JT_LEFT      0x0008    /* Left outer join */
   9339 #define JT_RIGHT     0x0010    /* Right outer join */
   9340 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
   9341 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
   9342 
   9343 
   9344 /*
   9345 ** A WherePlan object holds information that describes a lookup
   9346 ** strategy.
   9347 **
   9348 ** This object is intended to be opaque outside of the where.c module.
   9349 ** It is included here only so that that compiler will know how big it
   9350 ** is.  None of the fields in this object should be used outside of
   9351 ** the where.c module.
   9352 **
   9353 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
   9354 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
   9355 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
   9356 ** case that more than one of these conditions is true.
   9357 */
   9358 struct WherePlan {
   9359   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
   9360   u32 nEq;                       /* Number of == constraints */
   9361   union {
   9362     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
   9363     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
   9364     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
   9365   } u;
   9366 };
   9367 
   9368 /*
   9369 ** For each nested loop in a WHERE clause implementation, the WhereInfo
   9370 ** structure contains a single instance of this structure.  This structure
   9371 ** is intended to be private the the where.c module and should not be
   9372 ** access or modified by other modules.
   9373 **
   9374 ** The pIdxInfo field is used to help pick the best index on a
   9375 ** virtual table.  The pIdxInfo pointer contains indexing
   9376 ** information for the i-th table in the FROM clause before reordering.
   9377 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
   9378 ** All other information in the i-th WhereLevel object for the i-th table
   9379 ** after FROM clause ordering.
   9380 */
   9381 struct WhereLevel {
   9382   WherePlan plan;       /* query plan for this element of the FROM clause */
   9383   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
   9384   int iTabCur;          /* The VDBE cursor used to access the table */
   9385   int iIdxCur;          /* The VDBE cursor used to access pIdx */
   9386   int addrBrk;          /* Jump here to break out of the loop */
   9387   int addrNxt;          /* Jump here to start the next IN combination */
   9388   int addrCont;         /* Jump here to continue with the next loop cycle */
   9389   int addrFirst;        /* First instruction of interior of the loop */
   9390   u8 iFrom;             /* Which entry in the FROM clause */
   9391   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
   9392   int p1, p2;           /* Operands of the opcode used to ends the loop */
   9393   union {               /* Information that depends on plan.wsFlags */
   9394     struct {
   9395       int nIn;              /* Number of entries in aInLoop[] */
   9396       struct InLoop {
   9397         int iCur;              /* The VDBE cursor used by this IN operator */
   9398         int addrInTop;         /* Top of the IN loop */
   9399       } *aInLoop;           /* Information about each nested IN operator */
   9400     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
   9401   } u;
   9402 
   9403   /* The following field is really not part of the current level.  But
   9404   ** we need a place to cache virtual table index information for each
   9405   ** virtual table in the FROM clause and the WhereLevel structure is
   9406   ** a convenient place since there is one WhereLevel for each FROM clause
   9407   ** element.
   9408   */
   9409   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
   9410 };
   9411 
   9412 /*
   9413 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
   9414 ** and the WhereInfo.wctrlFlags member.
   9415 */
   9416 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
   9417 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
   9418 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
   9419 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
   9420 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
   9421 #define WHERE_OMIT_OPEN        0x0010 /* Table cursor are already open */
   9422 #define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
   9423 #define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
   9424 #define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
   9425 
   9426 /*
   9427 ** The WHERE clause processing routine has two halves.  The
   9428 ** first part does the start of the WHERE loop and the second
   9429 ** half does the tail of the WHERE loop.  An instance of
   9430 ** this structure is returned by the first half and passed
   9431 ** into the second half to give some continuity.
   9432 */
   9433 struct WhereInfo {
   9434   Parse *pParse;       /* Parsing and code generating context */
   9435   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
   9436   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
   9437   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
   9438   SrcList *pTabList;             /* List of tables in the join */
   9439   int iTop;                      /* The very beginning of the WHERE loop */
   9440   int iContinue;                 /* Jump here to continue with next record */
   9441   int iBreak;                    /* Jump here to break out of the loop */
   9442   int nLevel;                    /* Number of nested loop */
   9443   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
   9444   WhereLevel a[1];               /* Information about each nest loop in WHERE */
   9445 };
   9446 
   9447 /*
   9448 ** A NameContext defines a context in which to resolve table and column
   9449 ** names.  The context consists of a list of tables (the pSrcList) field and
   9450 ** a list of named expression (pEList).  The named expression list may
   9451 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
   9452 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
   9453 ** pEList corresponds to the result set of a SELECT and is NULL for
   9454 ** other statements.
   9455 **
   9456 ** NameContexts can be nested.  When resolving names, the inner-most
   9457 ** context is searched first.  If no match is found, the next outer
   9458 ** context is checked.  If there is still no match, the next context
   9459 ** is checked.  This process continues until either a match is found
   9460 ** or all contexts are check.  When a match is found, the nRef member of
   9461 ** the context containing the match is incremented.
   9462 **
   9463 ** Each subquery gets a new NameContext.  The pNext field points to the
   9464 ** NameContext in the parent query.  Thus the process of scanning the
   9465 ** NameContext list corresponds to searching through successively outer
   9466 ** subqueries looking for a match.
   9467 */
   9468 struct NameContext {
   9469   Parse *pParse;       /* The parser */
   9470   SrcList *pSrcList;   /* One or more tables used to resolve names */
   9471   ExprList *pEList;    /* Optional list of named expressions */
   9472   int nRef;            /* Number of names resolved by this context */
   9473   int nErr;            /* Number of errors encountered while resolving names */
   9474   u8 allowAgg;         /* Aggregate functions allowed here */
   9475   u8 hasAgg;           /* True if aggregates are seen */
   9476   u8 isCheck;          /* True if resolving names in a CHECK constraint */
   9477   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
   9478   AggInfo *pAggInfo;   /* Information about aggregates at this level */
   9479   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
   9480 };
   9481 
   9482 /*
   9483 ** An instance of the following structure contains all information
   9484 ** needed to generate code for a single SELECT statement.
   9485 **
   9486 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
   9487 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
   9488 ** limit and nOffset to the value of the offset (or 0 if there is not
   9489 ** offset).  But later on, nLimit and nOffset become the memory locations
   9490 ** in the VDBE that record the limit and offset counters.
   9491 **
   9492 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
   9493 ** These addresses must be stored so that we can go back and fill in
   9494 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
   9495 ** the number of columns in P2 can be computed at the same time
   9496 ** as the OP_OpenEphm instruction is coded because not
   9497 ** enough information about the compound query is known at that point.
   9498 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
   9499 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
   9500 ** sequences for the ORDER BY clause.
   9501 */
   9502 struct Select {
   9503   ExprList *pEList;      /* The fields of the result */
   9504   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
   9505   char affinity;         /* MakeRecord with this affinity for SRT_Set */
   9506   u16 selFlags;          /* Various SF_* values */
   9507   SrcList *pSrc;         /* The FROM clause */
   9508   Expr *pWhere;          /* The WHERE clause */
   9509   ExprList *pGroupBy;    /* The GROUP BY clause */
   9510   Expr *pHaving;         /* The HAVING clause */
   9511   ExprList *pOrderBy;    /* The ORDER BY clause */
   9512   Select *pPrior;        /* Prior select in a compound select statement */
   9513   Select *pNext;         /* Next select to the left in a compound */
   9514   Select *pRightmost;    /* Right-most select in a compound select statement */
   9515   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
   9516   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
   9517   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
   9518   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
   9519 };
   9520 
   9521 /*
   9522 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
   9523 ** "Select Flag".
   9524 */
   9525 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
   9526 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
   9527 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
   9528 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
   9529 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
   9530 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
   9531 
   9532 
   9533 /*
   9534 ** The results of a select can be distributed in several ways.  The
   9535 ** "SRT" prefix means "SELECT Result Type".
   9536 */
   9537 #define SRT_Union        1  /* Store result as keys in an index */
   9538 #define SRT_Except       2  /* Remove result from a UNION index */
   9539 #define SRT_Exists       3  /* Store 1 if the result is not empty */
   9540 #define SRT_Discard      4  /* Do not save the results anywhere */
   9541 
   9542 /* The ORDER BY clause is ignored for all of the above */
   9543 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
   9544 
   9545 #define SRT_Output       5  /* Output each row of result */
   9546 #define SRT_Mem          6  /* Store result in a memory cell */
   9547 #define SRT_Set          7  /* Store results as keys in an index */
   9548 #define SRT_Table        8  /* Store result as data with an automatic rowid */
   9549 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
   9550 #define SRT_Coroutine   10  /* Generate a single row of result */
   9551 
   9552 /*
   9553 ** A structure used to customize the behavior of sqlite3Select(). See
   9554 ** comments above sqlite3Select() for details.
   9555 */
   9556 typedef struct SelectDest SelectDest;
   9557 struct SelectDest {
   9558   u8 eDest;         /* How to dispose of the results */
   9559   u8 affinity;      /* Affinity used when eDest==SRT_Set */
   9560   int iParm;        /* A parameter used by the eDest disposal method */
   9561   int iMem;         /* Base register where results are written */
   9562   int nMem;         /* Number of registers allocated */
   9563 };
   9564 
   9565 /*
   9566 ** During code generation of statements that do inserts into AUTOINCREMENT
   9567 ** tables, the following information is attached to the Table.u.autoInc.p
   9568 ** pointer of each autoincrement table to record some side information that
   9569 ** the code generator needs.  We have to keep per-table autoincrement
   9570 ** information in case inserts are down within triggers.  Triggers do not
   9571 ** normally coordinate their activities, but we do need to coordinate the
   9572 ** loading and saving of autoincrement information.
   9573 */
   9574 struct AutoincInfo {
   9575   AutoincInfo *pNext;   /* Next info block in a list of them all */
   9576   Table *pTab;          /* Table this info block refers to */
   9577   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
   9578   int regCtr;           /* Memory register holding the rowid counter */
   9579 };
   9580 
   9581 /*
   9582 ** Size of the column cache
   9583 */
   9584 #ifndef SQLITE_N_COLCACHE
   9585 # define SQLITE_N_COLCACHE 10
   9586 #endif
   9587 
   9588 /*
   9589 ** At least one instance of the following structure is created for each
   9590 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
   9591 ** statement. All such objects are stored in the linked list headed at
   9592 ** Parse.pTriggerPrg and deleted once statement compilation has been
   9593 ** completed.
   9594 **
   9595 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
   9596 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
   9597 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
   9598 ** The Parse.pTriggerPrg list never contains two entries with the same
   9599 ** values for both pTrigger and orconf.
   9600 **
   9601 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
   9602 ** accessed (or set to 0 for triggers fired as a result of INSERT
   9603 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
   9604 ** a mask of new.* columns used by the program.
   9605 */
   9606 struct TriggerPrg {
   9607   Trigger *pTrigger;      /* Trigger this program was coded from */
   9608   int orconf;             /* Default ON CONFLICT policy */
   9609   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
   9610   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
   9611   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
   9612 };
   9613 
   9614 /*
   9615 ** An SQL parser context.  A copy of this structure is passed through
   9616 ** the parser and down into all the parser action routine in order to
   9617 ** carry around information that is global to the entire parse.
   9618 **
   9619 ** The structure is divided into two parts.  When the parser and code
   9620 ** generate call themselves recursively, the first part of the structure
   9621 ** is constant but the second part is reset at the beginning and end of
   9622 ** each recursion.
   9623 **
   9624 ** The nTableLock and aTableLock variables are only used if the shared-cache
   9625 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
   9626 ** used to store the set of table-locks required by the statement being
   9627 ** compiled. Function sqlite3TableLock() is used to add entries to the
   9628 ** list.
   9629 */
   9630 struct Parse {
   9631   sqlite3 *db;         /* The main database structure */
   9632   int rc;              /* Return code from execution */
   9633   char *zErrMsg;       /* An error message */
   9634   Vdbe *pVdbe;         /* An engine for executing database bytecode */
   9635   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
   9636   u8 nameClash;        /* A permanent table name clashes with temp table name */
   9637   u8 checkSchema;      /* Causes schema cookie check after an error */
   9638   u8 nested;           /* Number of nested calls to the parser/code generator */
   9639   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
   9640   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
   9641   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
   9642   int aTempReg[8];     /* Holding area for temporary registers */
   9643   int nRangeReg;       /* Size of the temporary register block */
   9644   int iRangeReg;       /* First register in temporary register block */
   9645   int nErr;            /* Number of errors seen */
   9646   int nTab;            /* Number of previously allocated VDBE cursors */
   9647   int nMem;            /* Number of memory cells used so far */
   9648   int nSet;            /* Number of sets used so far */
   9649   int ckBase;          /* Base register of data during check constraints */
   9650   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
   9651   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
   9652   u8 nColCache;        /* Number of entries in the column cache */
   9653   u8 iColCache;        /* Next entry of the cache to replace */
   9654   struct yColCache {
   9655     int iTable;           /* Table cursor number */
   9656     int iColumn;          /* Table column number */
   9657     u8 tempReg;           /* iReg is a temp register that needs to be freed */
   9658     int iLevel;           /* Nesting level */
   9659     int iReg;             /* Reg with value of this column. 0 means none. */
   9660     int lru;              /* Least recently used entry has the smallest value */
   9661   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
   9662   u32 writeMask;       /* Start a write transaction on these databases */
   9663   u32 cookieMask;      /* Bitmask of schema verified databases */
   9664   u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
   9665   u8 mayAbort;         /* True if statement may throw an ABORT exception */
   9666   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
   9667   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
   9668 #ifndef SQLITE_OMIT_SHARED_CACHE
   9669   int nTableLock;        /* Number of locks in aTableLock */
   9670   TableLock *aTableLock; /* Required table locks for shared-cache mode */
   9671 #endif
   9672   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
   9673   int regRoot;         /* Register holding root page number for new objects */
   9674   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
   9675   int nMaxArg;         /* Max args passed to user function by sub-program */
   9676 
   9677   /* Information used while coding trigger programs. */
   9678   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
   9679   Table *pTriggerTab;  /* Table triggers are being coded for */
   9680   u32 oldmask;         /* Mask of old.* columns referenced */
   9681   u32 newmask;         /* Mask of new.* columns referenced */
   9682   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
   9683   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
   9684   u8 disableTriggers;  /* True to disable triggers */
   9685 
   9686   /* Above is constant between recursions.  Below is reset before and after
   9687   ** each recursion */
   9688 
   9689   int nVar;            /* Number of '?' variables seen in the SQL so far */
   9690   int nVarExpr;        /* Number of used slots in apVarExpr[] */
   9691   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
   9692   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
   9693   Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
   9694   int nAlias;          /* Number of aliased result set columns */
   9695   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
   9696   int *aAlias;         /* Register used to hold aliased result */
   9697   u8 explain;          /* True if the EXPLAIN flag is found on the query */
   9698   Token sNameToken;    /* Token with unqualified schema object name */
   9699   Token sLastToken;    /* The last token parsed */
   9700   const char *zTail;   /* All SQL text past the last semicolon parsed */
   9701   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
   9702   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
   9703   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
   9704 #ifndef SQLITE_OMIT_VIRTUALTABLE
   9705   Token sArg;                /* Complete text of a module argument */
   9706   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
   9707   int nVtabLock;             /* Number of virtual tables to lock */
   9708   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
   9709 #endif
   9710   int nHeight;            /* Expression tree height of current sub-select */
   9711   Table *pZombieTab;      /* List of Table objects to delete after code gen */
   9712   TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
   9713 };
   9714 
   9715 #ifdef SQLITE_OMIT_VIRTUALTABLE
   9716   #define IN_DECLARE_VTAB 0
   9717 #else
   9718   #define IN_DECLARE_VTAB (pParse->declareVtab)
   9719 #endif
   9720 
   9721 /*
   9722 ** An instance of the following structure can be declared on a stack and used
   9723 ** to save the Parse.zAuthContext value so that it can be restored later.
   9724 */
   9725 struct AuthContext {
   9726   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
   9727   Parse *pParse;              /* The Parse structure */
   9728 };
   9729 
   9730 /*
   9731 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
   9732 */
   9733 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
   9734 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
   9735 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
   9736 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
   9737 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
   9738 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
   9739 
   9740 /*
   9741  * Each trigger present in the database schema is stored as an instance of
   9742  * struct Trigger.
   9743  *
   9744  * Pointers to instances of struct Trigger are stored in two ways.
   9745  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
   9746  *    database). This allows Trigger structures to be retrieved by name.
   9747  * 2. All triggers associated with a single table form a linked list, using the
   9748  *    pNext member of struct Trigger. A pointer to the first element of the
   9749  *    linked list is stored as the "pTrigger" member of the associated
   9750  *    struct Table.
   9751  *
   9752  * The "step_list" member points to the first element of a linked list
   9753  * containing the SQL statements specified as the trigger program.
   9754  */
   9755 struct Trigger {
   9756   char *zName;            /* The name of the trigger                        */
   9757   char *table;            /* The table or view to which the trigger applies */
   9758   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
   9759   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
   9760   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
   9761   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
   9762                              the <column-list> is stored here */
   9763   Schema *pSchema;        /* Schema containing the trigger */
   9764   Schema *pTabSchema;     /* Schema containing the table */
   9765   TriggerStep *step_list; /* Link list of trigger program steps             */
   9766   Trigger *pNext;         /* Next trigger associated with the table */
   9767 };
   9768 
   9769 /*
   9770 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
   9771 ** determine which.
   9772 **
   9773 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
   9774 ** In that cases, the constants below can be ORed together.
   9775 */
   9776 #define TRIGGER_BEFORE  1
   9777 #define TRIGGER_AFTER   2
   9778 
   9779 /*
   9780  * An instance of struct TriggerStep is used to store a single SQL statement
   9781  * that is a part of a trigger-program.
   9782  *
   9783  * Instances of struct TriggerStep are stored in a singly linked list (linked
   9784  * using the "pNext" member) referenced by the "step_list" member of the
   9785  * associated struct Trigger instance. The first element of the linked list is
   9786  * the first step of the trigger-program.
   9787  *
   9788  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
   9789  * "SELECT" statement. The meanings of the other members is determined by the
   9790  * value of "op" as follows:
   9791  *
   9792  * (op == TK_INSERT)
   9793  * orconf    -> stores the ON CONFLICT algorithm
   9794  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
   9795  *              this stores a pointer to the SELECT statement. Otherwise NULL.
   9796  * target    -> A token holding the quoted name of the table to insert into.
   9797  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
   9798  *              this stores values to be inserted. Otherwise NULL.
   9799  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
   9800  *              statement, then this stores the column-names to be
   9801  *              inserted into.
   9802  *
   9803  * (op == TK_DELETE)
   9804  * target    -> A token holding the quoted name of the table to delete from.
   9805  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
   9806  *              Otherwise NULL.
   9807  *
   9808  * (op == TK_UPDATE)
   9809  * target    -> A token holding the quoted name of the table to update rows of.
   9810  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
   9811  *              Otherwise NULL.
   9812  * pExprList -> A list of the columns to update and the expressions to update
   9813  *              them to. See sqlite3Update() documentation of "pChanges"
   9814  *              argument.
   9815  *
   9816  */
   9817 struct TriggerStep {
   9818   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
   9819   u8 orconf;           /* OE_Rollback etc. */
   9820   Trigger *pTrig;      /* The trigger that this step is a part of */
   9821   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
   9822   Token target;        /* Target table for DELETE, UPDATE, INSERT */
   9823   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
   9824   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
   9825   IdList *pIdList;     /* Column names for INSERT */
   9826   TriggerStep *pNext;  /* Next in the link-list */
   9827   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
   9828 };
   9829 
   9830 /*
   9831 ** The following structure contains information used by the sqliteFix...
   9832 ** routines as they walk the parse tree to make database references
   9833 ** explicit.
   9834 */
   9835 typedef struct DbFixer DbFixer;
   9836 struct DbFixer {
   9837   Parse *pParse;      /* The parsing context.  Error messages written here */
   9838   const char *zDb;    /* Make sure all objects are contained in this database */
   9839   const char *zType;  /* Type of the container - used for error messages */
   9840   const Token *pName; /* Name of the container - used for error messages */
   9841 };
   9842 
   9843 /*
   9844 ** An objected used to accumulate the text of a string where we
   9845 ** do not necessarily know how big the string will be in the end.
   9846 */
   9847 struct StrAccum {
   9848   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
   9849   char *zBase;         /* A base allocation.  Not from malloc. */
   9850   char *zText;         /* The string collected so far */
   9851   int  nChar;          /* Length of the string so far */
   9852   int  nAlloc;         /* Amount of space allocated in zText */
   9853   int  mxAlloc;        /* Maximum allowed string length */
   9854   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
   9855   u8   useMalloc;      /* True if zText is enlargeable using realloc */
   9856   u8   tooBig;         /* Becomes true if string size exceeds limits */
   9857 };
   9858 
   9859 /*
   9860 ** A pointer to this structure is used to communicate information
   9861 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
   9862 */
   9863 typedef struct {
   9864   sqlite3 *db;        /* The database being initialized */
   9865   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
   9866   char **pzErrMsg;    /* Error message stored here */
   9867   int rc;             /* Result code stored here */
   9868 } InitData;
   9869 
   9870 /*
   9871 ** Structure containing global configuration data for the SQLite library.
   9872 **
   9873 ** This structure also contains some state information.
   9874 */
   9875 struct Sqlite3Config {
   9876   int bMemstat;                     /* True to enable memory status */
   9877   int bCoreMutex;                   /* True to enable core mutexing */
   9878   int bFullMutex;                   /* True to enable full mutexing */
   9879   int mxStrlen;                     /* Maximum string length */
   9880   int szLookaside;                  /* Default lookaside buffer size */
   9881   int nLookaside;                   /* Default lookaside buffer count */
   9882   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
   9883   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
   9884   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
   9885   void *pHeap;                      /* Heap storage space */
   9886   int nHeap;                        /* Size of pHeap[] */
   9887   int mnReq, mxReq;                 /* Min and max heap requests sizes */
   9888   void *pScratch;                   /* Scratch memory */
   9889   int szScratch;                    /* Size of each scratch buffer */
   9890   int nScratch;                     /* Number of scratch buffers */
   9891   void *pPage;                      /* Page cache memory */
   9892   int szPage;                       /* Size of each page in pPage[] */
   9893   int nPage;                        /* Number of pages in pPage[] */
   9894   int mxParserStack;                /* maximum depth of the parser stack */
   9895   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
   9896   /* The above might be initialized to non-zero.  The following need to always
   9897   ** initially be zero, however. */
   9898   int isInit;                       /* True after initialization has finished */
   9899   int inProgress;                   /* True while initialization in progress */
   9900   int isMutexInit;                  /* True after mutexes are initialized */
   9901   int isMallocInit;                 /* True after malloc is initialized */
   9902   int isPCacheInit;                 /* True after malloc is initialized */
   9903   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
   9904   int nRefInitMutex;                /* Number of users of pInitMutex */
   9905   void (*xLog)(void*,int,const char*); /* Function for logging */
   9906   void *pLogArg;                       /* First argument to xLog() */
   9907 };
   9908 
   9909 /*
   9910 ** Context pointer passed down through the tree-walk.
   9911 */
   9912 struct Walker {
   9913   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
   9914   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
   9915   Parse *pParse;                            /* Parser context.  */
   9916   union {                                   /* Extra data for callback */
   9917     NameContext *pNC;                          /* Naming context */
   9918     int i;                                     /* Integer value */
   9919   } u;
   9920 };
   9921 
   9922 /* Forward declarations */
   9923 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
   9924 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
   9925 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
   9926 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
   9927 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
   9928 
   9929 /*
   9930 ** Return code from the parse-tree walking primitives and their
   9931 ** callbacks.
   9932 */
   9933 #define WRC_Continue    0   /* Continue down into children */
   9934 #define WRC_Prune       1   /* Omit children but continue walking siblings */
   9935 #define WRC_Abort       2   /* Abandon the tree walk */
   9936 
   9937 /*
   9938 ** Assuming zIn points to the first byte of a UTF-8 character,
   9939 ** advance zIn to point to the first byte of the next UTF-8 character.
   9940 */
   9941 #define SQLITE_SKIP_UTF8(zIn) {                        \
   9942   if( (*(zIn++))>=0xc0 ){                              \
   9943     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
   9944   }                                                    \
   9945 }
   9946 
   9947 /*
   9948 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
   9949 ** the same name but without the _BKPT suffix.  These macros invoke
   9950 ** routines that report the line-number on which the error originated
   9951 ** using sqlite3_log().  The routines also provide a convenient place
   9952 ** to set a debugger breakpoint.
   9953 */
   9954 SQLITE_PRIVATE int sqlite3CorruptError(int);
   9955 SQLITE_PRIVATE int sqlite3MisuseError(int);
   9956 SQLITE_PRIVATE int sqlite3CantopenError(int);
   9957 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
   9958 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
   9959 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
   9960 
   9961 
   9962 /*
   9963 ** The ctype.h header is needed for non-ASCII systems.  It is also
   9964 ** needed by FTS3 when FTS3 is included in the amalgamation.
   9965 */
   9966 #if !defined(SQLITE_ASCII) || \
   9967     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
   9968 # include <ctype.h>
   9969 #endif
   9970 
   9971 /*
   9972 ** The following macros mimic the standard library functions toupper(),
   9973 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
   9974 ** sqlite versions only work for ASCII characters, regardless of locale.
   9975 */
   9976 #ifdef SQLITE_ASCII
   9977 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
   9978 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
   9979 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
   9980 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
   9981 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
   9982 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
   9983 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
   9984 #else
   9985 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
   9986 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
   9987 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
   9988 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
   9989 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
   9990 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
   9991 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
   9992 #endif
   9993 
   9994 /*
   9995 ** Internal function prototypes
   9996 */
   9997 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
   9998 SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
   9999 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
   10000 #define sqlite3StrNICmp sqlite3_strnicmp
   10001 
   10002 SQLITE_PRIVATE int sqlite3MallocInit(void);
   10003 SQLITE_PRIVATE void sqlite3MallocEnd(void);
   10004 SQLITE_PRIVATE void *sqlite3Malloc(int);
   10005 SQLITE_PRIVATE void *sqlite3MallocZero(int);
   10006 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
   10007 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
   10008 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
   10009 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
   10010 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
   10011 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
   10012 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
   10013 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
   10014 SQLITE_PRIVATE int sqlite3MallocSize(void*);
   10015 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
   10016 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
   10017 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
   10018 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
   10019 SQLITE_PRIVATE void sqlite3PageFree(void*);
   10020 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
   10021 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
   10022 SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
   10023 
   10024 /*
   10025 ** On systems with ample stack space and that support alloca(), make
   10026 ** use of alloca() to obtain space for large automatic objects.  By default,
   10027 ** obtain space from malloc().
   10028 **
   10029 ** The alloca() routine never returns NULL.  This will cause code paths
   10030 ** that deal with sqlite3StackAlloc() failures to be unreachable.
   10031 */
   10032 #ifdef SQLITE_USE_ALLOCA
   10033 # define sqlite3StackAllocRaw(D,N)   alloca(N)
   10034 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
   10035 # define sqlite3StackFree(D,P)
   10036 #else
   10037 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
   10038 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
   10039 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
   10040 #endif
   10041 
   10042 #ifdef SQLITE_ENABLE_MEMSYS3
   10043 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
   10044 #endif
   10045 #ifdef SQLITE_ENABLE_MEMSYS5
   10046 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
   10047 #endif
   10048 
   10049 
   10050 #ifndef SQLITE_MUTEX_OMIT
   10051 SQLITE_PRIVATE   sqlite3_mutex_methods *sqlite3DefaultMutex(void);
   10052 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
   10053 SQLITE_PRIVATE   int sqlite3MutexInit(void);
   10054 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
   10055 #endif
   10056 
   10057 SQLITE_PRIVATE int sqlite3StatusValue(int);
   10058 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
   10059 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
   10060 
   10061 SQLITE_PRIVATE int sqlite3IsNaN(double);
   10062 
   10063 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
   10064 #ifndef SQLITE_OMIT_TRACE
   10065 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
   10066 #endif
   10067 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
   10068 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
   10069 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
   10070 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
   10071 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
   10072 #endif
   10073 #if defined(SQLITE_TEST)
   10074 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
   10075 #endif
   10076 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
   10077 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
   10078 SQLITE_PRIVATE int sqlite3Dequote(char*);
   10079 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
   10080 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
   10081 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
   10082 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
   10083 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
   10084 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
   10085 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
   10086 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
   10087 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
   10088 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
   10089 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
   10090 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
   10091 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
   10092 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
   10093 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
   10094 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
   10095 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
   10096 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
   10097 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
   10098 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
   10099 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
   10100 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
   10101 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
   10102 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
   10103 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
   10104 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
   10105 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
   10106 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
   10107 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
   10108 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
   10109 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
   10110 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
   10111 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
   10112 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
   10113 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
   10114 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
   10115 
   10116 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
   10117 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
   10118 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
   10119 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
   10120 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
   10121 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
   10122 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
   10123 
   10124 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
   10125 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
   10126 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
   10127 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
   10128 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
   10129 
   10130 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
   10131 
   10132 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   10133 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
   10134 #else
   10135 # define sqlite3ViewGetColumnNames(A,B) 0
   10136 #endif
   10137 
   10138 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
   10139 SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
   10140 #ifndef SQLITE_OMIT_AUTOINCREMENT
   10141 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
   10142 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
   10143 #else
   10144 # define sqlite3AutoincrementBegin(X)
   10145 # define sqlite3AutoincrementEnd(X)
   10146 #endif
   10147 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
   10148 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
   10149 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
   10150 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
   10151 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
   10152 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
   10153 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
   10154                                       Token*, Select*, Expr*, IdList*);
   10155 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
   10156 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
   10157 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
   10158 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
   10159 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
   10160 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
   10161 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
   10162                         Token*, int, int);
   10163 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
   10164 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
   10165 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
   10166                          Expr*,ExprList*,int,Expr*,Expr*);
   10167 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
   10168 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
   10169 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
   10170 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
   10171 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   10172 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
   10173 #endif
   10174 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
   10175 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
   10176 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
   10177 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
   10178 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
   10179 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
   10180 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
   10181 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
   10182 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
   10183 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
   10184 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
   10185 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
   10186 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
   10187 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
   10188 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
   10189 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
   10190 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
   10191 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
   10192 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
   10193 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
   10194 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
   10195 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
   10196 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
   10197 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
   10198 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
   10199 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
   10200 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
   10201 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
   10202 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
   10203 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
   10204 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
   10205 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
   10206 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
   10207 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
   10208 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
   10209 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
   10210 SQLITE_PRIVATE void sqlite3PrngResetState(void);
   10211 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
   10212 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
   10213 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
   10214 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
   10215 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
   10216 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
   10217 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
   10218 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
   10219 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
   10220 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
   10221 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
   10222 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
   10223 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
   10224 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
   10225 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
   10226 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
   10227 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
   10228 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
   10229 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
   10230                                      int*,int,int,int,int,int*);
   10231 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
   10232 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
   10233 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
   10234 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
   10235 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
   10236 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
   10237 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
   10238 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
   10239 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
   10240 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
   10241 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
   10242 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
   10243 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
   10244 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
   10245 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
   10246 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
   10247 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
   10248 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
   10249 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
   10250 
   10251 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   10252 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
   10253 #endif
   10254 
   10255 #ifndef SQLITE_OMIT_TRIGGER
   10256 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
   10257                            Expr*,int, int);
   10258 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
   10259 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
   10260 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
   10261 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
   10262 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
   10263 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
   10264                             int, int, int);
   10265 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
   10266   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
   10267 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
   10268 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
   10269 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
   10270                                         ExprList*,Select*,u8);
   10271 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
   10272 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
   10273 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
   10274 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
   10275 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
   10276 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
   10277 #else
   10278 # define sqlite3TriggersExist(B,C,D,E,F) 0
   10279 # define sqlite3DeleteTrigger(A,B)
   10280 # define sqlite3DropTriggerPtr(A,B)
   10281 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
   10282 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
   10283 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
   10284 # define sqlite3TriggerList(X, Y) 0
   10285 # define sqlite3ParseToplevel(p) p
   10286 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
   10287 #endif
   10288 
   10289 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
   10290 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
   10291 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
   10292 #ifndef SQLITE_OMIT_AUTHORIZATION
   10293 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
   10294 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
   10295 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
   10296 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
   10297 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
   10298 #else
   10299 # define sqlite3AuthRead(a,b,c,d)
   10300 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
   10301 # define sqlite3AuthContextPush(a,b,c)
   10302 # define sqlite3AuthContextPop(a)  ((void)(a))
   10303 #endif
   10304 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
   10305 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
   10306 SQLITE_PRIVATE int sqlite3BtreeFactory(sqlite3 *db, const char *zFilename,
   10307                        int omitJournal, int nCache, int flags, Btree **ppBtree);
   10308 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
   10309 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
   10310 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
   10311 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
   10312 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
   10313 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
   10314 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
   10315 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
   10316 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
   10317 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
   10318 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
   10319 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
   10320 
   10321 /*
   10322 ** Routines to read and write variable-length integers.  These used to
   10323 ** be defined locally, but now we use the varint routines in the util.c
   10324 ** file.  Code should use the MACRO forms below, as the Varint32 versions
   10325 ** are coded to assume the single byte case is already handled (which
   10326 ** the MACRO form does).
   10327 */
   10328 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
   10329 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
   10330 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
   10331 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
   10332 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
   10333 
   10334 /*
   10335 ** The header of a record consists of a sequence variable-length integers.
   10336 ** These integers are almost always small and are encoded as a single byte.
   10337 ** The following macros take advantage this fact to provide a fast encode
   10338 ** and decode of the integers in a record header.  It is faster for the common
   10339 ** case where the integer is a single byte.  It is a little slower when the
   10340 ** integer is two or more bytes.  But overall it is faster.
   10341 **
   10342 ** The following expressions are equivalent:
   10343 **
   10344 **     x = sqlite3GetVarint32( A, &B );
   10345 **     x = sqlite3PutVarint32( A, B );
   10346 **
   10347 **     x = getVarint32( A, B );
   10348 **     x = putVarint32( A, B );
   10349 **
   10350 */
   10351 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
   10352 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
   10353 #define getVarint    sqlite3GetVarint
   10354 #define putVarint    sqlite3PutVarint
   10355 
   10356 
   10357 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
   10358 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
   10359 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
   10360 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
   10361 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
   10362 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
   10363 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
   10364 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
   10365 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
   10366 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
   10367 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
   10368 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
   10369 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
   10370 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
   10371 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
   10372 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
   10373 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
   10374 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
   10375 
   10376 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
   10377 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
   10378 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
   10379                         void(*)(void*));
   10380 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
   10381 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
   10382 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
   10383 #ifdef SQLITE_ENABLE_STAT2
   10384 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
   10385 #endif
   10386 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
   10387 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
   10388 #ifndef SQLITE_AMALGAMATION
   10389 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
   10390 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
   10391 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
   10392 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
   10393 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
   10394 SQLITE_PRIVATE int sqlite3PendingByte;
   10395 #endif
   10396 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
   10397 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
   10398 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
   10399 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
   10400 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
   10401 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
   10402 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
   10403 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
   10404 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
   10405 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
   10406 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
   10407 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
   10408 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
   10409 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
   10410 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
   10411 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
   10412 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
   10413 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
   10414 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
   10415 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
   10416 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
   10417 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
   10418 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index*);
   10419 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
   10420 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
   10421 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
   10422 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
   10423 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
   10424 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
   10425 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
   10426 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
   10427 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
   10428   void (*)(sqlite3_context*,int,sqlite3_value **),
   10429   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
   10430 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
   10431 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
   10432 
   10433 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
   10434 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
   10435 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
   10436 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
   10437 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
   10438 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
   10439 
   10440 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
   10441 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
   10442 
   10443 /*
   10444 ** The interface to the LEMON-generated parser
   10445 */
   10446 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
   10447 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
   10448 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
   10449 #ifdef YYTRACKMAXSTACKDEPTH
   10450 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
   10451 #endif
   10452 
   10453 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
   10454 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   10455 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
   10456 #else
   10457 # define sqlite3CloseExtensions(X)
   10458 #endif
   10459 
   10460 #ifndef SQLITE_OMIT_SHARED_CACHE
   10461 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
   10462 #else
   10463   #define sqlite3TableLock(v,w,x,y,z)
   10464 #endif
   10465 
   10466 #ifdef SQLITE_TEST
   10467 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
   10468 #endif
   10469 
   10470 #ifdef SQLITE_OMIT_VIRTUALTABLE
   10471 #  define sqlite3VtabClear(Y)
   10472 #  define sqlite3VtabSync(X,Y) SQLITE_OK
   10473 #  define sqlite3VtabRollback(X)
   10474 #  define sqlite3VtabCommit(X)
   10475 #  define sqlite3VtabInSync(db) 0
   10476 #  define sqlite3VtabLock(X)
   10477 #  define sqlite3VtabUnlock(X)
   10478 #  define sqlite3VtabUnlockList(X)
   10479 #else
   10480 SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
   10481 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
   10482 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
   10483 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
   10484 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
   10485 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
   10486 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
   10487 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
   10488 #endif
   10489 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
   10490 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
   10491 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
   10492 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
   10493 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
   10494 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
   10495 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
   10496 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
   10497 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
   10498 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
   10499 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
   10500 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
   10501 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
   10502 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
   10503 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
   10504 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
   10505 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
   10506 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
   10507 
   10508 /* Declarations for functions in fkey.c. All of these are replaced by
   10509 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
   10510 ** key functionality is available. If OMIT_TRIGGER is defined but
   10511 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
   10512 ** this case foreign keys are parsed, but no other functionality is
   10513 ** provided (enforcement of FK constraints requires the triggers sub-system).
   10514 */
   10515 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   10516 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
   10517 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
   10518 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
   10519 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
   10520 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
   10521 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
   10522 #else
   10523   #define sqlite3FkActions(a,b,c,d)
   10524   #define sqlite3FkCheck(a,b,c,d)
   10525   #define sqlite3FkDropTable(a,b,c)
   10526   #define sqlite3FkOldmask(a,b)      0
   10527   #define sqlite3FkRequired(a,b,c,d) 0
   10528 #endif
   10529 #ifndef SQLITE_OMIT_FOREIGN_KEY
   10530 SQLITE_PRIVATE   void sqlite3FkDelete(Table*);
   10531 #else
   10532   #define sqlite3FkDelete(a)
   10533 #endif
   10534 
   10535 
   10536 /*
   10537 ** Available fault injectors.  Should be numbered beginning with 0.
   10538 */
   10539 #define SQLITE_FAULTINJECTOR_MALLOC     0
   10540 #define SQLITE_FAULTINJECTOR_COUNT      1
   10541 
   10542 /*
   10543 ** The interface to the code in fault.c used for identifying "benign"
   10544 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
   10545 ** is not defined.
   10546 */
   10547 #ifndef SQLITE_OMIT_BUILTIN_TEST
   10548 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
   10549 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
   10550 #else
   10551   #define sqlite3BeginBenignMalloc()
   10552   #define sqlite3EndBenignMalloc()
   10553 #endif
   10554 
   10555 #define IN_INDEX_ROWID           1
   10556 #define IN_INDEX_EPH             2
   10557 #define IN_INDEX_INDEX           3
   10558 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
   10559 
   10560 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   10561 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
   10562 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
   10563 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
   10564 #else
   10565   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
   10566 #endif
   10567 
   10568 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
   10569 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
   10570 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
   10571 
   10572 #if SQLITE_MAX_EXPR_DEPTH>0
   10573 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
   10574 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
   10575 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
   10576 #else
   10577   #define sqlite3ExprSetHeight(x,y)
   10578   #define sqlite3SelectExprHeight(x) 0
   10579   #define sqlite3ExprCheckHeight(x,y)
   10580 #endif
   10581 
   10582 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
   10583 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
   10584 
   10585 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   10586 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
   10587 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
   10588 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
   10589 #else
   10590   #define sqlite3ConnectionBlocked(x,y)
   10591   #define sqlite3ConnectionUnlocked(x)
   10592   #define sqlite3ConnectionClosed(x)
   10593 #endif
   10594 
   10595 #ifdef SQLITE_DEBUG
   10596 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
   10597 #endif
   10598 
   10599 /*
   10600 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
   10601 ** sqlite3IoTrace is a pointer to a printf-like routine used to
   10602 ** print I/O tracing messages.
   10603 */
   10604 #ifdef SQLITE_ENABLE_IOTRACE
   10605 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
   10606 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
   10607 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
   10608 #else
   10609 # define IOTRACE(A)
   10610 # define sqlite3VdbeIOTraceSql(X)
   10611 #endif
   10612 
   10613 #endif
   10614 
   10615 /************** End of sqliteInt.h *******************************************/
   10616 /************** Begin file global.c ******************************************/
   10617 /*
   10618 ** 2008 June 13
   10619 **
   10620 ** The author disclaims copyright to this source code.  In place of
   10621 ** a legal notice, here is a blessing:
   10622 **
   10623 **    May you do good and not evil.
   10624 **    May you find forgiveness for yourself and forgive others.
   10625 **    May you share freely, never taking more than you give.
   10626 **
   10627 *************************************************************************
   10628 **
   10629 ** This file contains definitions of global variables and contants.
   10630 */
   10631 
   10632 /* An array to map all upper-case characters into their corresponding
   10633 ** lower-case character.
   10634 **
   10635 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
   10636 ** handle case conversions for the UTF character set since the tables
   10637 ** involved are nearly as big or bigger than SQLite itself.
   10638 */
   10639 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
   10640 #ifdef SQLITE_ASCII
   10641       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
   10642      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
   10643      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
   10644      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
   10645     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
   10646     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
   10647     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
   10648     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
   10649     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
   10650     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
   10651     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
   10652     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
   10653     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
   10654     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
   10655     252,253,254,255
   10656 #endif
   10657 #ifdef SQLITE_EBCDIC
   10658       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
   10659      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
   10660      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
   10661      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
   10662      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
   10663      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
   10664      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
   10665     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
   10666     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
   10667     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
   10668     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
   10669     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
   10670     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
   10671     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
   10672     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
   10673     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
   10674 #endif
   10675 };
   10676 
   10677 /*
   10678 ** The following 256 byte lookup table is used to support SQLites built-in
   10679 ** equivalents to the following standard library functions:
   10680 **
   10681 **   isspace()                        0x01
   10682 **   isalpha()                        0x02
   10683 **   isdigit()                        0x04
   10684 **   isalnum()                        0x06
   10685 **   isxdigit()                       0x08
   10686 **   toupper()                        0x20
   10687 **   SQLite identifier character      0x40
   10688 **
   10689 ** Bit 0x20 is set if the mapped character requires translation to upper
   10690 ** case. i.e. if the character is a lower-case ASCII character.
   10691 ** If x is a lower-case ASCII character, then its upper-case equivalent
   10692 ** is (x - 0x20). Therefore toupper() can be implemented as:
   10693 **
   10694 **   (x & ~(map[x]&0x20))
   10695 **
   10696 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
   10697 ** array. tolower() is used more often than toupper() by SQLite.
   10698 **
   10699 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
   10700 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
   10701 ** non-ASCII UTF character. Hence the test for whether or not a character is
   10702 ** part of an identifier is 0x46.
   10703 **
   10704 ** SQLite's versions are identical to the standard versions assuming a
   10705 ** locale of "C". They are implemented as macros in sqliteInt.h.
   10706 */
   10707 #ifdef SQLITE_ASCII
   10708 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
   10709   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
   10710   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
   10711   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
   10712   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
   10713   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
   10714   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
   10715   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
   10716   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
   10717 
   10718   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
   10719   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
   10720   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
   10721   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
   10722   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
   10723   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
   10724   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
   10725   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
   10726 
   10727   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
   10728   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
   10729   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
   10730   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
   10731   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
   10732   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
   10733   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
   10734   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
   10735 
   10736   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
   10737   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
   10738   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
   10739   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
   10740   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
   10741   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
   10742   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
   10743   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
   10744 };
   10745 #endif
   10746 
   10747 
   10748 
   10749 /*
   10750 ** The following singleton contains the global configuration for
   10751 ** the SQLite library.
   10752 */
   10753 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
   10754    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
   10755    1,                         /* bCoreMutex */
   10756    SQLITE_THREADSAFE==1,      /* bFullMutex */
   10757    0x7ffffffe,                /* mxStrlen */
   10758    100,                       /* szLookaside */
   10759    500,                       /* nLookaside */
   10760    {0,0,0,0,0,0,0,0},         /* m */
   10761    {0,0,0,0,0,0,0,0,0},       /* mutex */
   10762    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
   10763    (void*)0,                  /* pHeap */
   10764    0,                         /* nHeap */
   10765    0, 0,                      /* mnHeap, mxHeap */
   10766    (void*)0,                  /* pScratch */
   10767    0,                         /* szScratch */
   10768    0,                         /* nScratch */
   10769    (void*)0,                  /* pPage */
   10770    0,                         /* szPage */
   10771    0,                         /* nPage */
   10772    0,                         /* mxParserStack */
   10773    0,                         /* sharedCacheEnabled */
   10774    /* All the rest should always be initialized to zero */
   10775    0,                         /* isInit */
   10776    0,                         /* inProgress */
   10777    0,                         /* isMutexInit */
   10778    0,                         /* isMallocInit */
   10779    0,                         /* isPCacheInit */
   10780    0,                         /* pInitMutex */
   10781    0,                         /* nRefInitMutex */
   10782    0,                         /* xLog */
   10783    0,                         /* pLogArg */
   10784 };
   10785 
   10786 
   10787 /*
   10788 ** Hash table for global functions - functions common to all
   10789 ** database connections.  After initialization, this table is
   10790 ** read-only.
   10791 */
   10792 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
   10793 
   10794 /*
   10795 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
   10796 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
   10797 ** the database page that contains the pending byte.  It never attempts
   10798 ** to read or write that page.  The pending byte page is set assign
   10799 ** for use by the VFS layers as space for managing file locks.
   10800 **
   10801 ** During testing, it is often desirable to move the pending byte to
   10802 ** a different position in the file.  This allows code that has to
   10803 ** deal with the pending byte to run on files that are much smaller
   10804 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
   10805 ** move the pending byte.
   10806 **
   10807 ** IMPORTANT:  Changing the pending byte to any value other than
   10808 ** 0x40000000 results in an incompatible database file format!
   10809 ** Changing the pending byte during operating results in undefined
   10810 ** and dileterious behavior.
   10811 */
   10812 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
   10813 
   10814 /*
   10815 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
   10816 ** created by mkopcodeh.awk during compilation.  Data is obtained
   10817 ** from the comments following the "case OP_xxxx:" statements in
   10818 ** the vdbe.c file.
   10819 */
   10820 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
   10821 
   10822 /************** End of global.c **********************************************/
   10823 /************** Begin file status.c ******************************************/
   10824 /*
   10825 ** 2008 June 18
   10826 **
   10827 ** The author disclaims copyright to this source code.  In place of
   10828 ** a legal notice, here is a blessing:
   10829 **
   10830 **    May you do good and not evil.
   10831 **    May you find forgiveness for yourself and forgive others.
   10832 **    May you share freely, never taking more than you give.
   10833 **
   10834 *************************************************************************
   10835 **
   10836 ** This module implements the sqlite3_status() interface and related
   10837 ** functionality.
   10838 */
   10839 
   10840 /*
   10841 ** Variables in which to record status information.
   10842 */
   10843 typedef struct sqlite3StatType sqlite3StatType;
   10844 static SQLITE_WSD struct sqlite3StatType {
   10845   int nowValue[9];         /* Current value */
   10846   int mxValue[9];          /* Maximum value */
   10847 } sqlite3Stat = { {0,}, {0,} };
   10848 
   10849 
   10850 /* The "wsdStat" macro will resolve to the status information
   10851 ** state vector.  If writable static data is unsupported on the target,
   10852 ** we have to locate the state vector at run-time.  In the more common
   10853 ** case where writable static data is supported, wsdStat can refer directly
   10854 ** to the "sqlite3Stat" state vector declared above.
   10855 */
   10856 #ifdef SQLITE_OMIT_WSD
   10857 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
   10858 # define wsdStat x[0]
   10859 #else
   10860 # define wsdStatInit
   10861 # define wsdStat sqlite3Stat
   10862 #endif
   10863 
   10864 /*
   10865 ** Return the current value of a status parameter.
   10866 */
   10867 SQLITE_PRIVATE int sqlite3StatusValue(int op){
   10868   wsdStatInit;
   10869   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   10870   return wsdStat.nowValue[op];
   10871 }
   10872 
   10873 /*
   10874 ** Add N to the value of a status record.  It is assumed that the
   10875 ** caller holds appropriate locks.
   10876 */
   10877 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
   10878   wsdStatInit;
   10879   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   10880   wsdStat.nowValue[op] += N;
   10881   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
   10882     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   10883   }
   10884 }
   10885 
   10886 /*
   10887 ** Set the value of a status to X.
   10888 */
   10889 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
   10890   wsdStatInit;
   10891   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   10892   wsdStat.nowValue[op] = X;
   10893   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
   10894     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   10895   }
   10896 }
   10897 
   10898 /*
   10899 ** Query status information.
   10900 **
   10901 ** This implementation assumes that reading or writing an aligned
   10902 ** 32-bit integer is an atomic operation.  If that assumption is not true,
   10903 ** then this routine is not threadsafe.
   10904 */
   10905 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
   10906   wsdStatInit;
   10907   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
   10908     return SQLITE_MISUSE_BKPT;
   10909   }
   10910   *pCurrent = wsdStat.nowValue[op];
   10911   *pHighwater = wsdStat.mxValue[op];
   10912   if( resetFlag ){
   10913     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   10914   }
   10915   return SQLITE_OK;
   10916 }
   10917 
   10918 /*
   10919 ** Query status information for a single database connection
   10920 */
   10921 SQLITE_API int sqlite3_db_status(
   10922   sqlite3 *db,          /* The database connection whose status is desired */
   10923   int op,               /* Status verb */
   10924   int *pCurrent,        /* Write current value here */
   10925   int *pHighwater,      /* Write high-water mark here */
   10926   int resetFlag         /* Reset high-water mark if true */
   10927 ){
   10928   switch( op ){
   10929     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
   10930       *pCurrent = db->lookaside.nOut;
   10931       *pHighwater = db->lookaside.mxOut;
   10932       if( resetFlag ){
   10933         db->lookaside.mxOut = db->lookaside.nOut;
   10934       }
   10935       break;
   10936     }
   10937     default: {
   10938       return SQLITE_ERROR;
   10939     }
   10940   }
   10941   return SQLITE_OK;
   10942 }
   10943 
   10944 /************** End of status.c **********************************************/
   10945 /************** Begin file date.c ********************************************/
   10946 /*
   10947 ** 2003 October 31
   10948 **
   10949 ** The author disclaims copyright to this source code.  In place of
   10950 ** a legal notice, here is a blessing:
   10951 **
   10952 **    May you do good and not evil.
   10953 **    May you find forgiveness for yourself and forgive others.
   10954 **    May you share freely, never taking more than you give.
   10955 **
   10956 *************************************************************************
   10957 ** This file contains the C functions that implement date and time
   10958 ** functions for SQLite.
   10959 **
   10960 ** There is only one exported symbol in this file - the function
   10961 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
   10962 ** All other code has file scope.
   10963 **
   10964 ** SQLite processes all times and dates as Julian Day numbers.  The
   10965 ** dates and times are stored as the number of days since noon
   10966 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
   10967 ** calendar system.
   10968 **
   10969 ** 1970-01-01 00:00:00 is JD 2440587.5
   10970 ** 2000-01-01 00:00:00 is JD 2451544.5
   10971 **
   10972 ** This implemention requires years to be expressed as a 4-digit number
   10973 ** which means that only dates between 0000-01-01 and 9999-12-31 can
   10974 ** be represented, even though julian day numbers allow a much wider
   10975 ** range of dates.
   10976 **
   10977 ** The Gregorian calendar system is used for all dates and times,
   10978 ** even those that predate the Gregorian calendar.  Historians usually
   10979 ** use the Julian calendar for dates prior to 1582-10-15 and for some
   10980 ** dates afterwards, depending on locale.  Beware of this difference.
   10981 **
   10982 ** The conversion algorithms are implemented based on descriptions
   10983 ** in the following text:
   10984 **
   10985 **      Jean Meeus
   10986 **      Astronomical Algorithms, 2nd Edition, 1998
   10987 **      ISBM 0-943396-61-1
   10988 **      Willmann-Bell, Inc
   10989 **      Richmond, Virginia (USA)
   10990 */
   10991 #include <time.h>
   10992 
   10993 #ifndef SQLITE_OMIT_DATETIME_FUNCS
   10994 
   10995 /*
   10996 ** On recent Windows platforms, the localtime_s() function is available
   10997 ** as part of the "Secure CRT". It is essentially equivalent to
   10998 ** localtime_r() available under most POSIX platforms, except that the
   10999 ** order of the parameters is reversed.
   11000 **
   11001 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
   11002 **
   11003 ** If the user has not indicated to use localtime_r() or localtime_s()
   11004 ** already, check for an MSVC build environment that provides
   11005 ** localtime_s().
   11006 */
   11007 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
   11008      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
   11009 #define HAVE_LOCALTIME_S 1
   11010 #endif
   11011 
   11012 /*
   11013 ** A structure for holding a single date and time.
   11014 */
   11015 typedef struct DateTime DateTime;
   11016 struct DateTime {
   11017   sqlite3_int64 iJD; /* The julian day number times 86400000 */
   11018   int Y, M, D;       /* Year, month, and day */
   11019   int h, m;          /* Hour and minutes */
   11020   int tz;            /* Timezone offset in minutes */
   11021   double s;          /* Seconds */
   11022   char validYMD;     /* True (1) if Y,M,D are valid */
   11023   char validHMS;     /* True (1) if h,m,s are valid */
   11024   char validJD;      /* True (1) if iJD is valid */
   11025   char validTZ;      /* True (1) if tz is valid */
   11026 };
   11027 
   11028 
   11029 /*
   11030 ** Convert zDate into one or more integers.  Additional arguments
   11031 ** come in groups of 5 as follows:
   11032 **
   11033 **       N       number of digits in the integer
   11034 **       min     minimum allowed value of the integer
   11035 **       max     maximum allowed value of the integer
   11036 **       nextC   first character after the integer
   11037 **       pVal    where to write the integers value.
   11038 **
   11039 ** Conversions continue until one with nextC==0 is encountered.
   11040 ** The function returns the number of successful conversions.
   11041 */
   11042 static int getDigits(const char *zDate, ...){
   11043   va_list ap;
   11044   int val;
   11045   int N;
   11046   int min;
   11047   int max;
   11048   int nextC;
   11049   int *pVal;
   11050   int cnt = 0;
   11051   va_start(ap, zDate);
   11052   do{
   11053     N = va_arg(ap, int);
   11054     min = va_arg(ap, int);
   11055     max = va_arg(ap, int);
   11056     nextC = va_arg(ap, int);
   11057     pVal = va_arg(ap, int*);
   11058     val = 0;
   11059     while( N-- ){
   11060       if( !sqlite3Isdigit(*zDate) ){
   11061         goto end_getDigits;
   11062       }
   11063       val = val*10 + *zDate - '0';
   11064       zDate++;
   11065     }
   11066     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
   11067       goto end_getDigits;
   11068     }
   11069     *pVal = val;
   11070     zDate++;
   11071     cnt++;
   11072   }while( nextC );
   11073 end_getDigits:
   11074   va_end(ap);
   11075   return cnt;
   11076 }
   11077 
   11078 /*
   11079 ** Read text from z[] and convert into a floating point number.  Return
   11080 ** the number of digits converted.
   11081 */
   11082 #define getValue sqlite3AtoF
   11083 
   11084 /*
   11085 ** Parse a timezone extension on the end of a date-time.
   11086 ** The extension is of the form:
   11087 **
   11088 **        (+/-)HH:MM
   11089 **
   11090 ** Or the "zulu" notation:
   11091 **
   11092 **        Z
   11093 **
   11094 ** If the parse is successful, write the number of minutes
   11095 ** of change in p->tz and return 0.  If a parser error occurs,
   11096 ** return non-zero.
   11097 **
   11098 ** A missing specifier is not considered an error.
   11099 */
   11100 static int parseTimezone(const char *zDate, DateTime *p){
   11101   int sgn = 0;
   11102   int nHr, nMn;
   11103   int c;
   11104   while( sqlite3Isspace(*zDate) ){ zDate++; }
   11105   p->tz = 0;
   11106   c = *zDate;
   11107   if( c=='-' ){
   11108     sgn = -1;
   11109   }else if( c=='+' ){
   11110     sgn = +1;
   11111   }else if( c=='Z' || c=='z' ){
   11112     zDate++;
   11113     goto zulu_time;
   11114   }else{
   11115     return c!=0;
   11116   }
   11117   zDate++;
   11118   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
   11119     return 1;
   11120   }
   11121   zDate += 5;
   11122   p->tz = sgn*(nMn + nHr*60);
   11123 zulu_time:
   11124   while( sqlite3Isspace(*zDate) ){ zDate++; }
   11125   return *zDate!=0;
   11126 }
   11127 
   11128 /*
   11129 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
   11130 ** The HH, MM, and SS must each be exactly 2 digits.  The
   11131 ** fractional seconds FFFF can be one or more digits.
   11132 **
   11133 ** Return 1 if there is a parsing error and 0 on success.
   11134 */
   11135 static int parseHhMmSs(const char *zDate, DateTime *p){
   11136   int h, m, s;
   11137   double ms = 0.0;
   11138   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
   11139     return 1;
   11140   }
   11141   zDate += 5;
   11142   if( *zDate==':' ){
   11143     zDate++;
   11144     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
   11145       return 1;
   11146     }
   11147     zDate += 2;
   11148     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
   11149       double rScale = 1.0;
   11150       zDate++;
   11151       while( sqlite3Isdigit(*zDate) ){
   11152         ms = ms*10.0 + *zDate - '0';
   11153         rScale *= 10.0;
   11154         zDate++;
   11155       }
   11156       ms /= rScale;
   11157     }
   11158   }else{
   11159     s = 0;
   11160   }
   11161   p->validJD = 0;
   11162   p->validHMS = 1;
   11163   p->h = h;
   11164   p->m = m;
   11165   p->s = s + ms;
   11166   if( parseTimezone(zDate, p) ) return 1;
   11167   p->validTZ = (p->tz!=0)?1:0;
   11168   return 0;
   11169 }
   11170 
   11171 /*
   11172 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
   11173 ** that the YYYY-MM-DD is according to the Gregorian calendar.
   11174 **
   11175 ** Reference:  Meeus page 61
   11176 */
   11177 static void computeJD(DateTime *p){
   11178   int Y, M, D, A, B, X1, X2;
   11179 
   11180   if( p->validJD ) return;
   11181   if( p->validYMD ){
   11182     Y = p->Y;
   11183     M = p->M;
   11184     D = p->D;
   11185   }else{
   11186     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
   11187     M = 1;
   11188     D = 1;
   11189   }
   11190   if( M<=2 ){
   11191     Y--;
   11192     M += 12;
   11193   }
   11194   A = Y/100;
   11195   B = 2 - A + (A/4);
   11196   X1 = 36525*(Y+4716)/100;
   11197   X2 = 306001*(M+1)/10000;
   11198   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
   11199   p->validJD = 1;
   11200   if( p->validHMS ){
   11201     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
   11202     if( p->validTZ ){
   11203       p->iJD -= p->tz*60000;
   11204       p->validYMD = 0;
   11205       p->validHMS = 0;
   11206       p->validTZ = 0;
   11207     }
   11208   }
   11209 }
   11210 
   11211 /*
   11212 ** Parse dates of the form
   11213 **
   11214 **     YYYY-MM-DD HH:MM:SS.FFF
   11215 **     YYYY-MM-DD HH:MM:SS
   11216 **     YYYY-MM-DD HH:MM
   11217 **     YYYY-MM-DD
   11218 **
   11219 ** Write the result into the DateTime structure and return 0
   11220 ** on success and 1 if the input string is not a well-formed
   11221 ** date.
   11222 */
   11223 static int parseYyyyMmDd(const char *zDate, DateTime *p){
   11224   int Y, M, D, neg;
   11225 
   11226   if( zDate[0]=='-' ){
   11227     zDate++;
   11228     neg = 1;
   11229   }else{
   11230     neg = 0;
   11231   }
   11232   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
   11233     return 1;
   11234   }
   11235   zDate += 10;
   11236   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
   11237   if( parseHhMmSs(zDate, p)==0 ){
   11238     /* We got the time */
   11239   }else if( *zDate==0 ){
   11240     p->validHMS = 0;
   11241   }else{
   11242     return 1;
   11243   }
   11244   p->validJD = 0;
   11245   p->validYMD = 1;
   11246   p->Y = neg ? -Y : Y;
   11247   p->M = M;
   11248   p->D = D;
   11249   if( p->validTZ ){
   11250     computeJD(p);
   11251   }
   11252   return 0;
   11253 }
   11254 
   11255 /*
   11256 ** Set the time to the current time reported by the VFS
   11257 */
   11258 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
   11259   double r;
   11260   sqlite3 *db = sqlite3_context_db_handle(context);
   11261   sqlite3OsCurrentTime(db->pVfs, &r);
   11262   p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
   11263   p->validJD = 1;
   11264 }
   11265 
   11266 /*
   11267 ** Attempt to parse the given string into a Julian Day Number.  Return
   11268 ** the number of errors.
   11269 **
   11270 ** The following are acceptable forms for the input string:
   11271 **
   11272 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
   11273 **      DDDD.DD
   11274 **      now
   11275 **
   11276 ** In the first form, the +/-HH:MM is always optional.  The fractional
   11277 ** seconds extension (the ".FFF") is optional.  The seconds portion
   11278 ** (":SS.FFF") is option.  The year and date can be omitted as long
   11279 ** as there is a time string.  The time string can be omitted as long
   11280 ** as there is a year and date.
   11281 */
   11282 static int parseDateOrTime(
   11283   sqlite3_context *context,
   11284   const char *zDate,
   11285   DateTime *p
   11286 ){
   11287   int isRealNum;    /* Return from sqlite3IsNumber().  Not used */
   11288   if( parseYyyyMmDd(zDate,p)==0 ){
   11289     return 0;
   11290   }else if( parseHhMmSs(zDate, p)==0 ){
   11291     return 0;
   11292   }else if( sqlite3StrICmp(zDate,"now")==0){
   11293     setDateTimeToCurrent(context, p);
   11294     return 0;
   11295   }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
   11296     double r;
   11297     getValue(zDate, &r);
   11298     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
   11299     p->validJD = 1;
   11300     return 0;
   11301   }
   11302   return 1;
   11303 }
   11304 
   11305 /*
   11306 ** Compute the Year, Month, and Day from the julian day number.
   11307 */
   11308 static void computeYMD(DateTime *p){
   11309   int Z, A, B, C, D, E, X1;
   11310   if( p->validYMD ) return;
   11311   if( !p->validJD ){
   11312     p->Y = 2000;
   11313     p->M = 1;
   11314     p->D = 1;
   11315   }else{
   11316     Z = (int)((p->iJD + 43200000)/86400000);
   11317     A = (int)((Z - 1867216.25)/36524.25);
   11318     A = Z + 1 + A - (A/4);
   11319     B = A + 1524;
   11320     C = (int)((B - 122.1)/365.25);
   11321     D = (36525*C)/100;
   11322     E = (int)((B-D)/30.6001);
   11323     X1 = (int)(30.6001*E);
   11324     p->D = B - D - X1;
   11325     p->M = E<14 ? E-1 : E-13;
   11326     p->Y = p->M>2 ? C - 4716 : C - 4715;
   11327   }
   11328   p->validYMD = 1;
   11329 }
   11330 
   11331 /*
   11332 ** Compute the Hour, Minute, and Seconds from the julian day number.
   11333 */
   11334 static void computeHMS(DateTime *p){
   11335   int s;
   11336   if( p->validHMS ) return;
   11337   computeJD(p);
   11338   s = (int)((p->iJD + 43200000) % 86400000);
   11339   p->s = s/1000.0;
   11340   s = (int)p->s;
   11341   p->s -= s;
   11342   p->h = s/3600;
   11343   s -= p->h*3600;
   11344   p->m = s/60;
   11345   p->s += s - p->m*60;
   11346   p->validHMS = 1;
   11347 }
   11348 
   11349 /*
   11350 ** Compute both YMD and HMS
   11351 */
   11352 static void computeYMD_HMS(DateTime *p){
   11353   computeYMD(p);
   11354   computeHMS(p);
   11355 }
   11356 
   11357 /*
   11358 ** Clear the YMD and HMS and the TZ
   11359 */
   11360 static void clearYMD_HMS_TZ(DateTime *p){
   11361   p->validYMD = 0;
   11362   p->validHMS = 0;
   11363   p->validTZ = 0;
   11364 }
   11365 
   11366 #ifndef SQLITE_OMIT_LOCALTIME
   11367 /*
   11368 ** Compute the difference (in milliseconds)
   11369 ** between localtime and UTC (a.k.a. GMT)
   11370 ** for the time value p where p is in UTC.
   11371 */
   11372 static sqlite3_int64 localtimeOffset(DateTime *p){
   11373   DateTime x, y;
   11374   time_t t;
   11375   x = *p;
   11376   computeYMD_HMS(&x);
   11377   if( x.Y<1971 || x.Y>=2038 ){
   11378     x.Y = 2000;
   11379     x.M = 1;
   11380     x.D = 1;
   11381     x.h = 0;
   11382     x.m = 0;
   11383     x.s = 0.0;
   11384   } else {
   11385     int s = (int)(x.s + 0.5);
   11386     x.s = s;
   11387   }
   11388   x.tz = 0;
   11389   x.validJD = 0;
   11390   computeJD(&x);
   11391   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
   11392 #ifdef HAVE_LOCALTIME_R
   11393   {
   11394     struct tm sLocal;
   11395     localtime_r(&t, &sLocal);
   11396     y.Y = sLocal.tm_year + 1900;
   11397     y.M = sLocal.tm_mon + 1;
   11398     y.D = sLocal.tm_mday;
   11399     y.h = sLocal.tm_hour;
   11400     y.m = sLocal.tm_min;
   11401     y.s = sLocal.tm_sec;
   11402   }
   11403 #elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
   11404   {
   11405     struct tm sLocal;
   11406     localtime_s(&sLocal, &t);
   11407     y.Y = sLocal.tm_year + 1900;
   11408     y.M = sLocal.tm_mon + 1;
   11409     y.D = sLocal.tm_mday;
   11410     y.h = sLocal.tm_hour;
   11411     y.m = sLocal.tm_min;
   11412     y.s = sLocal.tm_sec;
   11413   }
   11414 #else
   11415   {
   11416     struct tm *pTm;
   11417     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   11418     pTm = localtime(&t);
   11419     y.Y = pTm->tm_year + 1900;
   11420     y.M = pTm->tm_mon + 1;
   11421     y.D = pTm->tm_mday;
   11422     y.h = pTm->tm_hour;
   11423     y.m = pTm->tm_min;
   11424     y.s = pTm->tm_sec;
   11425     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   11426   }
   11427 #endif
   11428   y.validYMD = 1;
   11429   y.validHMS = 1;
   11430   y.validJD = 0;
   11431   y.validTZ = 0;
   11432   computeJD(&y);
   11433   return y.iJD - x.iJD;
   11434 }
   11435 #endif /* SQLITE_OMIT_LOCALTIME */
   11436 
   11437 /*
   11438 ** Process a modifier to a date-time stamp.  The modifiers are
   11439 ** as follows:
   11440 **
   11441 **     NNN days
   11442 **     NNN hours
   11443 **     NNN minutes
   11444 **     NNN.NNNN seconds
   11445 **     NNN months
   11446 **     NNN years
   11447 **     start of month
   11448 **     start of year
   11449 **     start of week
   11450 **     start of day
   11451 **     weekday N
   11452 **     unixepoch
   11453 **     localtime
   11454 **     utc
   11455 **
   11456 ** Return 0 on success and 1 if there is any kind of error.
   11457 */
   11458 static int parseModifier(const char *zMod, DateTime *p){
   11459   int rc = 1;
   11460   int n;
   11461   double r;
   11462   char *z, zBuf[30];
   11463   z = zBuf;
   11464   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
   11465     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
   11466   }
   11467   z[n] = 0;
   11468   switch( z[0] ){
   11469 #ifndef SQLITE_OMIT_LOCALTIME
   11470     case 'l': {
   11471       /*    localtime
   11472       **
   11473       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
   11474       ** show local time.
   11475       */
   11476       if( strcmp(z, "localtime")==0 ){
   11477         computeJD(p);
   11478         p->iJD += localtimeOffset(p);
   11479         clearYMD_HMS_TZ(p);
   11480         rc = 0;
   11481       }
   11482       break;
   11483     }
   11484 #endif
   11485     case 'u': {
   11486       /*
   11487       **    unixepoch
   11488       **
   11489       ** Treat the current value of p->iJD as the number of
   11490       ** seconds since 1970.  Convert to a real julian day number.
   11491       */
   11492       if( strcmp(z, "unixepoch")==0 && p->validJD ){
   11493         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
   11494         clearYMD_HMS_TZ(p);
   11495         rc = 0;
   11496       }
   11497 #ifndef SQLITE_OMIT_LOCALTIME
   11498       else if( strcmp(z, "utc")==0 ){
   11499         sqlite3_int64 c1;
   11500         computeJD(p);
   11501         c1 = localtimeOffset(p);
   11502         p->iJD -= c1;
   11503         clearYMD_HMS_TZ(p);
   11504         p->iJD += c1 - localtimeOffset(p);
   11505         rc = 0;
   11506       }
   11507 #endif
   11508       break;
   11509     }
   11510     case 'w': {
   11511       /*
   11512       **    weekday N
   11513       **
   11514       ** Move the date to the same time on the next occurrence of
   11515       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
   11516       ** date is already on the appropriate weekday, this is a no-op.
   11517       */
   11518       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
   11519                  && (n=(int)r)==r && n>=0 && r<7 ){
   11520         sqlite3_int64 Z;
   11521         computeYMD_HMS(p);
   11522         p->validTZ = 0;
   11523         p->validJD = 0;
   11524         computeJD(p);
   11525         Z = ((p->iJD + 129600000)/86400000) % 7;
   11526         if( Z>n ) Z -= 7;
   11527         p->iJD += (n - Z)*86400000;
   11528         clearYMD_HMS_TZ(p);
   11529         rc = 0;
   11530       }
   11531       break;
   11532     }
   11533     case 's': {
   11534       /*
   11535       **    start of TTTTT
   11536       **
   11537       ** Move the date backwards to the beginning of the current day,
   11538       ** or month or year.
   11539       */
   11540       if( strncmp(z, "start of ", 9)!=0 ) break;
   11541       z += 9;
   11542       computeYMD(p);
   11543       p->validHMS = 1;
   11544       p->h = p->m = 0;
   11545       p->s = 0.0;
   11546       p->validTZ = 0;
   11547       p->validJD = 0;
   11548       if( strcmp(z,"month")==0 ){
   11549         p->D = 1;
   11550         rc = 0;
   11551       }else if( strcmp(z,"year")==0 ){
   11552         computeYMD(p);
   11553         p->M = 1;
   11554         p->D = 1;
   11555         rc = 0;
   11556       }else if( strcmp(z,"day")==0 ){
   11557         rc = 0;
   11558       }
   11559       break;
   11560     }
   11561     case '+':
   11562     case '-':
   11563     case '0':
   11564     case '1':
   11565     case '2':
   11566     case '3':
   11567     case '4':
   11568     case '5':
   11569     case '6':
   11570     case '7':
   11571     case '8':
   11572     case '9': {
   11573       double rRounder;
   11574       n = getValue(z, &r);
   11575       assert( n>=1 );
   11576       if( z[n]==':' ){
   11577         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
   11578         ** specified number of hours, minutes, seconds, and fractional seconds
   11579         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
   11580         ** omitted.
   11581         */
   11582         const char *z2 = z;
   11583         DateTime tx;
   11584         sqlite3_int64 day;
   11585         if( !sqlite3Isdigit(*z2) ) z2++;
   11586         memset(&tx, 0, sizeof(tx));
   11587         if( parseHhMmSs(z2, &tx) ) break;
   11588         computeJD(&tx);
   11589         tx.iJD -= 43200000;
   11590         day = tx.iJD/86400000;
   11591         tx.iJD -= day*86400000;
   11592         if( z[0]=='-' ) tx.iJD = -tx.iJD;
   11593         computeJD(p);
   11594         clearYMD_HMS_TZ(p);
   11595         p->iJD += tx.iJD;
   11596         rc = 0;
   11597         break;
   11598       }
   11599       z += n;
   11600       while( sqlite3Isspace(*z) ) z++;
   11601       n = sqlite3Strlen30(z);
   11602       if( n>10 || n<3 ) break;
   11603       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
   11604       computeJD(p);
   11605       rc = 0;
   11606       rRounder = r<0 ? -0.5 : +0.5;
   11607       if( n==3 && strcmp(z,"day")==0 ){
   11608         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
   11609       }else if( n==4 && strcmp(z,"hour")==0 ){
   11610         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
   11611       }else if( n==6 && strcmp(z,"minute")==0 ){
   11612         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
   11613       }else if( n==6 && strcmp(z,"second")==0 ){
   11614         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
   11615       }else if( n==5 && strcmp(z,"month")==0 ){
   11616         int x, y;
   11617         computeYMD_HMS(p);
   11618         p->M += (int)r;
   11619         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
   11620         p->Y += x;
   11621         p->M -= x*12;
   11622         p->validJD = 0;
   11623         computeJD(p);
   11624         y = (int)r;
   11625         if( y!=r ){
   11626           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
   11627         }
   11628       }else if( n==4 && strcmp(z,"year")==0 ){
   11629         int y = (int)r;
   11630         computeYMD_HMS(p);
   11631         p->Y += y;
   11632         p->validJD = 0;
   11633         computeJD(p);
   11634         if( y!=r ){
   11635           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
   11636         }
   11637       }else{
   11638         rc = 1;
   11639       }
   11640       clearYMD_HMS_TZ(p);
   11641       break;
   11642     }
   11643     default: {
   11644       break;
   11645     }
   11646   }
   11647   return rc;
   11648 }
   11649 
   11650 /*
   11651 ** Process time function arguments.  argv[0] is a date-time stamp.
   11652 ** argv[1] and following are modifiers.  Parse them all and write
   11653 ** the resulting time into the DateTime structure p.  Return 0
   11654 ** on success and 1 if there are any errors.
   11655 **
   11656 ** If there are zero parameters (if even argv[0] is undefined)
   11657 ** then assume a default value of "now" for argv[0].
   11658 */
   11659 static int isDate(
   11660   sqlite3_context *context,
   11661   int argc,
   11662   sqlite3_value **argv,
   11663   DateTime *p
   11664 ){
   11665   int i;
   11666   const unsigned char *z;
   11667   int eType;
   11668   memset(p, 0, sizeof(*p));
   11669   if( argc==0 ){
   11670     setDateTimeToCurrent(context, p);
   11671   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
   11672                    || eType==SQLITE_INTEGER ){
   11673     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
   11674     p->validJD = 1;
   11675   }else{
   11676     z = sqlite3_value_text(argv[0]);
   11677     if( !z || parseDateOrTime(context, (char*)z, p) ){
   11678       return 1;
   11679     }
   11680   }
   11681   for(i=1; i<argc; i++){
   11682     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
   11683       return 1;
   11684     }
   11685   }
   11686   return 0;
   11687 }
   11688 
   11689 
   11690 /*
   11691 ** The following routines implement the various date and time functions
   11692 ** of SQLite.
   11693 */
   11694 
   11695 /*
   11696 **    julianday( TIMESTRING, MOD, MOD, ...)
   11697 **
   11698 ** Return the julian day number of the date specified in the arguments
   11699 */
   11700 static void juliandayFunc(
   11701   sqlite3_context *context,
   11702   int argc,
   11703   sqlite3_value **argv
   11704 ){
   11705   DateTime x;
   11706   if( isDate(context, argc, argv, &x)==0 ){
   11707     computeJD(&x);
   11708     sqlite3_result_double(context, x.iJD/86400000.0);
   11709   }
   11710 }
   11711 
   11712 /*
   11713 **    datetime( TIMESTRING, MOD, MOD, ...)
   11714 **
   11715 ** Return YYYY-MM-DD HH:MM:SS
   11716 */
   11717 static void datetimeFunc(
   11718   sqlite3_context *context,
   11719   int argc,
   11720   sqlite3_value **argv
   11721 ){
   11722   DateTime x;
   11723   if( isDate(context, argc, argv, &x)==0 ){
   11724     char zBuf[100];
   11725     computeYMD_HMS(&x);
   11726     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
   11727                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
   11728     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   11729   }
   11730 }
   11731 
   11732 /*
   11733 **    time( TIMESTRING, MOD, MOD, ...)
   11734 **
   11735 ** Return HH:MM:SS
   11736 */
   11737 static void timeFunc(
   11738   sqlite3_context *context,
   11739   int argc,
   11740   sqlite3_value **argv
   11741 ){
   11742   DateTime x;
   11743   if( isDate(context, argc, argv, &x)==0 ){
   11744     char zBuf[100];
   11745     computeHMS(&x);
   11746     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
   11747     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   11748   }
   11749 }
   11750 
   11751 /*
   11752 **    date( TIMESTRING, MOD, MOD, ...)
   11753 **
   11754 ** Return YYYY-MM-DD
   11755 */
   11756 static void dateFunc(
   11757   sqlite3_context *context,
   11758   int argc,
   11759   sqlite3_value **argv
   11760 ){
   11761   DateTime x;
   11762   if( isDate(context, argc, argv, &x)==0 ){
   11763     char zBuf[100];
   11764     computeYMD(&x);
   11765     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
   11766     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   11767   }
   11768 }
   11769 
   11770 /*
   11771 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
   11772 **
   11773 ** Return a string described by FORMAT.  Conversions as follows:
   11774 **
   11775 **   %d  day of month
   11776 **   %f  ** fractional seconds  SS.SSS
   11777 **   %H  hour 00-24
   11778 **   %j  day of year 000-366
   11779 **   %J  ** Julian day number
   11780 **   %m  month 01-12
   11781 **   %M  minute 00-59
   11782 **   %s  seconds since 1970-01-01
   11783 **   %S  seconds 00-59
   11784 **   %w  day of week 0-6  sunday==0
   11785 **   %W  week of year 00-53
   11786 **   %Y  year 0000-9999
   11787 **   %%  %
   11788 */
   11789 static void strftimeFunc(
   11790   sqlite3_context *context,
   11791   int argc,
   11792   sqlite3_value **argv
   11793 ){
   11794   DateTime x;
   11795   u64 n;
   11796   size_t i,j;
   11797   char *z;
   11798   sqlite3 *db;
   11799   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
   11800   char zBuf[100];
   11801   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
   11802   db = sqlite3_context_db_handle(context);
   11803   for(i=0, n=1; zFmt[i]; i++, n++){
   11804     if( zFmt[i]=='%' ){
   11805       switch( zFmt[i+1] ){
   11806         case 'd':
   11807         case 'H':
   11808         case 'm':
   11809         case 'M':
   11810         case 'S':
   11811         case 'W':
   11812           n++;
   11813           /* fall thru */
   11814         case 'w':
   11815         case '%':
   11816           break;
   11817         case 'f':
   11818           n += 8;
   11819           break;
   11820         case 'j':
   11821           n += 3;
   11822           break;
   11823         case 'Y':
   11824           n += 8;
   11825           break;
   11826         case 's':
   11827         case 'J':
   11828           n += 50;
   11829           break;
   11830         default:
   11831           return;  /* ERROR.  return a NULL */
   11832       }
   11833       i++;
   11834     }
   11835   }
   11836   testcase( n==sizeof(zBuf)-1 );
   11837   testcase( n==sizeof(zBuf) );
   11838   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   11839   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
   11840   if( n<sizeof(zBuf) ){
   11841     z = zBuf;
   11842   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   11843     sqlite3_result_error_toobig(context);
   11844     return;
   11845   }else{
   11846     z = sqlite3DbMallocRaw(db, (int)n);
   11847     if( z==0 ){
   11848       sqlite3_result_error_nomem(context);
   11849       return;
   11850     }
   11851   }
   11852   computeJD(&x);
   11853   computeYMD_HMS(&x);
   11854   for(i=j=0; zFmt[i]; i++){
   11855     if( zFmt[i]!='%' ){
   11856       z[j++] = zFmt[i];
   11857     }else{
   11858       i++;
   11859       switch( zFmt[i] ){
   11860         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
   11861         case 'f': {
   11862           double s = x.s;
   11863           if( s>59.999 ) s = 59.999;
   11864           sqlite3_snprintf(7, &z[j],"%06.3f", s);
   11865           j += sqlite3Strlen30(&z[j]);
   11866           break;
   11867         }
   11868         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
   11869         case 'W': /* Fall thru */
   11870         case 'j': {
   11871           int nDay;             /* Number of days since 1st day of year */
   11872           DateTime y = x;
   11873           y.validJD = 0;
   11874           y.M = 1;
   11875           y.D = 1;
   11876           computeJD(&y);
   11877           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
   11878           if( zFmt[i]=='W' ){
   11879             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
   11880             wd = (int)(((x.iJD+43200000)/86400000)%7);
   11881             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
   11882             j += 2;
   11883           }else{
   11884             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
   11885             j += 3;
   11886           }
   11887           break;
   11888         }
   11889         case 'J': {
   11890           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
   11891           j+=sqlite3Strlen30(&z[j]);
   11892           break;
   11893         }
   11894         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
   11895         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
   11896         case 's': {
   11897           sqlite3_snprintf(30,&z[j],"%lld",
   11898                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
   11899           j += sqlite3Strlen30(&z[j]);
   11900           break;
   11901         }
   11902         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
   11903         case 'w': {
   11904           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
   11905           break;
   11906         }
   11907         case 'Y': {
   11908           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
   11909           break;
   11910         }
   11911         default:   z[j++] = '%'; break;
   11912       }
   11913     }
   11914   }
   11915   z[j] = 0;
   11916   sqlite3_result_text(context, z, -1,
   11917                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
   11918 }
   11919 
   11920 /*
   11921 ** current_time()
   11922 **
   11923 ** This function returns the same value as time('now').
   11924 */
   11925 static void ctimeFunc(
   11926   sqlite3_context *context,
   11927   int NotUsed,
   11928   sqlite3_value **NotUsed2
   11929 ){
   11930   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   11931   timeFunc(context, 0, 0);
   11932 }
   11933 
   11934 /*
   11935 ** current_date()
   11936 **
   11937 ** This function returns the same value as date('now').
   11938 */
   11939 static void cdateFunc(
   11940   sqlite3_context *context,
   11941   int NotUsed,
   11942   sqlite3_value **NotUsed2
   11943 ){
   11944   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   11945   dateFunc(context, 0, 0);
   11946 }
   11947 
   11948 /*
   11949 ** current_timestamp()
   11950 **
   11951 ** This function returns the same value as datetime('now').
   11952 */
   11953 static void ctimestampFunc(
   11954   sqlite3_context *context,
   11955   int NotUsed,
   11956   sqlite3_value **NotUsed2
   11957 ){
   11958   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   11959   datetimeFunc(context, 0, 0);
   11960 }
   11961 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
   11962 
   11963 #ifdef SQLITE_OMIT_DATETIME_FUNCS
   11964 /*
   11965 ** If the library is compiled to omit the full-scale date and time
   11966 ** handling (to get a smaller binary), the following minimal version
   11967 ** of the functions current_time(), current_date() and current_timestamp()
   11968 ** are included instead. This is to support column declarations that
   11969 ** include "DEFAULT CURRENT_TIME" etc.
   11970 **
   11971 ** This function uses the C-library functions time(), gmtime()
   11972 ** and strftime(). The format string to pass to strftime() is supplied
   11973 ** as the user-data for the function.
   11974 */
   11975 static void currentTimeFunc(
   11976   sqlite3_context *context,
   11977   int argc,
   11978   sqlite3_value **argv
   11979 ){
   11980   time_t t;
   11981   char *zFormat = (char *)sqlite3_user_data(context);
   11982   sqlite3 *db;
   11983   double rT;
   11984   char zBuf[20];
   11985 
   11986   UNUSED_PARAMETER(argc);
   11987   UNUSED_PARAMETER(argv);
   11988 
   11989   db = sqlite3_context_db_handle(context);
   11990   sqlite3OsCurrentTime(db->pVfs, &rT);
   11991 #ifndef SQLITE_OMIT_FLOATING_POINT
   11992   t = 86400.0*(rT - 2440587.5) + 0.5;
   11993 #else
   11994   /* without floating point support, rT will have
   11995   ** already lost fractional day precision.
   11996   */
   11997   t = 86400 * (rT - 2440587) - 43200;
   11998 #endif
   11999 #ifdef HAVE_GMTIME_R
   12000   {
   12001     struct tm sNow;
   12002     gmtime_r(&t, &sNow);
   12003     strftime(zBuf, 20, zFormat, &sNow);
   12004   }
   12005 #else
   12006   {
   12007     struct tm *pTm;
   12008     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   12009     pTm = gmtime(&t);
   12010     strftime(zBuf, 20, zFormat, pTm);
   12011     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   12012   }
   12013 #endif
   12014 
   12015   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   12016 }
   12017 #endif
   12018 
   12019 /*
   12020 ** This function registered all of the above C functions as SQL
   12021 ** functions.  This should be the only routine in this file with
   12022 ** external linkage.
   12023 */
   12024 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
   12025   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
   12026 #ifndef SQLITE_OMIT_DATETIME_FUNCS
   12027     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
   12028     FUNCTION(date,             -1, 0, 0, dateFunc      ),
   12029     FUNCTION(time,             -1, 0, 0, timeFunc      ),
   12030     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
   12031     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
   12032     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
   12033     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
   12034     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
   12035 #else
   12036     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
   12037     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d",          0, currentTimeFunc),
   12038     STR_FUNCTION(current_date,      0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
   12039 #endif
   12040   };
   12041   int i;
   12042   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   12043   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
   12044 
   12045   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
   12046     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   12047   }
   12048 }
   12049 
   12050 /************** End of date.c ************************************************/
   12051 /************** Begin file os.c **********************************************/
   12052 /*
   12053 ** 2005 November 29
   12054 **
   12055 ** The author disclaims copyright to this source code.  In place of
   12056 ** a legal notice, here is a blessing:
   12057 **
   12058 **    May you do good and not evil.
   12059 **    May you find forgiveness for yourself and forgive others.
   12060 **    May you share freely, never taking more than you give.
   12061 **
   12062 ******************************************************************************
   12063 **
   12064 ** This file contains OS interface code that is common to all
   12065 ** architectures.
   12066 */
   12067 #define _SQLITE_OS_C_ 1
   12068 #undef _SQLITE_OS_C_
   12069 
   12070 /*
   12071 ** The default SQLite sqlite3_vfs implementations do not allocate
   12072 ** memory (actually, os_unix.c allocates a small amount of memory
   12073 ** from within OsOpen()), but some third-party implementations may.
   12074 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
   12075 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
   12076 **
   12077 ** The following functions are instrumented for malloc() failure
   12078 ** testing:
   12079 **
   12080 **     sqlite3OsOpen()
   12081 **     sqlite3OsRead()
   12082 **     sqlite3OsWrite()
   12083 **     sqlite3OsSync()
   12084 **     sqlite3OsLock()
   12085 **
   12086 */
   12087 #if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0)
   12088   #define DO_OS_MALLOC_TEST(x) if (!x || !sqlite3IsMemJournal(x)) {     \
   12089     void *pTstAlloc = sqlite3Malloc(10);                             \
   12090     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
   12091     sqlite3_free(pTstAlloc);                                         \
   12092   }
   12093 #else
   12094   #define DO_OS_MALLOC_TEST(x)
   12095 #endif
   12096 
   12097 /*
   12098 ** The following routines are convenience wrappers around methods
   12099 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
   12100 ** of this would be completely automatic if SQLite were coded using
   12101 ** C++ instead of plain old C.
   12102 */
   12103 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
   12104   int rc = SQLITE_OK;
   12105   if( pId->pMethods ){
   12106     rc = pId->pMethods->xClose(pId);
   12107     pId->pMethods = 0;
   12108   }
   12109   return rc;
   12110 }
   12111 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
   12112   DO_OS_MALLOC_TEST(id);
   12113   return id->pMethods->xRead(id, pBuf, amt, offset);
   12114 }
   12115 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
   12116   DO_OS_MALLOC_TEST(id);
   12117   return id->pMethods->xWrite(id, pBuf, amt, offset);
   12118 }
   12119 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
   12120   return id->pMethods->xTruncate(id, size);
   12121 }
   12122 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
   12123   DO_OS_MALLOC_TEST(id);
   12124   return id->pMethods->xSync(id, flags);
   12125 }
   12126 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
   12127   DO_OS_MALLOC_TEST(id);
   12128   return id->pMethods->xFileSize(id, pSize);
   12129 }
   12130 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
   12131   DO_OS_MALLOC_TEST(id);
   12132   return id->pMethods->xLock(id, lockType);
   12133 }
   12134 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
   12135   return id->pMethods->xUnlock(id, lockType);
   12136 }
   12137 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
   12138   DO_OS_MALLOC_TEST(id);
   12139   return id->pMethods->xCheckReservedLock(id, pResOut);
   12140 }
   12141 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
   12142   return id->pMethods->xFileControl(id, op, pArg);
   12143 }
   12144 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
   12145   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
   12146   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
   12147 }
   12148 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
   12149   return id->pMethods->xDeviceCharacteristics(id);
   12150 }
   12151 
   12152 /*
   12153 ** The next group of routines are convenience wrappers around the
   12154 ** VFS methods.
   12155 */
   12156 SQLITE_PRIVATE int sqlite3OsOpen(
   12157   sqlite3_vfs *pVfs,
   12158   const char *zPath,
   12159   sqlite3_file *pFile,
   12160   int flags,
   12161   int *pFlagsOut
   12162 ){
   12163   int rc;
   12164   DO_OS_MALLOC_TEST(0);
   12165   /* 0x7f1f is a mask of SQLITE_OPEN_ flags that are valid to be passed
   12166   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
   12167   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
   12168   ** reaching the VFS. */
   12169   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x7f1f, pFlagsOut);
   12170   assert( rc==SQLITE_OK || pFile->pMethods==0 );
   12171   return rc;
   12172 }
   12173 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
   12174   return pVfs->xDelete(pVfs, zPath, dirSync);
   12175 }
   12176 SQLITE_PRIVATE int sqlite3OsAccess(
   12177   sqlite3_vfs *pVfs,
   12178   const char *zPath,
   12179   int flags,
   12180   int *pResOut
   12181 ){
   12182   DO_OS_MALLOC_TEST(0);
   12183   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
   12184 }
   12185 SQLITE_PRIVATE int sqlite3OsFullPathname(
   12186   sqlite3_vfs *pVfs,
   12187   const char *zPath,
   12188   int nPathOut,
   12189   char *zPathOut
   12190 ){
   12191   zPathOut[0] = 0;
   12192   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
   12193 }
   12194 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   12195 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
   12196   return pVfs->xDlOpen(pVfs, zPath);
   12197 }
   12198 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
   12199   pVfs->xDlError(pVfs, nByte, zBufOut);
   12200 }
   12201 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
   12202   return pVfs->xDlSym(pVfs, pHdle, zSym);
   12203 }
   12204 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
   12205   pVfs->xDlClose(pVfs, pHandle);
   12206 }
   12207 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   12208 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
   12209   return pVfs->xRandomness(pVfs, nByte, zBufOut);
   12210 }
   12211 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
   12212   return pVfs->xSleep(pVfs, nMicro);
   12213 }
   12214 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
   12215   return pVfs->xCurrentTime(pVfs, pTimeOut);
   12216 }
   12217 
   12218 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
   12219   sqlite3_vfs *pVfs,
   12220   const char *zFile,
   12221   sqlite3_file **ppFile,
   12222   int flags,
   12223   int *pOutFlags
   12224 ){
   12225   int rc = SQLITE_NOMEM;
   12226   sqlite3_file *pFile;
   12227   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
   12228   if( pFile ){
   12229     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
   12230     if( rc!=SQLITE_OK ){
   12231       sqlite3_free(pFile);
   12232     }else{
   12233       *ppFile = pFile;
   12234     }
   12235   }
   12236   return rc;
   12237 }
   12238 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
   12239   int rc = SQLITE_OK;
   12240   assert( pFile );
   12241   rc = sqlite3OsClose(pFile);
   12242   sqlite3_free(pFile);
   12243   return rc;
   12244 }
   12245 
   12246 /*
   12247 ** This function is a wrapper around the OS specific implementation of
   12248 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
   12249 ** ability to simulate a malloc failure, so that the handling of an
   12250 ** error in sqlite3_os_init() by the upper layers can be tested.
   12251 */
   12252 SQLITE_PRIVATE int sqlite3OsInit(void){
   12253   void *p = sqlite3_malloc(10);
   12254   if( p==0 ) return SQLITE_NOMEM;
   12255   sqlite3_free(p);
   12256   return sqlite3_os_init();
   12257 }
   12258 
   12259 /*
   12260 ** The list of all registered VFS implementations.
   12261 */
   12262 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
   12263 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
   12264 
   12265 /*
   12266 ** Locate a VFS by name.  If no name is given, simply return the
   12267 ** first VFS on the list.
   12268 */
   12269 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
   12270   sqlite3_vfs *pVfs = 0;
   12271 #if SQLITE_THREADSAFE
   12272   sqlite3_mutex *mutex;
   12273 #endif
   12274 #ifndef SQLITE_OMIT_AUTOINIT
   12275   int rc = sqlite3_initialize();
   12276   if( rc ) return 0;
   12277 #endif
   12278 #if SQLITE_THREADSAFE
   12279   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   12280 #endif
   12281   sqlite3_mutex_enter(mutex);
   12282   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
   12283     if( zVfs==0 ) break;
   12284     if( strcmp(zVfs, pVfs->zName)==0 ) break;
   12285   }
   12286   sqlite3_mutex_leave(mutex);
   12287   return pVfs;
   12288 }
   12289 
   12290 /*
   12291 ** Unlink a VFS from the linked list
   12292 */
   12293 static void vfsUnlink(sqlite3_vfs *pVfs){
   12294   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
   12295   if( pVfs==0 ){
   12296     /* No-op */
   12297   }else if( vfsList==pVfs ){
   12298     vfsList = pVfs->pNext;
   12299   }else if( vfsList ){
   12300     sqlite3_vfs *p = vfsList;
   12301     while( p->pNext && p->pNext!=pVfs ){
   12302       p = p->pNext;
   12303     }
   12304     if( p->pNext==pVfs ){
   12305       p->pNext = pVfs->pNext;
   12306     }
   12307   }
   12308 }
   12309 
   12310 /*
   12311 ** Register a VFS with the system.  It is harmless to register the same
   12312 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
   12313 ** true.
   12314 */
   12315 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
   12316   sqlite3_mutex *mutex = 0;
   12317 #ifndef SQLITE_OMIT_AUTOINIT
   12318   int rc = sqlite3_initialize();
   12319   if( rc ) return rc;
   12320 #endif
   12321   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   12322   sqlite3_mutex_enter(mutex);
   12323   vfsUnlink(pVfs);
   12324   if( makeDflt || vfsList==0 ){
   12325     pVfs->pNext = vfsList;
   12326     vfsList = pVfs;
   12327   }else{
   12328     pVfs->pNext = vfsList->pNext;
   12329     vfsList->pNext = pVfs;
   12330   }
   12331   assert(vfsList);
   12332   sqlite3_mutex_leave(mutex);
   12333   return SQLITE_OK;
   12334 }
   12335 
   12336 /*
   12337 ** Unregister a VFS so that it is no longer accessible.
   12338 */
   12339 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
   12340 #if SQLITE_THREADSAFE
   12341   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   12342 #endif
   12343   sqlite3_mutex_enter(mutex);
   12344   vfsUnlink(pVfs);
   12345   sqlite3_mutex_leave(mutex);
   12346   return SQLITE_OK;
   12347 }
   12348 
   12349 /************** End of os.c **************************************************/
   12350 /************** Begin file fault.c *******************************************/
   12351 /*
   12352 ** 2008 Jan 22
   12353 **
   12354 ** The author disclaims copyright to this source code.  In place of
   12355 ** a legal notice, here is a blessing:
   12356 **
   12357 **    May you do good and not evil.
   12358 **    May you find forgiveness for yourself and forgive others.
   12359 **    May you share freely, never taking more than you give.
   12360 **
   12361 *************************************************************************
   12362 **
   12363 ** This file contains code to support the concept of "benign"
   12364 ** malloc failures (when the xMalloc() or xRealloc() method of the
   12365 ** sqlite3_mem_methods structure fails to allocate a block of memory
   12366 ** and returns 0).
   12367 **
   12368 ** Most malloc failures are non-benign. After they occur, SQLite
   12369 ** abandons the current operation and returns an error code (usually
   12370 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
   12371 ** fatal. For example, if a malloc fails while resizing a hash table, this
   12372 ** is completely recoverable simply by not carrying out the resize. The
   12373 ** hash table will continue to function normally.  So a malloc failure
   12374 ** during a hash table resize is a benign fault.
   12375 */
   12376 
   12377 
   12378 #ifndef SQLITE_OMIT_BUILTIN_TEST
   12379 
   12380 /*
   12381 ** Global variables.
   12382 */
   12383 typedef struct BenignMallocHooks BenignMallocHooks;
   12384 static SQLITE_WSD struct BenignMallocHooks {
   12385   void (*xBenignBegin)(void);
   12386   void (*xBenignEnd)(void);
   12387 } sqlite3Hooks = { 0, 0 };
   12388 
   12389 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
   12390 ** structure.  If writable static data is unsupported on the target,
   12391 ** we have to locate the state vector at run-time.  In the more common
   12392 ** case where writable static data is supported, wsdHooks can refer directly
   12393 ** to the "sqlite3Hooks" state vector declared above.
   12394 */
   12395 #ifdef SQLITE_OMIT_WSD
   12396 # define wsdHooksInit \
   12397   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
   12398 # define wsdHooks x[0]
   12399 #else
   12400 # define wsdHooksInit
   12401 # define wsdHooks sqlite3Hooks
   12402 #endif
   12403 
   12404 
   12405 /*
   12406 ** Register hooks to call when sqlite3BeginBenignMalloc() and
   12407 ** sqlite3EndBenignMalloc() are called, respectively.
   12408 */
   12409 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
   12410   void (*xBenignBegin)(void),
   12411   void (*xBenignEnd)(void)
   12412 ){
   12413   wsdHooksInit;
   12414   wsdHooks.xBenignBegin = xBenignBegin;
   12415   wsdHooks.xBenignEnd = xBenignEnd;
   12416 }
   12417 
   12418 /*
   12419 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
   12420 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
   12421 ** indicates that subsequent malloc failures are non-benign.
   12422 */
   12423 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
   12424   wsdHooksInit;
   12425   if( wsdHooks.xBenignBegin ){
   12426     wsdHooks.xBenignBegin();
   12427   }
   12428 }
   12429 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
   12430   wsdHooksInit;
   12431   if( wsdHooks.xBenignEnd ){
   12432     wsdHooks.xBenignEnd();
   12433   }
   12434 }
   12435 
   12436 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
   12437 
   12438 /************** End of fault.c ***********************************************/
   12439 /************** Begin file mem0.c ********************************************/
   12440 /*
   12441 ** 2008 October 28
   12442 **
   12443 ** The author disclaims copyright to this source code.  In place of
   12444 ** a legal notice, here is a blessing:
   12445 **
   12446 **    May you do good and not evil.
   12447 **    May you find forgiveness for yourself and forgive others.
   12448 **    May you share freely, never taking more than you give.
   12449 **
   12450 *************************************************************************
   12451 **
   12452 ** This file contains a no-op memory allocation drivers for use when
   12453 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
   12454 ** here always fail.  SQLite will not operate with these drivers.  These
   12455 ** are merely placeholders.  Real drivers must be substituted using
   12456 ** sqlite3_config() before SQLite will operate.
   12457 */
   12458 
   12459 /*
   12460 ** This version of the memory allocator is the default.  It is
   12461 ** used when no other memory allocator is specified using compile-time
   12462 ** macros.
   12463 */
   12464 #ifdef SQLITE_ZERO_MALLOC
   12465 
   12466 /*
   12467 ** No-op versions of all memory allocation routines
   12468 */
   12469 static void *sqlite3MemMalloc(int nByte){ return 0; }
   12470 static void sqlite3MemFree(void *pPrior){ return; }
   12471 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
   12472 static int sqlite3MemSize(void *pPrior){ return 0; }
   12473 static int sqlite3MemRoundup(int n){ return n; }
   12474 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
   12475 static void sqlite3MemShutdown(void *NotUsed){ return; }
   12476 
   12477 /*
   12478 ** This routine is the only routine in this file with external linkage.
   12479 **
   12480 ** Populate the low-level memory allocation function pointers in
   12481 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   12482 */
   12483 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   12484   static const sqlite3_mem_methods defaultMethods = {
   12485      sqlite3MemMalloc,
   12486      sqlite3MemFree,
   12487      sqlite3MemRealloc,
   12488      sqlite3MemSize,
   12489      sqlite3MemRoundup,
   12490      sqlite3MemInit,
   12491      sqlite3MemShutdown,
   12492      0
   12493   };
   12494   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   12495 }
   12496 
   12497 #endif /* SQLITE_ZERO_MALLOC */
   12498 
   12499 /************** End of mem0.c ************************************************/
   12500 /************** Begin file mem1.c ********************************************/
   12501 /*
   12502 ** 2007 August 14
   12503 **
   12504 ** The author disclaims copyright to this source code.  In place of
   12505 ** a legal notice, here is a blessing:
   12506 **
   12507 **    May you do good and not evil.
   12508 **    May you find forgiveness for yourself and forgive others.
   12509 **    May you share freely, never taking more than you give.
   12510 **
   12511 *************************************************************************
   12512 **
   12513 ** This file contains low-level memory allocation drivers for when
   12514 ** SQLite will use the standard C-library malloc/realloc/free interface
   12515 ** to obtain the memory it needs.
   12516 **
   12517 ** This file contains implementations of the low-level memory allocation
   12518 ** routines specified in the sqlite3_mem_methods object.
   12519 */
   12520 
   12521 /*
   12522 ** This version of the memory allocator is the default.  It is
   12523 ** used when no other memory allocator is specified using compile-time
   12524 ** macros.
   12525 */
   12526 #ifdef SQLITE_SYSTEM_MALLOC
   12527 
   12528 /*
   12529 ** Like malloc(), but remember the size of the allocation
   12530 ** so that we can find it later using sqlite3MemSize().
   12531 **
   12532 ** For this low-level routine, we are guaranteed that nByte>0 because
   12533 ** cases of nByte<=0 will be intercepted and dealt with by higher level
   12534 ** routines.
   12535 */
   12536 static void *sqlite3MemMalloc(int nByte){
   12537   sqlite3_int64 *p;
   12538   assert( nByte>0 );
   12539   nByte = ROUND8(nByte);
   12540   p = malloc( nByte+8 );
   12541   if( p ){
   12542     p[0] = nByte;
   12543     p++;
   12544   }else{
   12545     testcase( sqlite3GlobalConfig.xLog!=0 );
   12546     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
   12547   }
   12548   return (void *)p;
   12549 }
   12550 
   12551 /*
   12552 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
   12553 ** or sqlite3MemRealloc().
   12554 **
   12555 ** For this low-level routine, we already know that pPrior!=0 since
   12556 ** cases where pPrior==0 will have been intecepted and dealt with
   12557 ** by higher-level routines.
   12558 */
   12559 static void sqlite3MemFree(void *pPrior){
   12560   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
   12561   assert( pPrior!=0 );
   12562   p--;
   12563   free(p);
   12564 }
   12565 
   12566 /*
   12567 ** Report the allocated size of a prior return from xMalloc()
   12568 ** or xRealloc().
   12569 */
   12570 static int sqlite3MemSize(void *pPrior){
   12571   sqlite3_int64 *p;
   12572   if( pPrior==0 ) return 0;
   12573   p = (sqlite3_int64*)pPrior;
   12574   p--;
   12575   return (int)p[0];
   12576 }
   12577 
   12578 /*
   12579 ** Like realloc().  Resize an allocation previously obtained from
   12580 ** sqlite3MemMalloc().
   12581 **
   12582 ** For this low-level interface, we know that pPrior!=0.  Cases where
   12583 ** pPrior==0 while have been intercepted by higher-level routine and
   12584 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
   12585 ** cases where nByte<=0 will have been intercepted by higher-level
   12586 ** routines and redirected to xFree.
   12587 */
   12588 static void *sqlite3MemRealloc(void *pPrior, int nByte){
   12589   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
   12590   assert( pPrior!=0 && nByte>0 );
   12591   nByte = ROUND8(nByte);
   12592   p = (sqlite3_int64*)pPrior;
   12593   p--;
   12594   p = realloc(p, nByte+8 );
   12595   if( p ){
   12596     p[0] = nByte;
   12597     p++;
   12598   }else{
   12599     testcase( sqlite3GlobalConfig.xLog!=0 );
   12600     sqlite3_log(SQLITE_NOMEM,
   12601       "failed memory resize %u to %u bytes",
   12602       sqlite3MemSize(pPrior), nByte);
   12603   }
   12604   return (void*)p;
   12605 }
   12606 
   12607 /*
   12608 ** Round up a request size to the next valid allocation size.
   12609 */
   12610 static int sqlite3MemRoundup(int n){
   12611   return ROUND8(n);
   12612 }
   12613 
   12614 /*
   12615 ** Initialize this module.
   12616 */
   12617 static int sqlite3MemInit(void *NotUsed){
   12618   UNUSED_PARAMETER(NotUsed);
   12619   return SQLITE_OK;
   12620 }
   12621 
   12622 /*
   12623 ** Deinitialize this module.
   12624 */
   12625 static void sqlite3MemShutdown(void *NotUsed){
   12626   UNUSED_PARAMETER(NotUsed);
   12627   return;
   12628 }
   12629 
   12630 /*
   12631 ** This routine is the only routine in this file with external linkage.
   12632 **
   12633 ** Populate the low-level memory allocation function pointers in
   12634 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   12635 */
   12636 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   12637   static const sqlite3_mem_methods defaultMethods = {
   12638      sqlite3MemMalloc,
   12639      sqlite3MemFree,
   12640      sqlite3MemRealloc,
   12641      sqlite3MemSize,
   12642      sqlite3MemRoundup,
   12643      sqlite3MemInit,
   12644      sqlite3MemShutdown,
   12645      0
   12646   };
   12647   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   12648 }
   12649 
   12650 #endif /* SQLITE_SYSTEM_MALLOC */
   12651 
   12652 /************** End of mem1.c ************************************************/
   12653 /************** Begin file mem2.c ********************************************/
   12654 /*
   12655 ** 2007 August 15
   12656 **
   12657 ** The author disclaims copyright to this source code.  In place of
   12658 ** a legal notice, here is a blessing:
   12659 **
   12660 **    May you do good and not evil.
   12661 **    May you find forgiveness for yourself and forgive others.
   12662 **    May you share freely, never taking more than you give.
   12663 **
   12664 *************************************************************************
   12665 **
   12666 ** This file contains low-level memory allocation drivers for when
   12667 ** SQLite will use the standard C-library malloc/realloc/free interface
   12668 ** to obtain the memory it needs while adding lots of additional debugging
   12669 ** information to each allocation in order to help detect and fix memory
   12670 ** leaks and memory usage errors.
   12671 **
   12672 ** This file contains implementations of the low-level memory allocation
   12673 ** routines specified in the sqlite3_mem_methods object.
   12674 */
   12675 
   12676 /*
   12677 ** This version of the memory allocator is used only if the
   12678 ** SQLITE_MEMDEBUG macro is defined
   12679 */
   12680 #ifdef SQLITE_MEMDEBUG
   12681 
   12682 /*
   12683 ** The backtrace functionality is only available with GLIBC
   12684 */
   12685 #ifdef __GLIBC__
   12686   extern int backtrace(void**,int);
   12687   extern void backtrace_symbols_fd(void*const*,int,int);
   12688 #else
   12689 # define backtrace(A,B) 1
   12690 # define backtrace_symbols_fd(A,B,C)
   12691 #endif
   12692 
   12693 /*
   12694 ** Each memory allocation looks like this:
   12695 **
   12696 **  ------------------------------------------------------------------------
   12697 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
   12698 **  ------------------------------------------------------------------------
   12699 **
   12700 ** The application code sees only a pointer to the allocation.  We have
   12701 ** to back up from the allocation pointer to find the MemBlockHdr.  The
   12702 ** MemBlockHdr tells us the size of the allocation and the number of
   12703 ** backtrace pointers.  There is also a guard word at the end of the
   12704 ** MemBlockHdr.
   12705 */
   12706 struct MemBlockHdr {
   12707   i64 iSize;                          /* Size of this allocation */
   12708   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
   12709   char nBacktrace;                    /* Number of backtraces on this alloc */
   12710   char nBacktraceSlots;               /* Available backtrace slots */
   12711   short nTitle;                       /* Bytes of title; includes '\0' */
   12712   int iForeGuard;                     /* Guard word for sanity */
   12713 };
   12714 
   12715 /*
   12716 ** Guard words
   12717 */
   12718 #define FOREGUARD 0x80F5E153
   12719 #define REARGUARD 0xE4676B53
   12720 
   12721 /*
   12722 ** Number of malloc size increments to track.
   12723 */
   12724 #define NCSIZE  1000
   12725 
   12726 /*
   12727 ** All of the static variables used by this module are collected
   12728 ** into a single structure named "mem".  This is to keep the
   12729 ** static variables organized and to reduce namespace pollution
   12730 ** when this module is combined with other in the amalgamation.
   12731 */
   12732 static struct {
   12733 
   12734   /*
   12735   ** Mutex to control access to the memory allocation subsystem.
   12736   */
   12737   sqlite3_mutex *mutex;
   12738 
   12739   /*
   12740   ** Head and tail of a linked list of all outstanding allocations
   12741   */
   12742   struct MemBlockHdr *pFirst;
   12743   struct MemBlockHdr *pLast;
   12744 
   12745   /*
   12746   ** The number of levels of backtrace to save in new allocations.
   12747   */
   12748   int nBacktrace;
   12749   void (*xBacktrace)(int, int, void **);
   12750 
   12751   /*
   12752   ** Title text to insert in front of each block
   12753   */
   12754   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
   12755   char zTitle[100];  /* The title text */
   12756 
   12757   /*
   12758   ** sqlite3MallocDisallow() increments the following counter.
   12759   ** sqlite3MallocAllow() decrements it.
   12760   */
   12761   int disallow; /* Do not allow memory allocation */
   12762 
   12763   /*
   12764   ** Gather statistics on the sizes of memory allocations.
   12765   ** nAlloc[i] is the number of allocation attempts of i*8
   12766   ** bytes.  i==NCSIZE is the number of allocation attempts for
   12767   ** sizes more than NCSIZE*8 bytes.
   12768   */
   12769   int nAlloc[NCSIZE];      /* Total number of allocations */
   12770   int nCurrent[NCSIZE];    /* Current number of allocations */
   12771   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
   12772 
   12773 } mem;
   12774 
   12775 
   12776 /*
   12777 ** Adjust memory usage statistics
   12778 */
   12779 static void adjustStats(int iSize, int increment){
   12780   int i = ROUND8(iSize)/8;
   12781   if( i>NCSIZE-1 ){
   12782     i = NCSIZE - 1;
   12783   }
   12784   if( increment>0 ){
   12785     mem.nAlloc[i]++;
   12786     mem.nCurrent[i]++;
   12787     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
   12788       mem.mxCurrent[i] = mem.nCurrent[i];
   12789     }
   12790   }else{
   12791     mem.nCurrent[i]--;
   12792     assert( mem.nCurrent[i]>=0 );
   12793   }
   12794 }
   12795 
   12796 /*
   12797 ** Given an allocation, find the MemBlockHdr for that allocation.
   12798 **
   12799 ** This routine checks the guards at either end of the allocation and
   12800 ** if they are incorrect it asserts.
   12801 */
   12802 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
   12803   struct MemBlockHdr *p;
   12804   int *pInt;
   12805   u8 *pU8;
   12806   int nReserve;
   12807 
   12808   p = (struct MemBlockHdr*)pAllocation;
   12809   p--;
   12810   assert( p->iForeGuard==(int)FOREGUARD );
   12811   nReserve = ROUND8(p->iSize);
   12812   pInt = (int*)pAllocation;
   12813   pU8 = (u8*)pAllocation;
   12814   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
   12815   /* This checks any of the "extra" bytes allocated due
   12816   ** to rounding up to an 8 byte boundary to ensure
   12817   ** they haven't been overwritten.
   12818   */
   12819   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
   12820   return p;
   12821 }
   12822 
   12823 /*
   12824 ** Return the number of bytes currently allocated at address p.
   12825 */
   12826 static int sqlite3MemSize(void *p){
   12827   struct MemBlockHdr *pHdr;
   12828   if( !p ){
   12829     return 0;
   12830   }
   12831   pHdr = sqlite3MemsysGetHeader(p);
   12832   return pHdr->iSize;
   12833 }
   12834 
   12835 /*
   12836 ** Initialize the memory allocation subsystem.
   12837 */
   12838 static int sqlite3MemInit(void *NotUsed){
   12839   UNUSED_PARAMETER(NotUsed);
   12840   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
   12841   if( !sqlite3GlobalConfig.bMemstat ){
   12842     /* If memory status is enabled, then the malloc.c wrapper will already
   12843     ** hold the STATIC_MEM mutex when the routines here are invoked. */
   12844     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   12845   }
   12846   return SQLITE_OK;
   12847 }
   12848 
   12849 /*
   12850 ** Deinitialize the memory allocation subsystem.
   12851 */
   12852 static void sqlite3MemShutdown(void *NotUsed){
   12853   UNUSED_PARAMETER(NotUsed);
   12854   mem.mutex = 0;
   12855 }
   12856 
   12857 /*
   12858 ** Round up a request size to the next valid allocation size.
   12859 */
   12860 static int sqlite3MemRoundup(int n){
   12861   return ROUND8(n);
   12862 }
   12863 
   12864 /*
   12865 ** Fill a buffer with pseudo-random bytes.  This is used to preset
   12866 ** the content of a new memory allocation to unpredictable values and
   12867 ** to clear the content of a freed allocation to unpredictable values.
   12868 */
   12869 static void randomFill(char *pBuf, int nByte){
   12870   unsigned int x, y, r;
   12871   x = SQLITE_PTR_TO_INT(pBuf);
   12872   y = nByte | 1;
   12873   while( nByte >= 4 ){
   12874     x = (x>>1) ^ (-(x&1) & 0xd0000001);
   12875     y = y*1103515245 + 12345;
   12876     r = x ^ y;
   12877     *(int*)pBuf = r;
   12878     pBuf += 4;
   12879     nByte -= 4;
   12880   }
   12881   while( nByte-- > 0 ){
   12882     x = (x>>1) ^ (-(x&1) & 0xd0000001);
   12883     y = y*1103515245 + 12345;
   12884     r = x ^ y;
   12885     *(pBuf++) = r & 0xff;
   12886   }
   12887 }
   12888 
   12889 /*
   12890 ** Allocate nByte bytes of memory.
   12891 */
   12892 static void *sqlite3MemMalloc(int nByte){
   12893   struct MemBlockHdr *pHdr;
   12894   void **pBt;
   12895   char *z;
   12896   int *pInt;
   12897   void *p = 0;
   12898   int totalSize;
   12899   int nReserve;
   12900   sqlite3_mutex_enter(mem.mutex);
   12901   assert( mem.disallow==0 );
   12902   nReserve = ROUND8(nByte);
   12903   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
   12904                mem.nBacktrace*sizeof(void*) + mem.nTitle;
   12905   p = malloc(totalSize);
   12906   if( p ){
   12907     z = p;
   12908     pBt = (void**)&z[mem.nTitle];
   12909     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
   12910     pHdr->pNext = 0;
   12911     pHdr->pPrev = mem.pLast;
   12912     if( mem.pLast ){
   12913       mem.pLast->pNext = pHdr;
   12914     }else{
   12915       mem.pFirst = pHdr;
   12916     }
   12917     mem.pLast = pHdr;
   12918     pHdr->iForeGuard = FOREGUARD;
   12919     pHdr->nBacktraceSlots = mem.nBacktrace;
   12920     pHdr->nTitle = mem.nTitle;
   12921     if( mem.nBacktrace ){
   12922       void *aAddr[40];
   12923       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
   12924       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
   12925       assert(pBt[0]);
   12926       if( mem.xBacktrace ){
   12927         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
   12928       }
   12929     }else{
   12930       pHdr->nBacktrace = 0;
   12931     }
   12932     if( mem.nTitle ){
   12933       memcpy(z, mem.zTitle, mem.nTitle);
   12934     }
   12935     pHdr->iSize = nByte;
   12936     adjustStats(nByte, +1);
   12937     pInt = (int*)&pHdr[1];
   12938     pInt[nReserve/sizeof(int)] = REARGUARD;
   12939     randomFill((char*)pInt, nByte);
   12940     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
   12941     p = (void*)pInt;
   12942   }
   12943   sqlite3_mutex_leave(mem.mutex);
   12944   return p;
   12945 }
   12946 
   12947 /*
   12948 ** Free memory.
   12949 */
   12950 static void sqlite3MemFree(void *pPrior){
   12951   struct MemBlockHdr *pHdr;
   12952   void **pBt;
   12953   char *z;
   12954   assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 );
   12955   pHdr = sqlite3MemsysGetHeader(pPrior);
   12956   pBt = (void**)pHdr;
   12957   pBt -= pHdr->nBacktraceSlots;
   12958   sqlite3_mutex_enter(mem.mutex);
   12959   if( pHdr->pPrev ){
   12960     assert( pHdr->pPrev->pNext==pHdr );
   12961     pHdr->pPrev->pNext = pHdr->pNext;
   12962   }else{
   12963     assert( mem.pFirst==pHdr );
   12964     mem.pFirst = pHdr->pNext;
   12965   }
   12966   if( pHdr->pNext ){
   12967     assert( pHdr->pNext->pPrev==pHdr );
   12968     pHdr->pNext->pPrev = pHdr->pPrev;
   12969   }else{
   12970     assert( mem.pLast==pHdr );
   12971     mem.pLast = pHdr->pPrev;
   12972   }
   12973   z = (char*)pBt;
   12974   z -= pHdr->nTitle;
   12975   adjustStats(pHdr->iSize, -1);
   12976   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
   12977                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
   12978   free(z);
   12979   sqlite3_mutex_leave(mem.mutex);
   12980 }
   12981 
   12982 /*
   12983 ** Change the size of an existing memory allocation.
   12984 **
   12985 ** For this debugging implementation, we *always* make a copy of the
   12986 ** allocation into a new place in memory.  In this way, if the
   12987 ** higher level code is using pointer to the old allocation, it is
   12988 ** much more likely to break and we are much more liking to find
   12989 ** the error.
   12990 */
   12991 static void *sqlite3MemRealloc(void *pPrior, int nByte){
   12992   struct MemBlockHdr *pOldHdr;
   12993   void *pNew;
   12994   assert( mem.disallow==0 );
   12995   pOldHdr = sqlite3MemsysGetHeader(pPrior);
   12996   pNew = sqlite3MemMalloc(nByte);
   12997   if( pNew ){
   12998     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
   12999     if( nByte>pOldHdr->iSize ){
   13000       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
   13001     }
   13002     sqlite3MemFree(pPrior);
   13003   }
   13004   return pNew;
   13005 }
   13006 
   13007 /*
   13008 ** Populate the low-level memory allocation function pointers in
   13009 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   13010 */
   13011 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   13012   static const sqlite3_mem_methods defaultMethods = {
   13013      sqlite3MemMalloc,
   13014      sqlite3MemFree,
   13015      sqlite3MemRealloc,
   13016      sqlite3MemSize,
   13017      sqlite3MemRoundup,
   13018      sqlite3MemInit,
   13019      sqlite3MemShutdown,
   13020      0
   13021   };
   13022   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   13023 }
   13024 
   13025 /*
   13026 ** Set the number of backtrace levels kept for each allocation.
   13027 ** A value of zero turns off backtracing.  The number is always rounded
   13028 ** up to a multiple of 2.
   13029 */
   13030 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
   13031   if( depth<0 ){ depth = 0; }
   13032   if( depth>20 ){ depth = 20; }
   13033   depth = (depth+1)&0xfe;
   13034   mem.nBacktrace = depth;
   13035 }
   13036 
   13037 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
   13038   mem.xBacktrace = xBacktrace;
   13039 }
   13040 
   13041 /*
   13042 ** Set the title string for subsequent allocations.
   13043 */
   13044 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
   13045   unsigned int n = sqlite3Strlen30(zTitle) + 1;
   13046   sqlite3_mutex_enter(mem.mutex);
   13047   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
   13048   memcpy(mem.zTitle, zTitle, n);
   13049   mem.zTitle[n] = 0;
   13050   mem.nTitle = ROUND8(n);
   13051   sqlite3_mutex_leave(mem.mutex);
   13052 }
   13053 
   13054 SQLITE_PRIVATE void sqlite3MemdebugSync(){
   13055   struct MemBlockHdr *pHdr;
   13056   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
   13057     void **pBt = (void**)pHdr;
   13058     pBt -= pHdr->nBacktraceSlots;
   13059     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
   13060   }
   13061 }
   13062 
   13063 /*
   13064 ** Open the file indicated and write a log of all unfreed memory
   13065 ** allocations into that log.
   13066 */
   13067 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
   13068   FILE *out;
   13069   struct MemBlockHdr *pHdr;
   13070   void **pBt;
   13071   int i;
   13072   out = fopen(zFilename, "w");
   13073   if( out==0 ){
   13074     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   13075                     zFilename);
   13076     return;
   13077   }
   13078   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
   13079     char *z = (char*)pHdr;
   13080     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
   13081     fprintf(out, "**** %lld bytes at %p from %s ****\n",
   13082             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
   13083     if( pHdr->nBacktrace ){
   13084       fflush(out);
   13085       pBt = (void**)pHdr;
   13086       pBt -= pHdr->nBacktraceSlots;
   13087       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
   13088       fprintf(out, "\n");
   13089     }
   13090   }
   13091   fprintf(out, "COUNTS:\n");
   13092   for(i=0; i<NCSIZE-1; i++){
   13093     if( mem.nAlloc[i] ){
   13094       fprintf(out, "   %5d: %10d %10d %10d\n",
   13095             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
   13096     }
   13097   }
   13098   if( mem.nAlloc[NCSIZE-1] ){
   13099     fprintf(out, "   %5d: %10d %10d %10d\n",
   13100              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
   13101              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
   13102   }
   13103   fclose(out);
   13104 }
   13105 
   13106 /*
   13107 ** Return the number of times sqlite3MemMalloc() has been called.
   13108 */
   13109 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
   13110   int i;
   13111   int nTotal = 0;
   13112   for(i=0; i<NCSIZE; i++){
   13113     nTotal += mem.nAlloc[i];
   13114   }
   13115   return nTotal;
   13116 }
   13117 
   13118 
   13119 #endif /* SQLITE_MEMDEBUG */
   13120 
   13121 /************** End of mem2.c ************************************************/
   13122 /************** Begin file mem3.c ********************************************/
   13123 /*
   13124 ** 2007 October 14
   13125 **
   13126 ** The author disclaims copyright to this source code.  In place of
   13127 ** a legal notice, here is a blessing:
   13128 **
   13129 **    May you do good and not evil.
   13130 **    May you find forgiveness for yourself and forgive others.
   13131 **    May you share freely, never taking more than you give.
   13132 **
   13133 *************************************************************************
   13134 ** This file contains the C functions that implement a memory
   13135 ** allocation subsystem for use by SQLite.
   13136 **
   13137 ** This version of the memory allocation subsystem omits all
   13138 ** use of malloc(). The SQLite user supplies a block of memory
   13139 ** before calling sqlite3_initialize() from which allocations
   13140 ** are made and returned by the xMalloc() and xRealloc()
   13141 ** implementations. Once sqlite3_initialize() has been called,
   13142 ** the amount of memory available to SQLite is fixed and cannot
   13143 ** be changed.
   13144 **
   13145 ** This version of the memory allocation subsystem is included
   13146 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
   13147 */
   13148 
   13149 /*
   13150 ** This version of the memory allocator is only built into the library
   13151 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
   13152 ** mean that the library will use a memory-pool by default, just that
   13153 ** it is available. The mempool allocator is activated by calling
   13154 ** sqlite3_config().
   13155 */
   13156 #ifdef SQLITE_ENABLE_MEMSYS3
   13157 
   13158 /*
   13159 ** Maximum size (in Mem3Blocks) of a "small" chunk.
   13160 */
   13161 #define MX_SMALL 10
   13162 
   13163 
   13164 /*
   13165 ** Number of freelist hash slots
   13166 */
   13167 #define N_HASH  61
   13168 
   13169 /*
   13170 ** A memory allocation (also called a "chunk") consists of two or
   13171 ** more blocks where each block is 8 bytes.  The first 8 bytes are
   13172 ** a header that is not returned to the user.
   13173 **
   13174 ** A chunk is two or more blocks that is either checked out or
   13175 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
   13176 ** size of the allocation in blocks if the allocation is free.
   13177 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
   13178 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
   13179 ** is true if the previous chunk is checked out and false if the
   13180 ** previous chunk is free.  The u.hdr.prevSize field is the size of
   13181 ** the previous chunk in blocks if the previous chunk is on the
   13182 ** freelist. If the previous chunk is checked out, then
   13183 ** u.hdr.prevSize can be part of the data for that chunk and should
   13184 ** not be read or written.
   13185 **
   13186 ** We often identify a chunk by its index in mem3.aPool[].  When
   13187 ** this is done, the chunk index refers to the second block of
   13188 ** the chunk.  In this way, the first chunk has an index of 1.
   13189 ** A chunk index of 0 means "no such chunk" and is the equivalent
   13190 ** of a NULL pointer.
   13191 **
   13192 ** The second block of free chunks is of the form u.list.  The
   13193 ** two fields form a double-linked list of chunks of related sizes.
   13194 ** Pointers to the head of the list are stored in mem3.aiSmall[]
   13195 ** for smaller chunks and mem3.aiHash[] for larger chunks.
   13196 **
   13197 ** The second block of a chunk is user data if the chunk is checked
   13198 ** out.  If a chunk is checked out, the user data may extend into
   13199 ** the u.hdr.prevSize value of the following chunk.
   13200 */
   13201 typedef struct Mem3Block Mem3Block;
   13202 struct Mem3Block {
   13203   union {
   13204     struct {
   13205       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
   13206       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
   13207     } hdr;
   13208     struct {
   13209       u32 next;       /* Index in mem3.aPool[] of next free chunk */
   13210       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
   13211     } list;
   13212   } u;
   13213 };
   13214 
   13215 /*
   13216 ** All of the static variables used by this module are collected
   13217 ** into a single structure named "mem3".  This is to keep the
   13218 ** static variables organized and to reduce namespace pollution
   13219 ** when this module is combined with other in the amalgamation.
   13220 */
   13221 static SQLITE_WSD struct Mem3Global {
   13222   /*
   13223   ** Memory available for allocation. nPool is the size of the array
   13224   ** (in Mem3Blocks) pointed to by aPool less 2.
   13225   */
   13226   u32 nPool;
   13227   Mem3Block *aPool;
   13228 
   13229   /*
   13230   ** True if we are evaluating an out-of-memory callback.
   13231   */
   13232   int alarmBusy;
   13233 
   13234   /*
   13235   ** Mutex to control access to the memory allocation subsystem.
   13236   */
   13237   sqlite3_mutex *mutex;
   13238 
   13239   /*
   13240   ** The minimum amount of free space that we have seen.
   13241   */
   13242   u32 mnMaster;
   13243 
   13244   /*
   13245   ** iMaster is the index of the master chunk.  Most new allocations
   13246   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
   13247   ** of the current master.  iMaster is 0 if there is not master chunk.
   13248   ** The master chunk is not in either the aiHash[] or aiSmall[].
   13249   */
   13250   u32 iMaster;
   13251   u32 szMaster;
   13252 
   13253   /*
   13254   ** Array of lists of free blocks according to the block size
   13255   ** for smaller chunks, or a hash on the block size for larger
   13256   ** chunks.
   13257   */
   13258   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
   13259   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
   13260 } mem3 = { 97535575 };
   13261 
   13262 #define mem3 GLOBAL(struct Mem3Global, mem3)
   13263 
   13264 /*
   13265 ** Unlink the chunk at mem3.aPool[i] from list it is currently
   13266 ** on.  *pRoot is the list that i is a member of.
   13267 */
   13268 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
   13269   u32 next = mem3.aPool[i].u.list.next;
   13270   u32 prev = mem3.aPool[i].u.list.prev;
   13271   assert( sqlite3_mutex_held(mem3.mutex) );
   13272   if( prev==0 ){
   13273     *pRoot = next;
   13274   }else{
   13275     mem3.aPool[prev].u.list.next = next;
   13276   }
   13277   if( next ){
   13278     mem3.aPool[next].u.list.prev = prev;
   13279   }
   13280   mem3.aPool[i].u.list.next = 0;
   13281   mem3.aPool[i].u.list.prev = 0;
   13282 }
   13283 
   13284 /*
   13285 ** Unlink the chunk at index i from
   13286 ** whatever list is currently a member of.
   13287 */
   13288 static void memsys3Unlink(u32 i){
   13289   u32 size, hash;
   13290   assert( sqlite3_mutex_held(mem3.mutex) );
   13291   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
   13292   assert( i>=1 );
   13293   size = mem3.aPool[i-1].u.hdr.size4x/4;
   13294   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
   13295   assert( size>=2 );
   13296   if( size <= MX_SMALL ){
   13297     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
   13298   }else{
   13299     hash = size % N_HASH;
   13300     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
   13301   }
   13302 }
   13303 
   13304 /*
   13305 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
   13306 ** at *pRoot.
   13307 */
   13308 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
   13309   assert( sqlite3_mutex_held(mem3.mutex) );
   13310   mem3.aPool[i].u.list.next = *pRoot;
   13311   mem3.aPool[i].u.list.prev = 0;
   13312   if( *pRoot ){
   13313     mem3.aPool[*pRoot].u.list.prev = i;
   13314   }
   13315   *pRoot = i;
   13316 }
   13317 
   13318 /*
   13319 ** Link the chunk at index i into either the appropriate
   13320 ** small chunk list, or into the large chunk hash table.
   13321 */
   13322 static void memsys3Link(u32 i){
   13323   u32 size, hash;
   13324   assert( sqlite3_mutex_held(mem3.mutex) );
   13325   assert( i>=1 );
   13326   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
   13327   size = mem3.aPool[i-1].u.hdr.size4x/4;
   13328   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
   13329   assert( size>=2 );
   13330   if( size <= MX_SMALL ){
   13331     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
   13332   }else{
   13333     hash = size % N_HASH;
   13334     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
   13335   }
   13336 }
   13337 
   13338 /*
   13339 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
   13340 ** will already be held (obtained by code in malloc.c) if
   13341 ** sqlite3GlobalConfig.bMemStat is true.
   13342 */
   13343 static void memsys3Enter(void){
   13344   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
   13345     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   13346   }
   13347   sqlite3_mutex_enter(mem3.mutex);
   13348 }
   13349 static void memsys3Leave(void){
   13350   sqlite3_mutex_leave(mem3.mutex);
   13351 }
   13352 
   13353 /*
   13354 ** Called when we are unable to satisfy an allocation of nBytes.
   13355 */
   13356 static void memsys3OutOfMemory(int nByte){
   13357   if( !mem3.alarmBusy ){
   13358     mem3.alarmBusy = 1;
   13359     assert( sqlite3_mutex_held(mem3.mutex) );
   13360     sqlite3_mutex_leave(mem3.mutex);
   13361     sqlite3_release_memory(nByte);
   13362     sqlite3_mutex_enter(mem3.mutex);
   13363     mem3.alarmBusy = 0;
   13364   }
   13365 }
   13366 
   13367 
   13368 /*
   13369 ** Chunk i is a free chunk that has been unlinked.  Adjust its
   13370 ** size parameters for check-out and return a pointer to the
   13371 ** user portion of the chunk.
   13372 */
   13373 static void *memsys3Checkout(u32 i, u32 nBlock){
   13374   u32 x;
   13375   assert( sqlite3_mutex_held(mem3.mutex) );
   13376   assert( i>=1 );
   13377   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
   13378   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
   13379   x = mem3.aPool[i-1].u.hdr.size4x;
   13380   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
   13381   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
   13382   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
   13383   return &mem3.aPool[i];
   13384 }
   13385 
   13386 /*
   13387 ** Carve a piece off of the end of the mem3.iMaster free chunk.
   13388 ** Return a pointer to the new allocation.  Or, if the master chunk
   13389 ** is not large enough, return 0.
   13390 */
   13391 static void *memsys3FromMaster(u32 nBlock){
   13392   assert( sqlite3_mutex_held(mem3.mutex) );
   13393   assert( mem3.szMaster>=nBlock );
   13394   if( nBlock>=mem3.szMaster-1 ){
   13395     /* Use the entire master */
   13396     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
   13397     mem3.iMaster = 0;
   13398     mem3.szMaster = 0;
   13399     mem3.mnMaster = 0;
   13400     return p;
   13401   }else{
   13402     /* Split the master block.  Return the tail. */
   13403     u32 newi, x;
   13404     newi = mem3.iMaster + mem3.szMaster - nBlock;
   13405     assert( newi > mem3.iMaster+1 );
   13406     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
   13407     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
   13408     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
   13409     mem3.szMaster -= nBlock;
   13410     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
   13411     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   13412     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   13413     if( mem3.szMaster < mem3.mnMaster ){
   13414       mem3.mnMaster = mem3.szMaster;
   13415     }
   13416     return (void*)&mem3.aPool[newi];
   13417   }
   13418 }
   13419 
   13420 /*
   13421 ** *pRoot is the head of a list of free chunks of the same size
   13422 ** or same size hash.  In other words, *pRoot is an entry in either
   13423 ** mem3.aiSmall[] or mem3.aiHash[].
   13424 **
   13425 ** This routine examines all entries on the given list and tries
   13426 ** to coalesce each entries with adjacent free chunks.
   13427 **
   13428 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
   13429 ** the current mem3.iMaster with the new larger chunk.  In order for
   13430 ** this mem3.iMaster replacement to work, the master chunk must be
   13431 ** linked into the hash tables.  That is not the normal state of
   13432 ** affairs, of course.  The calling routine must link the master
   13433 ** chunk before invoking this routine, then must unlink the (possibly
   13434 ** changed) master chunk once this routine has finished.
   13435 */
   13436 static void memsys3Merge(u32 *pRoot){
   13437   u32 iNext, prev, size, i, x;
   13438 
   13439   assert( sqlite3_mutex_held(mem3.mutex) );
   13440   for(i=*pRoot; i>0; i=iNext){
   13441     iNext = mem3.aPool[i].u.list.next;
   13442     size = mem3.aPool[i-1].u.hdr.size4x;
   13443     assert( (size&1)==0 );
   13444     if( (size&2)==0 ){
   13445       memsys3UnlinkFromList(i, pRoot);
   13446       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
   13447       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
   13448       if( prev==iNext ){
   13449         iNext = mem3.aPool[prev].u.list.next;
   13450       }
   13451       memsys3Unlink(prev);
   13452       size = i + size/4 - prev;
   13453       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
   13454       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
   13455       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
   13456       memsys3Link(prev);
   13457       i = prev;
   13458     }else{
   13459       size /= 4;
   13460     }
   13461     if( size>mem3.szMaster ){
   13462       mem3.iMaster = i;
   13463       mem3.szMaster = size;
   13464     }
   13465   }
   13466 }
   13467 
   13468 /*
   13469 ** Return a block of memory of at least nBytes in size.
   13470 ** Return NULL if unable.
   13471 **
   13472 ** This function assumes that the necessary mutexes, if any, are
   13473 ** already held by the caller. Hence "Unsafe".
   13474 */
   13475 static void *memsys3MallocUnsafe(int nByte){
   13476   u32 i;
   13477   u32 nBlock;
   13478   u32 toFree;
   13479 
   13480   assert( sqlite3_mutex_held(mem3.mutex) );
   13481   assert( sizeof(Mem3Block)==8 );
   13482   if( nByte<=12 ){
   13483     nBlock = 2;
   13484   }else{
   13485     nBlock = (nByte + 11)/8;
   13486   }
   13487   assert( nBlock>=2 );
   13488 
   13489   /* STEP 1:
   13490   ** Look for an entry of the correct size in either the small
   13491   ** chunk table or in the large chunk hash table.  This is
   13492   ** successful most of the time (about 9 times out of 10).
   13493   */
   13494   if( nBlock <= MX_SMALL ){
   13495     i = mem3.aiSmall[nBlock-2];
   13496     if( i>0 ){
   13497       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
   13498       return memsys3Checkout(i, nBlock);
   13499     }
   13500   }else{
   13501     int hash = nBlock % N_HASH;
   13502     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
   13503       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
   13504         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
   13505         return memsys3Checkout(i, nBlock);
   13506       }
   13507     }
   13508   }
   13509 
   13510   /* STEP 2:
   13511   ** Try to satisfy the allocation by carving a piece off of the end
   13512   ** of the master chunk.  This step usually works if step 1 fails.
   13513   */
   13514   if( mem3.szMaster>=nBlock ){
   13515     return memsys3FromMaster(nBlock);
   13516   }
   13517 
   13518 
   13519   /* STEP 3:
   13520   ** Loop through the entire memory pool.  Coalesce adjacent free
   13521   ** chunks.  Recompute the master chunk as the largest free chunk.
   13522   ** Then try again to satisfy the allocation by carving a piece off
   13523   ** of the end of the master chunk.  This step happens very
   13524   ** rarely (we hope!)
   13525   */
   13526   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
   13527     memsys3OutOfMemory(toFree);
   13528     if( mem3.iMaster ){
   13529       memsys3Link(mem3.iMaster);
   13530       mem3.iMaster = 0;
   13531       mem3.szMaster = 0;
   13532     }
   13533     for(i=0; i<N_HASH; i++){
   13534       memsys3Merge(&mem3.aiHash[i]);
   13535     }
   13536     for(i=0; i<MX_SMALL-1; i++){
   13537       memsys3Merge(&mem3.aiSmall[i]);
   13538     }
   13539     if( mem3.szMaster ){
   13540       memsys3Unlink(mem3.iMaster);
   13541       if( mem3.szMaster>=nBlock ){
   13542         return memsys3FromMaster(nBlock);
   13543       }
   13544     }
   13545   }
   13546 
   13547   /* If none of the above worked, then we fail. */
   13548   return 0;
   13549 }
   13550 
   13551 /*
   13552 ** Free an outstanding memory allocation.
   13553 **
   13554 ** This function assumes that the necessary mutexes, if any, are
   13555 ** already held by the caller. Hence "Unsafe".
   13556 */
   13557 void memsys3FreeUnsafe(void *pOld){
   13558   Mem3Block *p = (Mem3Block*)pOld;
   13559   int i;
   13560   u32 size, x;
   13561   assert( sqlite3_mutex_held(mem3.mutex) );
   13562   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
   13563   i = p - mem3.aPool;
   13564   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
   13565   size = mem3.aPool[i-1].u.hdr.size4x/4;
   13566   assert( i+size<=mem3.nPool+1 );
   13567   mem3.aPool[i-1].u.hdr.size4x &= ~1;
   13568   mem3.aPool[i+size-1].u.hdr.prevSize = size;
   13569   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
   13570   memsys3Link(i);
   13571 
   13572   /* Try to expand the master using the newly freed chunk */
   13573   if( mem3.iMaster ){
   13574     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
   13575       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
   13576       mem3.iMaster -= size;
   13577       mem3.szMaster += size;
   13578       memsys3Unlink(mem3.iMaster);
   13579       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   13580       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   13581       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
   13582     }
   13583     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   13584     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
   13585       memsys3Unlink(mem3.iMaster+mem3.szMaster);
   13586       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
   13587       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   13588       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
   13589     }
   13590   }
   13591 }
   13592 
   13593 /*
   13594 ** Return the size of an outstanding allocation, in bytes.  The
   13595 ** size returned omits the 8-byte header overhead.  This only
   13596 ** works for chunks that are currently checked out.
   13597 */
   13598 static int memsys3Size(void *p){
   13599   Mem3Block *pBlock;
   13600   if( p==0 ) return 0;
   13601   pBlock = (Mem3Block*)p;
   13602   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
   13603   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
   13604 }
   13605 
   13606 /*
   13607 ** Round up a request size to the next valid allocation size.
   13608 */
   13609 static int memsys3Roundup(int n){
   13610   if( n<=12 ){
   13611     return 12;
   13612   }else{
   13613     return ((n+11)&~7) - 4;
   13614   }
   13615 }
   13616 
   13617 /*
   13618 ** Allocate nBytes of memory.
   13619 */
   13620 static void *memsys3Malloc(int nBytes){
   13621   sqlite3_int64 *p;
   13622   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
   13623   memsys3Enter();
   13624   p = memsys3MallocUnsafe(nBytes);
   13625   memsys3Leave();
   13626   return (void*)p;
   13627 }
   13628 
   13629 /*
   13630 ** Free memory.
   13631 */
   13632 void memsys3Free(void *pPrior){
   13633   assert( pPrior );
   13634   memsys3Enter();
   13635   memsys3FreeUnsafe(pPrior);
   13636   memsys3Leave();
   13637 }
   13638 
   13639 /*
   13640 ** Change the size of an existing memory allocation
   13641 */
   13642 void *memsys3Realloc(void *pPrior, int nBytes){
   13643   int nOld;
   13644   void *p;
   13645   if( pPrior==0 ){
   13646     return sqlite3_malloc(nBytes);
   13647   }
   13648   if( nBytes<=0 ){
   13649     sqlite3_free(pPrior);
   13650     return 0;
   13651   }
   13652   nOld = memsys3Size(pPrior);
   13653   if( nBytes<=nOld && nBytes>=nOld-128 ){
   13654     return pPrior;
   13655   }
   13656   memsys3Enter();
   13657   p = memsys3MallocUnsafe(nBytes);
   13658   if( p ){
   13659     if( nOld<nBytes ){
   13660       memcpy(p, pPrior, nOld);
   13661     }else{
   13662       memcpy(p, pPrior, nBytes);
   13663     }
   13664     memsys3FreeUnsafe(pPrior);
   13665   }
   13666   memsys3Leave();
   13667   return p;
   13668 }
   13669 
   13670 /*
   13671 ** Initialize this module.
   13672 */
   13673 static int memsys3Init(void *NotUsed){
   13674   UNUSED_PARAMETER(NotUsed);
   13675   if( !sqlite3GlobalConfig.pHeap ){
   13676     return SQLITE_ERROR;
   13677   }
   13678 
   13679   /* Store a pointer to the memory block in global structure mem3. */
   13680   assert( sizeof(Mem3Block)==8 );
   13681   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
   13682   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
   13683 
   13684   /* Initialize the master block. */
   13685   mem3.szMaster = mem3.nPool;
   13686   mem3.mnMaster = mem3.szMaster;
   13687   mem3.iMaster = 1;
   13688   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
   13689   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
   13690   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
   13691 
   13692   return SQLITE_OK;
   13693 }
   13694 
   13695 /*
   13696 ** Deinitialize this module.
   13697 */
   13698 static void memsys3Shutdown(void *NotUsed){
   13699   UNUSED_PARAMETER(NotUsed);
   13700   mem3.mutex = 0;
   13701   return;
   13702 }
   13703 
   13704 
   13705 
   13706 /*
   13707 ** Open the file indicated and write a log of all unfreed memory
   13708 ** allocations into that log.
   13709 */
   13710 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
   13711 #ifdef SQLITE_DEBUG
   13712   FILE *out;
   13713   u32 i, j;
   13714   u32 size;
   13715   if( zFilename==0 || zFilename[0]==0 ){
   13716     out = stdout;
   13717   }else{
   13718     out = fopen(zFilename, "w");
   13719     if( out==0 ){
   13720       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   13721                       zFilename);
   13722       return;
   13723     }
   13724   }
   13725   memsys3Enter();
   13726   fprintf(out, "CHUNKS:\n");
   13727   for(i=1; i<=mem3.nPool; i+=size/4){
   13728     size = mem3.aPool[i-1].u.hdr.size4x;
   13729     if( size/4<=1 ){
   13730       fprintf(out, "%p size error\n", &mem3.aPool[i]);
   13731       assert( 0 );
   13732       break;
   13733     }
   13734     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
   13735       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
   13736       assert( 0 );
   13737       break;
   13738     }
   13739     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
   13740       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
   13741       assert( 0 );
   13742       break;
   13743     }
   13744     if( size&1 ){
   13745       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
   13746     }else{
   13747       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
   13748                   i==mem3.iMaster ? " **master**" : "");
   13749     }
   13750   }
   13751   for(i=0; i<MX_SMALL-1; i++){
   13752     if( mem3.aiSmall[i]==0 ) continue;
   13753     fprintf(out, "small(%2d):", i);
   13754     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
   13755       fprintf(out, " %p(%d)", &mem3.aPool[j],
   13756               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
   13757     }
   13758     fprintf(out, "\n");
   13759   }
   13760   for(i=0; i<N_HASH; i++){
   13761     if( mem3.aiHash[i]==0 ) continue;
   13762     fprintf(out, "hash(%2d):", i);
   13763     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
   13764       fprintf(out, " %p(%d)", &mem3.aPool[j],
   13765               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
   13766     }
   13767     fprintf(out, "\n");
   13768   }
   13769   fprintf(out, "master=%d\n", mem3.iMaster);
   13770   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
   13771   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
   13772   sqlite3_mutex_leave(mem3.mutex);
   13773   if( out==stdout ){
   13774     fflush(stdout);
   13775   }else{
   13776     fclose(out);
   13777   }
   13778 #else
   13779   UNUSED_PARAMETER(zFilename);
   13780 #endif
   13781 }
   13782 
   13783 /*
   13784 ** This routine is the only routine in this file with external
   13785 ** linkage.
   13786 **
   13787 ** Populate the low-level memory allocation function pointers in
   13788 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
   13789 ** arguments specify the block of memory to manage.
   13790 **
   13791 ** This routine is only called by sqlite3_config(), and therefore
   13792 ** is not required to be threadsafe (it is not).
   13793 */
   13794 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
   13795   static const sqlite3_mem_methods mempoolMethods = {
   13796      memsys3Malloc,
   13797      memsys3Free,
   13798      memsys3Realloc,
   13799      memsys3Size,
   13800      memsys3Roundup,
   13801      memsys3Init,
   13802      memsys3Shutdown,
   13803      0
   13804   };
   13805   return &mempoolMethods;
   13806 }
   13807 
   13808 #endif /* SQLITE_ENABLE_MEMSYS3 */
   13809 
   13810 /************** End of mem3.c ************************************************/
   13811 /************** Begin file mem5.c ********************************************/
   13812 /*
   13813 ** 2007 October 14
   13814 **
   13815 ** The author disclaims copyright to this source code.  In place of
   13816 ** a legal notice, here is a blessing:
   13817 **
   13818 **    May you do good and not evil.
   13819 **    May you find forgiveness for yourself and forgive others.
   13820 **    May you share freely, never taking more than you give.
   13821 **
   13822 *************************************************************************
   13823 ** This file contains the C functions that implement a memory
   13824 ** allocation subsystem for use by SQLite.
   13825 **
   13826 ** This version of the memory allocation subsystem omits all
   13827 ** use of malloc(). The application gives SQLite a block of memory
   13828 ** before calling sqlite3_initialize() from which allocations
   13829 ** are made and returned by the xMalloc() and xRealloc()
   13830 ** implementations. Once sqlite3_initialize() has been called,
   13831 ** the amount of memory available to SQLite is fixed and cannot
   13832 ** be changed.
   13833 **
   13834 ** This version of the memory allocation subsystem is included
   13835 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
   13836 **
   13837 ** This memory allocator uses the following algorithm:
   13838 **
   13839 **   1.  All memory allocations sizes are rounded up to a power of 2.
   13840 **
   13841 **   2.  If two adjacent free blocks are the halves of a larger block,
   13842 **       then the two blocks are coalesed into the single larger block.
   13843 **
   13844 **   3.  New memory is allocated from the first available free block.
   13845 **
   13846 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
   13847 ** Concerning Dynamic Storage Allocation". Journal of the Association for
   13848 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
   13849 **
   13850 ** Let n be the size of the largest allocation divided by the minimum
   13851 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
   13852 ** be the maximum amount of memory ever outstanding at one time.  Let
   13853 ** N be the total amount of memory available for allocation.  Robson
   13854 ** proved that this memory allocator will never breakdown due to
   13855 ** fragmentation as long as the following constraint holds:
   13856 **
   13857 **      N >=  M*(1 + log2(n)/2) - n + 1
   13858 **
   13859 ** The sqlite3_status() logic tracks the maximum values of n and M so
   13860 ** that an application can, at any time, verify this constraint.
   13861 */
   13862 
   13863 /*
   13864 ** This version of the memory allocator is used only when
   13865 ** SQLITE_ENABLE_MEMSYS5 is defined.
   13866 */
   13867 #ifdef SQLITE_ENABLE_MEMSYS5
   13868 
   13869 /*
   13870 ** A minimum allocation is an instance of the following structure.
   13871 ** Larger allocations are an array of these structures where the
   13872 ** size of the array is a power of 2.
   13873 **
   13874 ** The size of this object must be a power of two.  That fact is
   13875 ** verified in memsys5Init().
   13876 */
   13877 typedef struct Mem5Link Mem5Link;
   13878 struct Mem5Link {
   13879   int next;       /* Index of next free chunk */
   13880   int prev;       /* Index of previous free chunk */
   13881 };
   13882 
   13883 /*
   13884 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
   13885 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
   13886 ** it is not actually possible to reach this limit.
   13887 */
   13888 #define LOGMAX 30
   13889 
   13890 /*
   13891 ** Masks used for mem5.aCtrl[] elements.
   13892 */
   13893 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
   13894 #define CTRL_FREE     0x20    /* True if not checked out */
   13895 
   13896 /*
   13897 ** All of the static variables used by this module are collected
   13898 ** into a single structure named "mem5".  This is to keep the
   13899 ** static variables organized and to reduce namespace pollution
   13900 ** when this module is combined with other in the amalgamation.
   13901 */
   13902 static SQLITE_WSD struct Mem5Global {
   13903   /*
   13904   ** Memory available for allocation
   13905   */
   13906   int szAtom;      /* Smallest possible allocation in bytes */
   13907   int nBlock;      /* Number of szAtom sized blocks in zPool */
   13908   u8 *zPool;       /* Memory available to be allocated */
   13909 
   13910   /*
   13911   ** Mutex to control access to the memory allocation subsystem.
   13912   */
   13913   sqlite3_mutex *mutex;
   13914 
   13915   /*
   13916   ** Performance statistics
   13917   */
   13918   u64 nAlloc;         /* Total number of calls to malloc */
   13919   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
   13920   u64 totalExcess;    /* Total internal fragmentation */
   13921   u32 currentOut;     /* Current checkout, including internal fragmentation */
   13922   u32 currentCount;   /* Current number of distinct checkouts */
   13923   u32 maxOut;         /* Maximum instantaneous currentOut */
   13924   u32 maxCount;       /* Maximum instantaneous currentCount */
   13925   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
   13926 
   13927   /*
   13928   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
   13929   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
   13930   ** and so forth.
   13931   */
   13932   int aiFreelist[LOGMAX+1];
   13933 
   13934   /*
   13935   ** Space for tracking which blocks are checked out and the size
   13936   ** of each block.  One byte per block.
   13937   */
   13938   u8 *aCtrl;
   13939 
   13940 } mem5 = { 0 };
   13941 
   13942 /*
   13943 ** Access the static variable through a macro for SQLITE_OMIT_WSD
   13944 */
   13945 #define mem5 GLOBAL(struct Mem5Global, mem5)
   13946 
   13947 /*
   13948 ** Assuming mem5.zPool is divided up into an array of Mem5Link
   13949 ** structures, return a pointer to the idx-th such lik.
   13950 */
   13951 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
   13952 
   13953 /*
   13954 ** Unlink the chunk at mem5.aPool[i] from list it is currently
   13955 ** on.  It should be found on mem5.aiFreelist[iLogsize].
   13956 */
   13957 static void memsys5Unlink(int i, int iLogsize){
   13958   int next, prev;
   13959   assert( i>=0 && i<mem5.nBlock );
   13960   assert( iLogsize>=0 && iLogsize<=LOGMAX );
   13961   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
   13962 
   13963   next = MEM5LINK(i)->next;
   13964   prev = MEM5LINK(i)->prev;
   13965   if( prev<0 ){
   13966     mem5.aiFreelist[iLogsize] = next;
   13967   }else{
   13968     MEM5LINK(prev)->next = next;
   13969   }
   13970   if( next>=0 ){
   13971     MEM5LINK(next)->prev = prev;
   13972   }
   13973 }
   13974 
   13975 /*
   13976 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
   13977 ** free list.
   13978 */
   13979 static void memsys5Link(int i, int iLogsize){
   13980   int x;
   13981   assert( sqlite3_mutex_held(mem5.mutex) );
   13982   assert( i>=0 && i<mem5.nBlock );
   13983   assert( iLogsize>=0 && iLogsize<=LOGMAX );
   13984   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
   13985 
   13986   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
   13987   MEM5LINK(i)->prev = -1;
   13988   if( x>=0 ){
   13989     assert( x<mem5.nBlock );
   13990     MEM5LINK(x)->prev = i;
   13991   }
   13992   mem5.aiFreelist[iLogsize] = i;
   13993 }
   13994 
   13995 /*
   13996 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
   13997 ** will already be held (obtained by code in malloc.c) if
   13998 ** sqlite3GlobalConfig.bMemStat is true.
   13999 */
   14000 static void memsys5Enter(void){
   14001   sqlite3_mutex_enter(mem5.mutex);
   14002 }
   14003 static void memsys5Leave(void){
   14004   sqlite3_mutex_leave(mem5.mutex);
   14005 }
   14006 
   14007 /*
   14008 ** Return the size of an outstanding allocation, in bytes.  The
   14009 ** size returned omits the 8-byte header overhead.  This only
   14010 ** works for chunks that are currently checked out.
   14011 */
   14012 static int memsys5Size(void *p){
   14013   int iSize = 0;
   14014   if( p ){
   14015     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
   14016     assert( i>=0 && i<mem5.nBlock );
   14017     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
   14018   }
   14019   return iSize;
   14020 }
   14021 
   14022 /*
   14023 ** Find the first entry on the freelist iLogsize.  Unlink that
   14024 ** entry and return its index.
   14025 */
   14026 static int memsys5UnlinkFirst(int iLogsize){
   14027   int i;
   14028   int iFirst;
   14029 
   14030   assert( iLogsize>=0 && iLogsize<=LOGMAX );
   14031   i = iFirst = mem5.aiFreelist[iLogsize];
   14032   assert( iFirst>=0 );
   14033   while( i>0 ){
   14034     if( i<iFirst ) iFirst = i;
   14035     i = MEM5LINK(i)->next;
   14036   }
   14037   memsys5Unlink(iFirst, iLogsize);
   14038   return iFirst;
   14039 }
   14040 
   14041 /*
   14042 ** Return a block of memory of at least nBytes in size.
   14043 ** Return NULL if unable.  Return NULL if nBytes==0.
   14044 **
   14045 ** The caller guarantees that nByte positive.
   14046 **
   14047 ** The caller has obtained a mutex prior to invoking this
   14048 ** routine so there is never any chance that two or more
   14049 ** threads can be in this routine at the same time.
   14050 */
   14051 static void *memsys5MallocUnsafe(int nByte){
   14052   int i;           /* Index of a mem5.aPool[] slot */
   14053   int iBin;        /* Index into mem5.aiFreelist[] */
   14054   int iFullSz;     /* Size of allocation rounded up to power of 2 */
   14055   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
   14056 
   14057   /* nByte must be a positive */
   14058   assert( nByte>0 );
   14059 
   14060   /* Keep track of the maximum allocation request.  Even unfulfilled
   14061   ** requests are counted */
   14062   if( (u32)nByte>mem5.maxRequest ){
   14063     mem5.maxRequest = nByte;
   14064   }
   14065 
   14066   /* Abort if the requested allocation size is larger than the largest
   14067   ** power of two that we can represent using 32-bit signed integers.
   14068   */
   14069   if( nByte > 0x40000000 ){
   14070     return 0;
   14071   }
   14072 
   14073   /* Round nByte up to the next valid power of two */
   14074   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
   14075 
   14076   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
   14077   ** block.  If not, then split a block of the next larger power of
   14078   ** two in order to create a new free block of size iLogsize.
   14079   */
   14080   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
   14081   if( iBin>LOGMAX ){
   14082     testcase( sqlite3GlobalConfig.xLog!=0 );
   14083     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
   14084     return 0;
   14085   }
   14086   i = memsys5UnlinkFirst(iBin);
   14087   while( iBin>iLogsize ){
   14088     int newSize;
   14089 
   14090     iBin--;
   14091     newSize = 1 << iBin;
   14092     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
   14093     memsys5Link(i+newSize, iBin);
   14094   }
   14095   mem5.aCtrl[i] = iLogsize;
   14096 
   14097   /* Update allocator performance statistics. */
   14098   mem5.nAlloc++;
   14099   mem5.totalAlloc += iFullSz;
   14100   mem5.totalExcess += iFullSz - nByte;
   14101   mem5.currentCount++;
   14102   mem5.currentOut += iFullSz;
   14103   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
   14104   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
   14105 
   14106   /* Return a pointer to the allocated memory. */
   14107   return (void*)&mem5.zPool[i*mem5.szAtom];
   14108 }
   14109 
   14110 /*
   14111 ** Free an outstanding memory allocation.
   14112 */
   14113 static void memsys5FreeUnsafe(void *pOld){
   14114   u32 size, iLogsize;
   14115   int iBlock;
   14116 
   14117   /* Set iBlock to the index of the block pointed to by pOld in
   14118   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
   14119   */
   14120   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
   14121 
   14122   /* Check that the pointer pOld points to a valid, non-free block. */
   14123   assert( iBlock>=0 && iBlock<mem5.nBlock );
   14124   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
   14125   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
   14126 
   14127   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
   14128   size = 1<<iLogsize;
   14129   assert( iBlock+size-1<(u32)mem5.nBlock );
   14130 
   14131   mem5.aCtrl[iBlock] |= CTRL_FREE;
   14132   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
   14133   assert( mem5.currentCount>0 );
   14134   assert( mem5.currentOut>=(size*mem5.szAtom) );
   14135   mem5.currentCount--;
   14136   mem5.currentOut -= size*mem5.szAtom;
   14137   assert( mem5.currentOut>0 || mem5.currentCount==0 );
   14138   assert( mem5.currentCount>0 || mem5.currentOut==0 );
   14139 
   14140   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
   14141   while( ALWAYS(iLogsize<LOGMAX) ){
   14142     int iBuddy;
   14143     if( (iBlock>>iLogsize) & 1 ){
   14144       iBuddy = iBlock - size;
   14145     }else{
   14146       iBuddy = iBlock + size;
   14147     }
   14148     assert( iBuddy>=0 );
   14149     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
   14150     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
   14151     memsys5Unlink(iBuddy, iLogsize);
   14152     iLogsize++;
   14153     if( iBuddy<iBlock ){
   14154       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
   14155       mem5.aCtrl[iBlock] = 0;
   14156       iBlock = iBuddy;
   14157     }else{
   14158       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
   14159       mem5.aCtrl[iBuddy] = 0;
   14160     }
   14161     size *= 2;
   14162   }
   14163   memsys5Link(iBlock, iLogsize);
   14164 }
   14165 
   14166 /*
   14167 ** Allocate nBytes of memory
   14168 */
   14169 static void *memsys5Malloc(int nBytes){
   14170   sqlite3_int64 *p = 0;
   14171   if( nBytes>0 ){
   14172     memsys5Enter();
   14173     p = memsys5MallocUnsafe(nBytes);
   14174     memsys5Leave();
   14175   }
   14176   return (void*)p;
   14177 }
   14178 
   14179 /*
   14180 ** Free memory.
   14181 **
   14182 ** The outer layer memory allocator prevents this routine from
   14183 ** being called with pPrior==0.
   14184 */
   14185 static void memsys5Free(void *pPrior){
   14186   assert( pPrior!=0 );
   14187   memsys5Enter();
   14188   memsys5FreeUnsafe(pPrior);
   14189   memsys5Leave();
   14190 }
   14191 
   14192 /*
   14193 ** Change the size of an existing memory allocation.
   14194 **
   14195 ** The outer layer memory allocator prevents this routine from
   14196 ** being called with pPrior==0.
   14197 **
   14198 ** nBytes is always a value obtained from a prior call to
   14199 ** memsys5Round().  Hence nBytes is always a non-negative power
   14200 ** of two.  If nBytes==0 that means that an oversize allocation
   14201 ** (an allocation larger than 0x40000000) was requested and this
   14202 ** routine should return 0 without freeing pPrior.
   14203 */
   14204 static void *memsys5Realloc(void *pPrior, int nBytes){
   14205   int nOld;
   14206   void *p;
   14207   assert( pPrior!=0 );
   14208   assert( (nBytes&(nBytes-1))==0 );
   14209   assert( nBytes>=0 );
   14210   if( nBytes==0 ){
   14211     return 0;
   14212   }
   14213   nOld = memsys5Size(pPrior);
   14214   if( nBytes<=nOld ){
   14215     return pPrior;
   14216   }
   14217   memsys5Enter();
   14218   p = memsys5MallocUnsafe(nBytes);
   14219   if( p ){
   14220     memcpy(p, pPrior, nOld);
   14221     memsys5FreeUnsafe(pPrior);
   14222   }
   14223   memsys5Leave();
   14224   return p;
   14225 }
   14226 
   14227 /*
   14228 ** Round up a request size to the next valid allocation size.  If
   14229 ** the allocation is too large to be handled by this allocation system,
   14230 ** return 0.
   14231 **
   14232 ** All allocations must be a power of two and must be expressed by a
   14233 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
   14234 ** or 1073741824 bytes.
   14235 */
   14236 static int memsys5Roundup(int n){
   14237   int iFullSz;
   14238   if( n > 0x40000000 ) return 0;
   14239   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
   14240   return iFullSz;
   14241 }
   14242 
   14243 /*
   14244 ** Return the ceiling of the logarithm base 2 of iValue.
   14245 **
   14246 ** Examples:   memsys5Log(1) -> 0
   14247 **             memsys5Log(2) -> 1
   14248 **             memsys5Log(4) -> 2
   14249 **             memsys5Log(5) -> 3
   14250 **             memsys5Log(8) -> 3
   14251 **             memsys5Log(9) -> 4
   14252 */
   14253 static int memsys5Log(int iValue){
   14254   int iLog;
   14255   for(iLog=0; (1<<iLog)<iValue; iLog++);
   14256   return iLog;
   14257 }
   14258 
   14259 /*
   14260 ** Initialize the memory allocator.
   14261 **
   14262 ** This routine is not threadsafe.  The caller must be holding a mutex
   14263 ** to prevent multiple threads from entering at the same time.
   14264 */
   14265 static int memsys5Init(void *NotUsed){
   14266   int ii;            /* Loop counter */
   14267   int nByte;         /* Number of bytes of memory available to this allocator */
   14268   u8 *zByte;         /* Memory usable by this allocator */
   14269   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
   14270   int iOffset;       /* An offset into mem5.aCtrl[] */
   14271 
   14272   UNUSED_PARAMETER(NotUsed);
   14273 
   14274   /* For the purposes of this routine, disable the mutex */
   14275   mem5.mutex = 0;
   14276 
   14277   /* The size of a Mem5Link object must be a power of two.  Verify that
   14278   ** this is case.
   14279   */
   14280   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
   14281 
   14282   nByte = sqlite3GlobalConfig.nHeap;
   14283   zByte = (u8*)sqlite3GlobalConfig.pHeap;
   14284   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
   14285 
   14286   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
   14287   mem5.szAtom = (1<<nMinLog);
   14288   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
   14289     mem5.szAtom = mem5.szAtom << 1;
   14290   }
   14291 
   14292   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
   14293   mem5.zPool = zByte;
   14294   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
   14295 
   14296   for(ii=0; ii<=LOGMAX; ii++){
   14297     mem5.aiFreelist[ii] = -1;
   14298   }
   14299 
   14300   iOffset = 0;
   14301   for(ii=LOGMAX; ii>=0; ii--){
   14302     int nAlloc = (1<<ii);
   14303     if( (iOffset+nAlloc)<=mem5.nBlock ){
   14304       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
   14305       memsys5Link(iOffset, ii);
   14306       iOffset += nAlloc;
   14307     }
   14308     assert((iOffset+nAlloc)>mem5.nBlock);
   14309   }
   14310 
   14311   /* If a mutex is required for normal operation, allocate one */
   14312   if( sqlite3GlobalConfig.bMemstat==0 ){
   14313     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   14314   }
   14315 
   14316   return SQLITE_OK;
   14317 }
   14318 
   14319 /*
   14320 ** Deinitialize this module.
   14321 */
   14322 static void memsys5Shutdown(void *NotUsed){
   14323   UNUSED_PARAMETER(NotUsed);
   14324   mem5.mutex = 0;
   14325   return;
   14326 }
   14327 
   14328 #ifdef SQLITE_TEST
   14329 /*
   14330 ** Open the file indicated and write a log of all unfreed memory
   14331 ** allocations into that log.
   14332 */
   14333 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
   14334   FILE *out;
   14335   int i, j, n;
   14336   int nMinLog;
   14337 
   14338   if( zFilename==0 || zFilename[0]==0 ){
   14339     out = stdout;
   14340   }else{
   14341     out = fopen(zFilename, "w");
   14342     if( out==0 ){
   14343       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   14344                       zFilename);
   14345       return;
   14346     }
   14347   }
   14348   memsys5Enter();
   14349   nMinLog = memsys5Log(mem5.szAtom);
   14350   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
   14351     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
   14352     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
   14353   }
   14354   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
   14355   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
   14356   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
   14357   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
   14358   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
   14359   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
   14360   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
   14361   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
   14362   memsys5Leave();
   14363   if( out==stdout ){
   14364     fflush(stdout);
   14365   }else{
   14366     fclose(out);
   14367   }
   14368 }
   14369 #endif
   14370 
   14371 /*
   14372 ** This routine is the only routine in this file with external
   14373 ** linkage. It returns a pointer to a static sqlite3_mem_methods
   14374 ** struct populated with the memsys5 methods.
   14375 */
   14376 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
   14377   static const sqlite3_mem_methods memsys5Methods = {
   14378      memsys5Malloc,
   14379      memsys5Free,
   14380      memsys5Realloc,
   14381      memsys5Size,
   14382      memsys5Roundup,
   14383      memsys5Init,
   14384      memsys5Shutdown,
   14385      0
   14386   };
   14387   return &memsys5Methods;
   14388 }
   14389 
   14390 #endif /* SQLITE_ENABLE_MEMSYS5 */
   14391 
   14392 /************** End of mem5.c ************************************************/
   14393 /************** Begin file mutex.c *******************************************/
   14394 /*
   14395 ** 2007 August 14
   14396 **
   14397 ** The author disclaims copyright to this source code.  In place of
   14398 ** a legal notice, here is a blessing:
   14399 **
   14400 **    May you do good and not evil.
   14401 **    May you find forgiveness for yourself and forgive others.
   14402 **    May you share freely, never taking more than you give.
   14403 **
   14404 *************************************************************************
   14405 ** This file contains the C functions that implement mutexes.
   14406 **
   14407 ** This file contains code that is common across all mutex implementations.
   14408 */
   14409 
   14410 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
   14411 /*
   14412 ** For debugging purposes, record when the mutex subsystem is initialized
   14413 ** and uninitialized so that we can assert() if there is an attempt to
   14414 ** allocate a mutex while the system is uninitialized.
   14415 */
   14416 static SQLITE_WSD int mutexIsInit = 0;
   14417 #endif /* SQLITE_DEBUG */
   14418 
   14419 
   14420 #ifndef SQLITE_MUTEX_OMIT
   14421 /*
   14422 ** Initialize the mutex system.
   14423 */
   14424 SQLITE_PRIVATE int sqlite3MutexInit(void){
   14425   int rc = SQLITE_OK;
   14426   if( sqlite3GlobalConfig.bCoreMutex ){
   14427     if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
   14428       /* If the xMutexAlloc method has not been set, then the user did not
   14429       ** install a mutex implementation via sqlite3_config() prior to
   14430       ** sqlite3_initialize() being called. This block copies pointers to
   14431       ** the default implementation into the sqlite3GlobalConfig structure.
   14432       */
   14433       sqlite3_mutex_methods *pFrom = sqlite3DefaultMutex();
   14434       sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
   14435 
   14436       memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
   14437       memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
   14438              sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
   14439       pTo->xMutexAlloc = pFrom->xMutexAlloc;
   14440     }
   14441     rc = sqlite3GlobalConfig.mutex.xMutexInit();
   14442   }
   14443 
   14444 #ifdef SQLITE_DEBUG
   14445   GLOBAL(int, mutexIsInit) = 1;
   14446 #endif
   14447 
   14448   return rc;
   14449 }
   14450 
   14451 /*
   14452 ** Shutdown the mutex system. This call frees resources allocated by
   14453 ** sqlite3MutexInit().
   14454 */
   14455 SQLITE_PRIVATE int sqlite3MutexEnd(void){
   14456   int rc = SQLITE_OK;
   14457   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
   14458     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
   14459   }
   14460 
   14461 #ifdef SQLITE_DEBUG
   14462   GLOBAL(int, mutexIsInit) = 0;
   14463 #endif
   14464 
   14465   return rc;
   14466 }
   14467 
   14468 /*
   14469 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
   14470 */
   14471 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
   14472 #ifndef SQLITE_OMIT_AUTOINIT
   14473   if( sqlite3_initialize() ) return 0;
   14474 #endif
   14475   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
   14476 }
   14477 
   14478 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
   14479   if( !sqlite3GlobalConfig.bCoreMutex ){
   14480     return 0;
   14481   }
   14482   assert( GLOBAL(int, mutexIsInit) );
   14483   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
   14484 }
   14485 
   14486 /*
   14487 ** Free a dynamic mutex.
   14488 */
   14489 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
   14490   if( p ){
   14491     sqlite3GlobalConfig.mutex.xMutexFree(p);
   14492   }
   14493 }
   14494 
   14495 /*
   14496 ** Obtain the mutex p. If some other thread already has the mutex, block
   14497 ** until it can be obtained.
   14498 */
   14499 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
   14500   if( p ){
   14501     sqlite3GlobalConfig.mutex.xMutexEnter(p);
   14502   }
   14503 }
   14504 
   14505 /*
   14506 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
   14507 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
   14508 */
   14509 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
   14510   int rc = SQLITE_OK;
   14511   if( p ){
   14512     return sqlite3GlobalConfig.mutex.xMutexTry(p);
   14513   }
   14514   return rc;
   14515 }
   14516 
   14517 /*
   14518 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
   14519 ** entered by the same thread.  The behavior is undefined if the mutex
   14520 ** is not currently entered. If a NULL pointer is passed as an argument
   14521 ** this function is a no-op.
   14522 */
   14523 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
   14524   if( p ){
   14525     sqlite3GlobalConfig.mutex.xMutexLeave(p);
   14526   }
   14527 }
   14528 
   14529 #ifndef NDEBUG
   14530 /*
   14531 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   14532 ** intended for use inside assert() statements.
   14533 */
   14534 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
   14535   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
   14536 }
   14537 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
   14538   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
   14539 }
   14540 #endif
   14541 
   14542 #endif /* SQLITE_MUTEX_OMIT */
   14543 
   14544 /************** End of mutex.c ***********************************************/
   14545 /************** Begin file mutex_noop.c **************************************/
   14546 /*
   14547 ** 2008 October 07
   14548 **
   14549 ** The author disclaims copyright to this source code.  In place of
   14550 ** a legal notice, here is a blessing:
   14551 **
   14552 **    May you do good and not evil.
   14553 **    May you find forgiveness for yourself and forgive others.
   14554 **    May you share freely, never taking more than you give.
   14555 **
   14556 *************************************************************************
   14557 ** This file contains the C functions that implement mutexes.
   14558 **
   14559 ** This implementation in this file does not provide any mutual
   14560 ** exclusion and is thus suitable for use only in applications
   14561 ** that use SQLite in a single thread.  The routines defined
   14562 ** here are place-holders.  Applications can substitute working
   14563 ** mutex routines at start-time using the
   14564 **
   14565 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
   14566 **
   14567 ** interface.
   14568 **
   14569 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
   14570 ** that does error checking on mutexes to make sure they are being
   14571 ** called correctly.
   14572 */
   14573 
   14574 
   14575 #if defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG)
   14576 /*
   14577 ** Stub routines for all mutex methods.
   14578 **
   14579 ** This routines provide no mutual exclusion or error checking.
   14580 */
   14581 static int noopMutexHeld(sqlite3_mutex *p){ return 1; }
   14582 static int noopMutexNotheld(sqlite3_mutex *p){ return 1; }
   14583 static int noopMutexInit(void){ return SQLITE_OK; }
   14584 static int noopMutexEnd(void){ return SQLITE_OK; }
   14585 static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; }
   14586 static void noopMutexFree(sqlite3_mutex *p){ return; }
   14587 static void noopMutexEnter(sqlite3_mutex *p){ return; }
   14588 static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; }
   14589 static void noopMutexLeave(sqlite3_mutex *p){ return; }
   14590 
   14591 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
   14592   static sqlite3_mutex_methods sMutex = {
   14593     noopMutexInit,
   14594     noopMutexEnd,
   14595     noopMutexAlloc,
   14596     noopMutexFree,
   14597     noopMutexEnter,
   14598     noopMutexTry,
   14599     noopMutexLeave,
   14600 
   14601     noopMutexHeld,
   14602     noopMutexNotheld
   14603   };
   14604 
   14605   return &sMutex;
   14606 }
   14607 #endif /* defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG) */
   14608 
   14609 #if defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG)
   14610 /*
   14611 ** In this implementation, error checking is provided for testing
   14612 ** and debugging purposes.  The mutexes still do not provide any
   14613 ** mutual exclusion.
   14614 */
   14615 
   14616 /*
   14617 ** The mutex object
   14618 */
   14619 struct sqlite3_mutex {
   14620   int id;     /* The mutex type */
   14621   int cnt;    /* Number of entries without a matching leave */
   14622 };
   14623 
   14624 /*
   14625 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   14626 ** intended for use inside assert() statements.
   14627 */
   14628 static int debugMutexHeld(sqlite3_mutex *p){
   14629   return p==0 || p->cnt>0;
   14630 }
   14631 static int debugMutexNotheld(sqlite3_mutex *p){
   14632   return p==0 || p->cnt==0;
   14633 }
   14634 
   14635 /*
   14636 ** Initialize and deinitialize the mutex subsystem.
   14637 */
   14638 static int debugMutexInit(void){ return SQLITE_OK; }
   14639 static int debugMutexEnd(void){ return SQLITE_OK; }
   14640 
   14641 /*
   14642 ** The sqlite3_mutex_alloc() routine allocates a new
   14643 ** mutex and returns a pointer to it.  If it returns NULL
   14644 ** that means that a mutex could not be allocated.
   14645 */
   14646 static sqlite3_mutex *debugMutexAlloc(int id){
   14647   static sqlite3_mutex aStatic[6];
   14648   sqlite3_mutex *pNew = 0;
   14649   switch( id ){
   14650     case SQLITE_MUTEX_FAST:
   14651     case SQLITE_MUTEX_RECURSIVE: {
   14652       pNew = sqlite3Malloc(sizeof(*pNew));
   14653       if( pNew ){
   14654         pNew->id = id;
   14655         pNew->cnt = 0;
   14656       }
   14657       break;
   14658     }
   14659     default: {
   14660       assert( id-2 >= 0 );
   14661       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
   14662       pNew = &aStatic[id-2];
   14663       pNew->id = id;
   14664       break;
   14665     }
   14666   }
   14667   return pNew;
   14668 }
   14669 
   14670 /*
   14671 ** This routine deallocates a previously allocated mutex.
   14672 */
   14673 static void debugMutexFree(sqlite3_mutex *p){
   14674   assert( p->cnt==0 );
   14675   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
   14676   sqlite3_free(p);
   14677 }
   14678 
   14679 /*
   14680 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   14681 ** to enter a mutex.  If another thread is already within the mutex,
   14682 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   14683 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   14684 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   14685 ** be entered multiple times by the same thread.  In such cases the,
   14686 ** mutex must be exited an equal number of times before another thread
   14687 ** can enter.  If the same thread tries to enter any other kind of mutex
   14688 ** more than once, the behavior is undefined.
   14689 */
   14690 static void debugMutexEnter(sqlite3_mutex *p){
   14691   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
   14692   p->cnt++;
   14693 }
   14694 static int debugMutexTry(sqlite3_mutex *p){
   14695   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
   14696   p->cnt++;
   14697   return SQLITE_OK;
   14698 }
   14699 
   14700 /*
   14701 ** The sqlite3_mutex_leave() routine exits a mutex that was
   14702 ** previously entered by the same thread.  The behavior
   14703 ** is undefined if the mutex is not currently entered or
   14704 ** is not currently allocated.  SQLite will never do either.
   14705 */
   14706 static void debugMutexLeave(sqlite3_mutex *p){
   14707   assert( debugMutexHeld(p) );
   14708   p->cnt--;
   14709   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
   14710 }
   14711 
   14712 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
   14713   static sqlite3_mutex_methods sMutex = {
   14714     debugMutexInit,
   14715     debugMutexEnd,
   14716     debugMutexAlloc,
   14717     debugMutexFree,
   14718     debugMutexEnter,
   14719     debugMutexTry,
   14720     debugMutexLeave,
   14721 
   14722     debugMutexHeld,
   14723     debugMutexNotheld
   14724   };
   14725 
   14726   return &sMutex;
   14727 }
   14728 #endif /* defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG) */
   14729 
   14730 /************** End of mutex_noop.c ******************************************/
   14731 /************** Begin file mutex_os2.c ***************************************/
   14732 /*
   14733 ** 2007 August 28
   14734 **
   14735 ** The author disclaims copyright to this source code.  In place of
   14736 ** a legal notice, here is a blessing:
   14737 **
   14738 **    May you do good and not evil.
   14739 **    May you find forgiveness for yourself and forgive others.
   14740 **    May you share freely, never taking more than you give.
   14741 **
   14742 *************************************************************************
   14743 ** This file contains the C functions that implement mutexes for OS/2
   14744 */
   14745 
   14746 /*
   14747 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
   14748 ** See the mutex.h file for details.
   14749 */
   14750 #ifdef SQLITE_MUTEX_OS2
   14751 
   14752 /********************** OS/2 Mutex Implementation **********************
   14753 **
   14754 ** This implementation of mutexes is built using the OS/2 API.
   14755 */
   14756 
   14757 /*
   14758 ** The mutex object
   14759 ** Each recursive mutex is an instance of the following structure.
   14760 */
   14761 struct sqlite3_mutex {
   14762   HMTX mutex;       /* Mutex controlling the lock */
   14763   int  id;          /* Mutex type */
   14764   int  nRef;        /* Number of references */
   14765   TID  owner;       /* Thread holding this mutex */
   14766 };
   14767 
   14768 #define OS2_MUTEX_INITIALIZER   0,0,0,0
   14769 
   14770 /*
   14771 ** Initialize and deinitialize the mutex subsystem.
   14772 */
   14773 static int os2MutexInit(void){ return SQLITE_OK; }
   14774 static int os2MutexEnd(void){ return SQLITE_OK; }
   14775 
   14776 /*
   14777 ** The sqlite3_mutex_alloc() routine allocates a new
   14778 ** mutex and returns a pointer to it.  If it returns NULL
   14779 ** that means that a mutex could not be allocated.
   14780 ** SQLite will unwind its stack and return an error.  The argument
   14781 ** to sqlite3_mutex_alloc() is one of these integer constants:
   14782 **
   14783 ** <ul>
   14784 ** <li>  SQLITE_MUTEX_FAST               0
   14785 ** <li>  SQLITE_MUTEX_RECURSIVE          1
   14786 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
   14787 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
   14788 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
   14789 ** </ul>
   14790 **
   14791 ** The first two constants cause sqlite3_mutex_alloc() to create
   14792 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   14793 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   14794 ** The mutex implementation does not need to make a distinction
   14795 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   14796 ** not want to.  But SQLite will only request a recursive mutex in
   14797 ** cases where it really needs one.  If a faster non-recursive mutex
   14798 ** implementation is available on the host platform, the mutex subsystem
   14799 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   14800 **
   14801 ** The other allowed parameters to sqlite3_mutex_alloc() each return
   14802 ** a pointer to a static preexisting mutex.  Three static mutexes are
   14803 ** used by the current version of SQLite.  Future versions of SQLite
   14804 ** may add additional static mutexes.  Static mutexes are for internal
   14805 ** use by SQLite only.  Applications that use SQLite mutexes should
   14806 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   14807 ** SQLITE_MUTEX_RECURSIVE.
   14808 **
   14809 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   14810 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   14811 ** returns a different mutex on every call.  But for the static
   14812 ** mutex types, the same mutex is returned on every call that has
   14813 ** the same type number.
   14814 */
   14815 static sqlite3_mutex *os2MutexAlloc(int iType){
   14816   sqlite3_mutex *p = NULL;
   14817   switch( iType ){
   14818     case SQLITE_MUTEX_FAST:
   14819     case SQLITE_MUTEX_RECURSIVE: {
   14820       p = sqlite3MallocZero( sizeof(*p) );
   14821       if( p ){
   14822         p->id = iType;
   14823         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
   14824           sqlite3_free( p );
   14825           p = NULL;
   14826         }
   14827       }
   14828       break;
   14829     }
   14830     default: {
   14831       static volatile int isInit = 0;
   14832       static sqlite3_mutex staticMutexes[] = {
   14833         { OS2_MUTEX_INITIALIZER, },
   14834         { OS2_MUTEX_INITIALIZER, },
   14835         { OS2_MUTEX_INITIALIZER, },
   14836         { OS2_MUTEX_INITIALIZER, },
   14837         { OS2_MUTEX_INITIALIZER, },
   14838         { OS2_MUTEX_INITIALIZER, },
   14839       };
   14840       if ( !isInit ){
   14841         APIRET rc;
   14842         PTIB ptib;
   14843         PPIB ppib;
   14844         HMTX mutex;
   14845         char name[32];
   14846         DosGetInfoBlocks( &ptib, &ppib );
   14847         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
   14848                           ppib->pib_ulpid );
   14849         while( !isInit ){
   14850           mutex = 0;
   14851           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
   14852           if( rc == NO_ERROR ){
   14853             unsigned int i;
   14854             if( !isInit ){
   14855               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
   14856                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
   14857               }
   14858               isInit = 1;
   14859             }
   14860             DosCloseMutexSem( mutex );
   14861           }else if( rc == ERROR_DUPLICATE_NAME ){
   14862             DosSleep( 1 );
   14863           }else{
   14864             return p;
   14865           }
   14866         }
   14867       }
   14868       assert( iType-2 >= 0 );
   14869       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
   14870       p = &staticMutexes[iType-2];
   14871       p->id = iType;
   14872       break;
   14873     }
   14874   }
   14875   return p;
   14876 }
   14877 
   14878 
   14879 /*
   14880 ** This routine deallocates a previously allocated mutex.
   14881 ** SQLite is careful to deallocate every mutex that it allocates.
   14882 */
   14883 static void os2MutexFree(sqlite3_mutex *p){
   14884   if( p==0 ) return;
   14885   assert( p->nRef==0 );
   14886   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
   14887   DosCloseMutexSem( p->mutex );
   14888   sqlite3_free( p );
   14889 }
   14890 
   14891 #ifdef SQLITE_DEBUG
   14892 /*
   14893 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   14894 ** intended for use inside assert() statements.
   14895 */
   14896 static int os2MutexHeld(sqlite3_mutex *p){
   14897   TID tid;
   14898   PID pid;
   14899   ULONG ulCount;
   14900   PTIB ptib;
   14901   if( p!=0 ) {
   14902     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
   14903   } else {
   14904     DosGetInfoBlocks(&ptib, NULL);
   14905     tid = ptib->tib_ptib2->tib2_ultid;
   14906   }
   14907   return p==0 || (p->nRef!=0 && p->owner==tid);
   14908 }
   14909 static int os2MutexNotheld(sqlite3_mutex *p){
   14910   TID tid;
   14911   PID pid;
   14912   ULONG ulCount;
   14913   PTIB ptib;
   14914   if( p!= 0 ) {
   14915     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
   14916   } else {
   14917     DosGetInfoBlocks(&ptib, NULL);
   14918     tid = ptib->tib_ptib2->tib2_ultid;
   14919   }
   14920   return p==0 || p->nRef==0 || p->owner!=tid;
   14921 }
   14922 #endif
   14923 
   14924 /*
   14925 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   14926 ** to enter a mutex.  If another thread is already within the mutex,
   14927 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   14928 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   14929 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   14930 ** be entered multiple times by the same thread.  In such cases the,
   14931 ** mutex must be exited an equal number of times before another thread
   14932 ** can enter.  If the same thread tries to enter any other kind of mutex
   14933 ** more than once, the behavior is undefined.
   14934 */
   14935 static void os2MutexEnter(sqlite3_mutex *p){
   14936   TID tid;
   14937   PID holder1;
   14938   ULONG holder2;
   14939   if( p==0 ) return;
   14940   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
   14941   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
   14942   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
   14943   p->owner = tid;
   14944   p->nRef++;
   14945 }
   14946 static int os2MutexTry(sqlite3_mutex *p){
   14947   int rc;
   14948   TID tid;
   14949   PID holder1;
   14950   ULONG holder2;
   14951   if( p==0 ) return SQLITE_OK;
   14952   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
   14953   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
   14954     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
   14955     p->owner = tid;
   14956     p->nRef++;
   14957     rc = SQLITE_OK;
   14958   } else {
   14959     rc = SQLITE_BUSY;
   14960   }
   14961 
   14962   return rc;
   14963 }
   14964 
   14965 /*
   14966 ** The sqlite3_mutex_leave() routine exits a mutex that was
   14967 ** previously entered by the same thread.  The behavior
   14968 ** is undefined if the mutex is not currently entered or
   14969 ** is not currently allocated.  SQLite will never do either.
   14970 */
   14971 static void os2MutexLeave(sqlite3_mutex *p){
   14972   TID tid;
   14973   PID holder1;
   14974   ULONG holder2;
   14975   if( p==0 ) return;
   14976   assert( p->nRef>0 );
   14977   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
   14978   assert( p->owner==tid );
   14979   p->nRef--;
   14980   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
   14981   DosReleaseMutexSem(p->mutex);
   14982 }
   14983 
   14984 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
   14985   static sqlite3_mutex_methods sMutex = {
   14986     os2MutexInit,
   14987     os2MutexEnd,
   14988     os2MutexAlloc,
   14989     os2MutexFree,
   14990     os2MutexEnter,
   14991     os2MutexTry,
   14992     os2MutexLeave,
   14993 #ifdef SQLITE_DEBUG
   14994     os2MutexHeld,
   14995     os2MutexNotheld
   14996 #endif
   14997   };
   14998 
   14999   return &sMutex;
   15000 }
   15001 #endif /* SQLITE_MUTEX_OS2 */
   15002 
   15003 /************** End of mutex_os2.c *******************************************/
   15004 /************** Begin file mutex_unix.c **************************************/
   15005 /*
   15006 ** 2007 August 28
   15007 **
   15008 ** The author disclaims copyright to this source code.  In place of
   15009 ** a legal notice, here is a blessing:
   15010 **
   15011 **    May you do good and not evil.
   15012 **    May you find forgiveness for yourself and forgive others.
   15013 **    May you share freely, never taking more than you give.
   15014 **
   15015 *************************************************************************
   15016 ** This file contains the C functions that implement mutexes for pthreads
   15017 */
   15018 
   15019 /*
   15020 ** The code in this file is only used if we are compiling threadsafe
   15021 ** under unix with pthreads.
   15022 **
   15023 ** Note that this implementation requires a version of pthreads that
   15024 ** supports recursive mutexes.
   15025 */
   15026 #ifdef SQLITE_MUTEX_PTHREADS
   15027 
   15028 #include <pthread.h>
   15029 
   15030 
   15031 /*
   15032 ** Each recursive mutex is an instance of the following structure.
   15033 */
   15034 struct sqlite3_mutex {
   15035   pthread_mutex_t mutex;     /* Mutex controlling the lock */
   15036   int id;                    /* Mutex type */
   15037   int nRef;                  /* Number of entrances */
   15038   pthread_t owner;           /* Thread that is within this mutex */
   15039 #ifdef SQLITE_DEBUG
   15040   int trace;                 /* True to trace changes */
   15041 #endif
   15042 };
   15043 #ifdef SQLITE_DEBUG
   15044 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
   15045 #else
   15046 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
   15047 #endif
   15048 
   15049 /*
   15050 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   15051 ** intended for use only inside assert() statements.  On some platforms,
   15052 ** there might be race conditions that can cause these routines to
   15053 ** deliver incorrect results.  In particular, if pthread_equal() is
   15054 ** not an atomic operation, then these routines might delivery
   15055 ** incorrect results.  On most platforms, pthread_equal() is a
   15056 ** comparison of two integers and is therefore atomic.  But we are
   15057 ** told that HPUX is not such a platform.  If so, then these routines
   15058 ** will not always work correctly on HPUX.
   15059 **
   15060 ** On those platforms where pthread_equal() is not atomic, SQLite
   15061 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
   15062 ** make sure no assert() statements are evaluated and hence these
   15063 ** routines are never called.
   15064 */
   15065 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
   15066 static int pthreadMutexHeld(sqlite3_mutex *p){
   15067   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
   15068 }
   15069 static int pthreadMutexNotheld(sqlite3_mutex *p){
   15070   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
   15071 }
   15072 #endif
   15073 
   15074 /*
   15075 ** Initialize and deinitialize the mutex subsystem.
   15076 */
   15077 static int pthreadMutexInit(void){ return SQLITE_OK; }
   15078 static int pthreadMutexEnd(void){ return SQLITE_OK; }
   15079 
   15080 /*
   15081 ** The sqlite3_mutex_alloc() routine allocates a new
   15082 ** mutex and returns a pointer to it.  If it returns NULL
   15083 ** that means that a mutex could not be allocated.  SQLite
   15084 ** will unwind its stack and return an error.  The argument
   15085 ** to sqlite3_mutex_alloc() is one of these integer constants:
   15086 **
   15087 ** <ul>
   15088 ** <li>  SQLITE_MUTEX_FAST
   15089 ** <li>  SQLITE_MUTEX_RECURSIVE
   15090 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   15091 ** <li>  SQLITE_MUTEX_STATIC_MEM
   15092 ** <li>  SQLITE_MUTEX_STATIC_MEM2
   15093 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   15094 ** <li>  SQLITE_MUTEX_STATIC_LRU
   15095 ** <li>  SQLITE_MUTEX_STATIC_LRU2
   15096 ** </ul>
   15097 **
   15098 ** The first two constants cause sqlite3_mutex_alloc() to create
   15099 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   15100 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   15101 ** The mutex implementation does not need to make a distinction
   15102 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   15103 ** not want to.  But SQLite will only request a recursive mutex in
   15104 ** cases where it really needs one.  If a faster non-recursive mutex
   15105 ** implementation is available on the host platform, the mutex subsystem
   15106 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   15107 **
   15108 ** The other allowed parameters to sqlite3_mutex_alloc() each return
   15109 ** a pointer to a static preexisting mutex.  Six static mutexes are
   15110 ** used by the current version of SQLite.  Future versions of SQLite
   15111 ** may add additional static mutexes.  Static mutexes are for internal
   15112 ** use by SQLite only.  Applications that use SQLite mutexes should
   15113 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   15114 ** SQLITE_MUTEX_RECURSIVE.
   15115 **
   15116 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   15117 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   15118 ** returns a different mutex on every call.  But for the static
   15119 ** mutex types, the same mutex is returned on every call that has
   15120 ** the same type number.
   15121 */
   15122 static sqlite3_mutex *pthreadMutexAlloc(int iType){
   15123   static sqlite3_mutex staticMutexes[] = {
   15124     SQLITE3_MUTEX_INITIALIZER,
   15125     SQLITE3_MUTEX_INITIALIZER,
   15126     SQLITE3_MUTEX_INITIALIZER,
   15127     SQLITE3_MUTEX_INITIALIZER,
   15128     SQLITE3_MUTEX_INITIALIZER,
   15129     SQLITE3_MUTEX_INITIALIZER
   15130   };
   15131   sqlite3_mutex *p;
   15132   switch( iType ){
   15133     case SQLITE_MUTEX_RECURSIVE: {
   15134       p = sqlite3MallocZero( sizeof(*p) );
   15135       if( p ){
   15136 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   15137         /* If recursive mutexes are not available, we will have to
   15138         ** build our own.  See below. */
   15139         pthread_mutex_init(&p->mutex, 0);
   15140 #else
   15141         /* Use a recursive mutex if it is available */
   15142         pthread_mutexattr_t recursiveAttr;
   15143         pthread_mutexattr_init(&recursiveAttr);
   15144         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
   15145         pthread_mutex_init(&p->mutex, &recursiveAttr);
   15146         pthread_mutexattr_destroy(&recursiveAttr);
   15147 #endif
   15148         p->id = iType;
   15149       }
   15150       break;
   15151     }
   15152     case SQLITE_MUTEX_FAST: {
   15153       p = sqlite3MallocZero( sizeof(*p) );
   15154       if( p ){
   15155         p->id = iType;
   15156         pthread_mutex_init(&p->mutex, 0);
   15157       }
   15158       break;
   15159     }
   15160     default: {
   15161       assert( iType-2 >= 0 );
   15162       assert( iType-2 < ArraySize(staticMutexes) );
   15163       p = &staticMutexes[iType-2];
   15164       p->id = iType;
   15165       break;
   15166     }
   15167   }
   15168   return p;
   15169 }
   15170 
   15171 
   15172 /*
   15173 ** This routine deallocates a previously
   15174 ** allocated mutex.  SQLite is careful to deallocate every
   15175 ** mutex that it allocates.
   15176 */
   15177 static void pthreadMutexFree(sqlite3_mutex *p){
   15178   assert( p->nRef==0 );
   15179   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
   15180   pthread_mutex_destroy(&p->mutex);
   15181   sqlite3_free(p);
   15182 }
   15183 
   15184 /*
   15185 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   15186 ** to enter a mutex.  If another thread is already within the mutex,
   15187 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   15188 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   15189 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   15190 ** be entered multiple times by the same thread.  In such cases the,
   15191 ** mutex must be exited an equal number of times before another thread
   15192 ** can enter.  If the same thread tries to enter any other kind of mutex
   15193 ** more than once, the behavior is undefined.
   15194 */
   15195 static void pthreadMutexEnter(sqlite3_mutex *p){
   15196   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
   15197 
   15198 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   15199   /* If recursive mutexes are not available, then we have to grow
   15200   ** our own.  This implementation assumes that pthread_equal()
   15201   ** is atomic - that it cannot be deceived into thinking self
   15202   ** and p->owner are equal if p->owner changes between two values
   15203   ** that are not equal to self while the comparison is taking place.
   15204   ** This implementation also assumes a coherent cache - that
   15205   ** separate processes cannot read different values from the same
   15206   ** address at the same time.  If either of these two conditions
   15207   ** are not met, then the mutexes will fail and problems will result.
   15208   */
   15209   {
   15210     pthread_t self = pthread_self();
   15211     if( p->nRef>0 && pthread_equal(p->owner, self) ){
   15212       p->nRef++;
   15213     }else{
   15214       pthread_mutex_lock(&p->mutex);
   15215       assert( p->nRef==0 );
   15216       p->owner = self;
   15217       p->nRef = 1;
   15218     }
   15219   }
   15220 #else
   15221   /* Use the built-in recursive mutexes if they are available.
   15222   */
   15223   pthread_mutex_lock(&p->mutex);
   15224   p->owner = pthread_self();
   15225   p->nRef++;
   15226 #endif
   15227 
   15228 #ifdef SQLITE_DEBUG
   15229   if( p->trace ){
   15230     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   15231   }
   15232 #endif
   15233 }
   15234 static int pthreadMutexTry(sqlite3_mutex *p){
   15235   int rc;
   15236   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
   15237 
   15238 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   15239   /* If recursive mutexes are not available, then we have to grow
   15240   ** our own.  This implementation assumes that pthread_equal()
   15241   ** is atomic - that it cannot be deceived into thinking self
   15242   ** and p->owner are equal if p->owner changes between two values
   15243   ** that are not equal to self while the comparison is taking place.
   15244   ** This implementation also assumes a coherent cache - that
   15245   ** separate processes cannot read different values from the same
   15246   ** address at the same time.  If either of these two conditions
   15247   ** are not met, then the mutexes will fail and problems will result.
   15248   */
   15249   {
   15250     pthread_t self = pthread_self();
   15251     if( p->nRef>0 && pthread_equal(p->owner, self) ){
   15252       p->nRef++;
   15253       rc = SQLITE_OK;
   15254     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
   15255       assert( p->nRef==0 );
   15256       p->owner = self;
   15257       p->nRef = 1;
   15258       rc = SQLITE_OK;
   15259     }else{
   15260       rc = SQLITE_BUSY;
   15261     }
   15262   }
   15263 #else
   15264   /* Use the built-in recursive mutexes if they are available.
   15265   */
   15266   if( pthread_mutex_trylock(&p->mutex)==0 ){
   15267     p->owner = pthread_self();
   15268     p->nRef++;
   15269     rc = SQLITE_OK;
   15270   }else{
   15271     rc = SQLITE_BUSY;
   15272   }
   15273 #endif
   15274 
   15275 #ifdef SQLITE_DEBUG
   15276   if( rc==SQLITE_OK && p->trace ){
   15277     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   15278   }
   15279 #endif
   15280   return rc;
   15281 }
   15282 
   15283 /*
   15284 ** The sqlite3_mutex_leave() routine exits a mutex that was
   15285 ** previously entered by the same thread.  The behavior
   15286 ** is undefined if the mutex is not currently entered or
   15287 ** is not currently allocated.  SQLite will never do either.
   15288 */
   15289 static void pthreadMutexLeave(sqlite3_mutex *p){
   15290   assert( pthreadMutexHeld(p) );
   15291   p->nRef--;
   15292   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
   15293 
   15294 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   15295   if( p->nRef==0 ){
   15296     pthread_mutex_unlock(&p->mutex);
   15297   }
   15298 #else
   15299   pthread_mutex_unlock(&p->mutex);
   15300 #endif
   15301 
   15302 #ifdef SQLITE_DEBUG
   15303   if( p->trace ){
   15304     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   15305   }
   15306 #endif
   15307 }
   15308 
   15309 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
   15310   static sqlite3_mutex_methods sMutex = {
   15311     pthreadMutexInit,
   15312     pthreadMutexEnd,
   15313     pthreadMutexAlloc,
   15314     pthreadMutexFree,
   15315     pthreadMutexEnter,
   15316     pthreadMutexTry,
   15317     pthreadMutexLeave,
   15318 #ifdef SQLITE_DEBUG
   15319     pthreadMutexHeld,
   15320     pthreadMutexNotheld
   15321 #else
   15322     0,
   15323     0
   15324 #endif
   15325   };
   15326 
   15327   return &sMutex;
   15328 }
   15329 
   15330 #endif /* SQLITE_MUTEX_PTHREAD */
   15331 
   15332 /************** End of mutex_unix.c ******************************************/
   15333 /************** Begin file mutex_w32.c ***************************************/
   15334 /*
   15335 ** 2007 August 14
   15336 **
   15337 ** The author disclaims copyright to this source code.  In place of
   15338 ** a legal notice, here is a blessing:
   15339 **
   15340 **    May you do good and not evil.
   15341 **    May you find forgiveness for yourself and forgive others.
   15342 **    May you share freely, never taking more than you give.
   15343 **
   15344 *************************************************************************
   15345 ** This file contains the C functions that implement mutexes for win32
   15346 */
   15347 
   15348 /*
   15349 ** The code in this file is only used if we are compiling multithreaded
   15350 ** on a win32 system.
   15351 */
   15352 #ifdef SQLITE_MUTEX_W32
   15353 
   15354 /*
   15355 ** Each recursive mutex is an instance of the following structure.
   15356 */
   15357 struct sqlite3_mutex {
   15358   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
   15359   int id;                    /* Mutex type */
   15360   int nRef;                  /* Number of enterances */
   15361   DWORD owner;               /* Thread holding this mutex */
   15362 };
   15363 
   15364 /*
   15365 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
   15366 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
   15367 **
   15368 ** Here is an interesting observation:  Win95, Win98, and WinME lack
   15369 ** the LockFileEx() API.  But we can still statically link against that
   15370 ** API as long as we don't call it win running Win95/98/ME.  A call to
   15371 ** this routine is used to determine if the host is Win95/98/ME or
   15372 ** WinNT/2K/XP so that we will know whether or not we can safely call
   15373 ** the LockFileEx() API.
   15374 **
   15375 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
   15376 ** which is only available if your application was compiled with
   15377 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
   15378 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
   15379 ** this out as well.
   15380 */
   15381 #if 0
   15382 #if SQLITE_OS_WINCE
   15383 # define mutexIsNT()  (1)
   15384 #else
   15385   static int mutexIsNT(void){
   15386     static int osType = 0;
   15387     if( osType==0 ){
   15388       OSVERSIONINFO sInfo;
   15389       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
   15390       GetVersionEx(&sInfo);
   15391       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
   15392     }
   15393     return osType==2;
   15394   }
   15395 #endif /* SQLITE_OS_WINCE */
   15396 #endif
   15397 
   15398 #ifdef SQLITE_DEBUG
   15399 /*
   15400 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   15401 ** intended for use only inside assert() statements.
   15402 */
   15403 static int winMutexHeld(sqlite3_mutex *p){
   15404   return p->nRef!=0 && p->owner==GetCurrentThreadId();
   15405 }
   15406 static int winMutexNotheld(sqlite3_mutex *p){
   15407   return p->nRef==0 || p->owner!=GetCurrentThreadId();
   15408 }
   15409 #endif
   15410 
   15411 
   15412 /*
   15413 ** Initialize and deinitialize the mutex subsystem.
   15414 */
   15415 static sqlite3_mutex winMutex_staticMutexes[6];
   15416 static int winMutex_isInit = 0;
   15417 /* As winMutexInit() and winMutexEnd() are called as part
   15418 ** of the sqlite3_initialize and sqlite3_shutdown()
   15419 ** processing, the "interlocked" magic is probably not
   15420 ** strictly necessary.
   15421 */
   15422 static long winMutex_lock = 0;
   15423 
   15424 static int winMutexInit(void){
   15425   /* The first to increment to 1 does actual initialization */
   15426   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
   15427     int i;
   15428     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
   15429       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
   15430     }
   15431     winMutex_isInit = 1;
   15432   }else{
   15433     /* Someone else is in the process of initing the static mutexes */
   15434     while( !winMutex_isInit ){
   15435       Sleep(1);
   15436     }
   15437   }
   15438   return SQLITE_OK;
   15439 }
   15440 
   15441 static int winMutexEnd(void){
   15442   /* The first to decrement to 0 does actual shutdown
   15443   ** (which should be the last to shutdown.) */
   15444   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
   15445     if( winMutex_isInit==1 ){
   15446       int i;
   15447       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
   15448         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
   15449       }
   15450       winMutex_isInit = 0;
   15451     }
   15452   }
   15453   return SQLITE_OK;
   15454 }
   15455 
   15456 /*
   15457 ** The sqlite3_mutex_alloc() routine allocates a new
   15458 ** mutex and returns a pointer to it.  If it returns NULL
   15459 ** that means that a mutex could not be allocated.  SQLite
   15460 ** will unwind its stack and return an error.  The argument
   15461 ** to sqlite3_mutex_alloc() is one of these integer constants:
   15462 **
   15463 ** <ul>
   15464 ** <li>  SQLITE_MUTEX_FAST
   15465 ** <li>  SQLITE_MUTEX_RECURSIVE
   15466 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   15467 ** <li>  SQLITE_MUTEX_STATIC_MEM
   15468 ** <li>  SQLITE_MUTEX_STATIC_MEM2
   15469 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   15470 ** <li>  SQLITE_MUTEX_STATIC_LRU
   15471 ** <li>  SQLITE_MUTEX_STATIC_LRU2
   15472 ** </ul>
   15473 **
   15474 ** The first two constants cause sqlite3_mutex_alloc() to create
   15475 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   15476 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   15477 ** The mutex implementation does not need to make a distinction
   15478 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   15479 ** not want to.  But SQLite will only request a recursive mutex in
   15480 ** cases where it really needs one.  If a faster non-recursive mutex
   15481 ** implementation is available on the host platform, the mutex subsystem
   15482 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   15483 **
   15484 ** The other allowed parameters to sqlite3_mutex_alloc() each return
   15485 ** a pointer to a static preexisting mutex.  Six static mutexes are
   15486 ** used by the current version of SQLite.  Future versions of SQLite
   15487 ** may add additional static mutexes.  Static mutexes are for internal
   15488 ** use by SQLite only.  Applications that use SQLite mutexes should
   15489 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   15490 ** SQLITE_MUTEX_RECURSIVE.
   15491 **
   15492 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   15493 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   15494 ** returns a different mutex on every call.  But for the static
   15495 ** mutex types, the same mutex is returned on every call that has
   15496 ** the same type number.
   15497 */
   15498 static sqlite3_mutex *winMutexAlloc(int iType){
   15499   sqlite3_mutex *p;
   15500 
   15501   switch( iType ){
   15502     case SQLITE_MUTEX_FAST:
   15503     case SQLITE_MUTEX_RECURSIVE: {
   15504       p = sqlite3MallocZero( sizeof(*p) );
   15505       if( p ){
   15506         p->id = iType;
   15507         InitializeCriticalSection(&p->mutex);
   15508       }
   15509       break;
   15510     }
   15511     default: {
   15512       assert( winMutex_isInit==1 );
   15513       assert( iType-2 >= 0 );
   15514       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
   15515       p = &winMutex_staticMutexes[iType-2];
   15516       p->id = iType;
   15517       break;
   15518     }
   15519   }
   15520   return p;
   15521 }
   15522 
   15523 
   15524 /*
   15525 ** This routine deallocates a previously
   15526 ** allocated mutex.  SQLite is careful to deallocate every
   15527 ** mutex that it allocates.
   15528 */
   15529 static void winMutexFree(sqlite3_mutex *p){
   15530   assert( p );
   15531   assert( p->nRef==0 );
   15532   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
   15533   DeleteCriticalSection(&p->mutex);
   15534   sqlite3_free(p);
   15535 }
   15536 
   15537 /*
   15538 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   15539 ** to enter a mutex.  If another thread is already within the mutex,
   15540 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   15541 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   15542 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   15543 ** be entered multiple times by the same thread.  In such cases the,
   15544 ** mutex must be exited an equal number of times before another thread
   15545 ** can enter.  If the same thread tries to enter any other kind of mutex
   15546 ** more than once, the behavior is undefined.
   15547 */
   15548 static void winMutexEnter(sqlite3_mutex *p){
   15549   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
   15550   EnterCriticalSection(&p->mutex);
   15551   p->owner = GetCurrentThreadId();
   15552   p->nRef++;
   15553 }
   15554 static int winMutexTry(sqlite3_mutex *p){
   15555   int rc = SQLITE_BUSY;
   15556   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
   15557   /*
   15558   ** The sqlite3_mutex_try() routine is very rarely used, and when it
   15559   ** is used it is merely an optimization.  So it is OK for it to always
   15560   ** fail.
   15561   **
   15562   ** The TryEnterCriticalSection() interface is only available on WinNT.
   15563   ** And some windows compilers complain if you try to use it without
   15564   ** first doing some #defines that prevent SQLite from building on Win98.
   15565   ** For that reason, we will omit this optimization for now.  See
   15566   ** ticket #2685.
   15567   */
   15568 #if 0
   15569   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
   15570     p->owner = GetCurrentThreadId();
   15571     p->nRef++;
   15572     rc = SQLITE_OK;
   15573   }
   15574 #else
   15575   UNUSED_PARAMETER(p);
   15576 #endif
   15577   return rc;
   15578 }
   15579 
   15580 /*
   15581 ** The sqlite3_mutex_leave() routine exits a mutex that was
   15582 ** previously entered by the same thread.  The behavior
   15583 ** is undefined if the mutex is not currently entered or
   15584 ** is not currently allocated.  SQLite will never do either.
   15585 */
   15586 static void winMutexLeave(sqlite3_mutex *p){
   15587   assert( p->nRef>0 );
   15588   assert( p->owner==GetCurrentThreadId() );
   15589   p->nRef--;
   15590   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
   15591   LeaveCriticalSection(&p->mutex);
   15592 }
   15593 
   15594 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
   15595   static sqlite3_mutex_methods sMutex = {
   15596     winMutexInit,
   15597     winMutexEnd,
   15598     winMutexAlloc,
   15599     winMutexFree,
   15600     winMutexEnter,
   15601     winMutexTry,
   15602     winMutexLeave,
   15603 #ifdef SQLITE_DEBUG
   15604     winMutexHeld,
   15605     winMutexNotheld
   15606 #else
   15607     0,
   15608     0
   15609 #endif
   15610   };
   15611 
   15612   return &sMutex;
   15613 }
   15614 #endif /* SQLITE_MUTEX_W32 */
   15615 
   15616 /************** End of mutex_w32.c *******************************************/
   15617 /************** Begin file malloc.c ******************************************/
   15618 /*
   15619 ** 2001 September 15
   15620 **
   15621 ** The author disclaims copyright to this source code.  In place of
   15622 ** a legal notice, here is a blessing:
   15623 **
   15624 **    May you do good and not evil.
   15625 **    May you find forgiveness for yourself and forgive others.
   15626 **    May you share freely, never taking more than you give.
   15627 **
   15628 *************************************************************************
   15629 **
   15630 ** Memory allocation functions used throughout sqlite.
   15631 */
   15632 
   15633 /*
   15634 ** This routine runs when the memory allocator sees that the
   15635 ** total memory allocation is about to exceed the soft heap
   15636 ** limit.
   15637 */
   15638 static void softHeapLimitEnforcer(
   15639   void *NotUsed,
   15640   sqlite3_int64 NotUsed2,
   15641   int allocSize
   15642 ){
   15643   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   15644   sqlite3_release_memory(allocSize);
   15645 }
   15646 
   15647 /*
   15648 ** Set the soft heap-size limit for the library. Passing a zero or
   15649 ** negative value indicates no limit.
   15650 */
   15651 SQLITE_API void sqlite3_soft_heap_limit(int n){
   15652   sqlite3_uint64 iLimit;
   15653   int overage;
   15654   if( n<0 ){
   15655     iLimit = 0;
   15656   }else{
   15657     iLimit = n;
   15658   }
   15659 #ifndef SQLITE_OMIT_AUTOINIT
   15660   sqlite3_initialize();
   15661 #endif
   15662   if( iLimit>0 ){
   15663     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
   15664   }else{
   15665     sqlite3MemoryAlarm(0, 0, 0);
   15666   }
   15667   overage = (int)(sqlite3_memory_used() - (i64)n);
   15668   if( overage>0 ){
   15669     sqlite3_release_memory(overage);
   15670   }
   15671 }
   15672 
   15673 /*
   15674 ** Attempt to release up to n bytes of non-essential memory currently
   15675 ** held by SQLite. An example of non-essential memory is memory used to
   15676 ** cache database pages that are not currently in use.
   15677 */
   15678 SQLITE_API int sqlite3_release_memory(int n){
   15679 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   15680   int nRet = 0;
   15681   nRet += sqlite3PcacheReleaseMemory(n-nRet);
   15682   return nRet;
   15683 #else
   15684   UNUSED_PARAMETER(n);
   15685   return SQLITE_OK;
   15686 #endif
   15687 }
   15688 
   15689 /*
   15690 ** State information local to the memory allocation subsystem.
   15691 */
   15692 static SQLITE_WSD struct Mem0Global {
   15693   /* Number of free pages for scratch and page-cache memory */
   15694   u32 nScratchFree;
   15695   u32 nPageFree;
   15696 
   15697   sqlite3_mutex *mutex;         /* Mutex to serialize access */
   15698 
   15699   /*
   15700   ** The alarm callback and its arguments.  The mem0.mutex lock will
   15701   ** be held while the callback is running.  Recursive calls into
   15702   ** the memory subsystem are allowed, but no new callbacks will be
   15703   ** issued.
   15704   */
   15705   sqlite3_int64 alarmThreshold;
   15706   void (*alarmCallback)(void*, sqlite3_int64,int);
   15707   void *alarmArg;
   15708 
   15709   /*
   15710   ** Pointers to the end of sqlite3GlobalConfig.pScratch and
   15711   ** sqlite3GlobalConfig.pPage to a block of memory that records
   15712   ** which pages are available.
   15713   */
   15714   u32 *aScratchFree;
   15715   u32 *aPageFree;
   15716 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
   15717 
   15718 #define mem0 GLOBAL(struct Mem0Global, mem0)
   15719 
   15720 /*
   15721 ** Initialize the memory allocation subsystem.
   15722 */
   15723 SQLITE_PRIVATE int sqlite3MallocInit(void){
   15724   if( sqlite3GlobalConfig.m.xMalloc==0 ){
   15725     sqlite3MemSetDefault();
   15726   }
   15727   memset(&mem0, 0, sizeof(mem0));
   15728   if( sqlite3GlobalConfig.bCoreMutex ){
   15729     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   15730   }
   15731   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
   15732       && sqlite3GlobalConfig.nScratch>=0 ){
   15733     int i;
   15734     sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
   15735     mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
   15736                   [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
   15737     for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
   15738     mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
   15739   }else{
   15740     sqlite3GlobalConfig.pScratch = 0;
   15741     sqlite3GlobalConfig.szScratch = 0;
   15742   }
   15743   if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
   15744       && sqlite3GlobalConfig.nPage>=1 ){
   15745     int i;
   15746     int overhead;
   15747     int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
   15748     int n = sqlite3GlobalConfig.nPage;
   15749     overhead = (4*n + sz - 1)/sz;
   15750     sqlite3GlobalConfig.nPage -= overhead;
   15751     mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
   15752                   [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
   15753     for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
   15754     mem0.nPageFree = sqlite3GlobalConfig.nPage;
   15755   }else{
   15756     sqlite3GlobalConfig.pPage = 0;
   15757     sqlite3GlobalConfig.szPage = 0;
   15758   }
   15759   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
   15760 }
   15761 
   15762 /*
   15763 ** Deinitialize the memory allocation subsystem.
   15764 */
   15765 SQLITE_PRIVATE void sqlite3MallocEnd(void){
   15766   if( sqlite3GlobalConfig.m.xShutdown ){
   15767     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
   15768   }
   15769   memset(&mem0, 0, sizeof(mem0));
   15770 }
   15771 
   15772 /*
   15773 ** Return the amount of memory currently checked out.
   15774 */
   15775 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
   15776   int n, mx;
   15777   sqlite3_int64 res;
   15778   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
   15779   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
   15780   return res;
   15781 }
   15782 
   15783 /*
   15784 ** Return the maximum amount of memory that has ever been
   15785 ** checked out since either the beginning of this process
   15786 ** or since the most recent reset.
   15787 */
   15788 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
   15789   int n, mx;
   15790   sqlite3_int64 res;
   15791   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
   15792   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
   15793   return res;
   15794 }
   15795 
   15796 /*
   15797 ** Change the alarm callback
   15798 */
   15799 SQLITE_PRIVATE int sqlite3MemoryAlarm(
   15800   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
   15801   void *pArg,
   15802   sqlite3_int64 iThreshold
   15803 ){
   15804   sqlite3_mutex_enter(mem0.mutex);
   15805   mem0.alarmCallback = xCallback;
   15806   mem0.alarmArg = pArg;
   15807   mem0.alarmThreshold = iThreshold;
   15808   sqlite3_mutex_leave(mem0.mutex);
   15809   return SQLITE_OK;
   15810 }
   15811 
   15812 #ifndef SQLITE_OMIT_DEPRECATED
   15813 /*
   15814 ** Deprecated external interface.  Internal/core SQLite code
   15815 ** should call sqlite3MemoryAlarm.
   15816 */
   15817 SQLITE_API int sqlite3_memory_alarm(
   15818   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
   15819   void *pArg,
   15820   sqlite3_int64 iThreshold
   15821 ){
   15822   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
   15823 }
   15824 #endif
   15825 
   15826 /*
   15827 ** Trigger the alarm
   15828 */
   15829 static void sqlite3MallocAlarm(int nByte){
   15830   void (*xCallback)(void*,sqlite3_int64,int);
   15831   sqlite3_int64 nowUsed;
   15832   void *pArg;
   15833   if( mem0.alarmCallback==0 ) return;
   15834   xCallback = mem0.alarmCallback;
   15835   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
   15836   pArg = mem0.alarmArg;
   15837   mem0.alarmCallback = 0;
   15838   sqlite3_mutex_leave(mem0.mutex);
   15839   xCallback(pArg, nowUsed, nByte);
   15840   sqlite3_mutex_enter(mem0.mutex);
   15841   mem0.alarmCallback = xCallback;
   15842   mem0.alarmArg = pArg;
   15843 }
   15844 
   15845 /*
   15846 ** Do a memory allocation with statistics and alarms.  Assume the
   15847 ** lock is already held.
   15848 */
   15849 static int mallocWithAlarm(int n, void **pp){
   15850   int nFull;
   15851   void *p;
   15852   assert( sqlite3_mutex_held(mem0.mutex) );
   15853   nFull = sqlite3GlobalConfig.m.xRoundup(n);
   15854   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
   15855   if( mem0.alarmCallback!=0 ){
   15856     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
   15857     if( nUsed+nFull >= mem0.alarmThreshold ){
   15858       sqlite3MallocAlarm(nFull);
   15859     }
   15860   }
   15861   p = sqlite3GlobalConfig.m.xMalloc(nFull);
   15862   if( p==0 && mem0.alarmCallback ){
   15863     sqlite3MallocAlarm(nFull);
   15864     p = sqlite3GlobalConfig.m.xMalloc(nFull);
   15865   }
   15866   if( p ){
   15867     nFull = sqlite3MallocSize(p);
   15868     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
   15869   }
   15870   *pp = p;
   15871   return nFull;
   15872 }
   15873 
   15874 /*
   15875 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
   15876 ** assumes the memory subsystem has already been initialized.
   15877 */
   15878 SQLITE_PRIVATE void *sqlite3Malloc(int n){
   15879   void *p;
   15880   if( n<=0 || n>=0x7fffff00 ){
   15881     /* A memory allocation of a number of bytes which is near the maximum
   15882     ** signed integer value might cause an integer overflow inside of the
   15883     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
   15884     ** 255 bytes of overhead.  SQLite itself will never use anything near
   15885     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
   15886     p = 0;
   15887   }else if( sqlite3GlobalConfig.bMemstat ){
   15888     sqlite3_mutex_enter(mem0.mutex);
   15889     mallocWithAlarm(n, &p);
   15890     sqlite3_mutex_leave(mem0.mutex);
   15891   }else{
   15892     p = sqlite3GlobalConfig.m.xMalloc(n);
   15893   }
   15894   return p;
   15895 }
   15896 
   15897 /*
   15898 ** This version of the memory allocation is for use by the application.
   15899 ** First make sure the memory subsystem is initialized, then do the
   15900 ** allocation.
   15901 */
   15902 SQLITE_API void *sqlite3_malloc(int n){
   15903 #ifndef SQLITE_OMIT_AUTOINIT
   15904   if( sqlite3_initialize() ) return 0;
   15905 #endif
   15906   return sqlite3Malloc(n);
   15907 }
   15908 
   15909 /*
   15910 ** Each thread may only have a single outstanding allocation from
   15911 ** xScratchMalloc().  We verify this constraint in the single-threaded
   15912 ** case by setting scratchAllocOut to 1 when an allocation
   15913 ** is outstanding clearing it when the allocation is freed.
   15914 */
   15915 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
   15916 static int scratchAllocOut = 0;
   15917 #endif
   15918 
   15919 
   15920 /*
   15921 ** Allocate memory that is to be used and released right away.
   15922 ** This routine is similar to alloca() in that it is not intended
   15923 ** for situations where the memory might be held long-term.  This
   15924 ** routine is intended to get memory to old large transient data
   15925 ** structures that would not normally fit on the stack of an
   15926 ** embedded processor.
   15927 */
   15928 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
   15929   void *p;
   15930   assert( n>0 );
   15931 
   15932 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
   15933   /* Verify that no more than one scratch allocation per thread
   15934   ** is outstanding at one time.  (This is only checked in the
   15935   ** single-threaded case since checking in the multi-threaded case
   15936   ** would be much more complicated.) */
   15937   assert( scratchAllocOut==0 );
   15938 #endif
   15939 
   15940   if( sqlite3GlobalConfig.szScratch<n ){
   15941     goto scratch_overflow;
   15942   }else{
   15943     sqlite3_mutex_enter(mem0.mutex);
   15944     if( mem0.nScratchFree==0 ){
   15945       sqlite3_mutex_leave(mem0.mutex);
   15946       goto scratch_overflow;
   15947     }else{
   15948       int i;
   15949       i = mem0.aScratchFree[--mem0.nScratchFree];
   15950       i *= sqlite3GlobalConfig.szScratch;
   15951       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
   15952       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
   15953       sqlite3_mutex_leave(mem0.mutex);
   15954       p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
   15955       assert(  (((u8*)p - (u8*)0) & 7)==0 );
   15956     }
   15957   }
   15958 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
   15959   scratchAllocOut = p!=0;
   15960 #endif
   15961 
   15962   return p;
   15963 
   15964 scratch_overflow:
   15965   if( sqlite3GlobalConfig.bMemstat ){
   15966     sqlite3_mutex_enter(mem0.mutex);
   15967     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
   15968     n = mallocWithAlarm(n, &p);
   15969     if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
   15970     sqlite3_mutex_leave(mem0.mutex);
   15971   }else{
   15972     p = sqlite3GlobalConfig.m.xMalloc(n);
   15973   }
   15974 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
   15975   scratchAllocOut = p!=0;
   15976 #endif
   15977   return p;
   15978 }
   15979 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
   15980   if( p ){
   15981 
   15982 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
   15983     /* Verify that no more than one scratch allocation per thread
   15984     ** is outstanding at one time.  (This is only checked in the
   15985     ** single-threaded case since checking in the multi-threaded case
   15986     ** would be much more complicated.) */
   15987     assert( scratchAllocOut==1 );
   15988     scratchAllocOut = 0;
   15989 #endif
   15990 
   15991     if( sqlite3GlobalConfig.pScratch==0
   15992            || p<sqlite3GlobalConfig.pScratch
   15993            || p>=(void*)mem0.aScratchFree ){
   15994       if( sqlite3GlobalConfig.bMemstat ){
   15995         int iSize = sqlite3MallocSize(p);
   15996         sqlite3_mutex_enter(mem0.mutex);
   15997         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
   15998         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
   15999         sqlite3GlobalConfig.m.xFree(p);
   16000         sqlite3_mutex_leave(mem0.mutex);
   16001       }else{
   16002         sqlite3GlobalConfig.m.xFree(p);
   16003       }
   16004     }else{
   16005       int i;
   16006       i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
   16007       i /= sqlite3GlobalConfig.szScratch;
   16008       assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
   16009       sqlite3_mutex_enter(mem0.mutex);
   16010       assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
   16011       mem0.aScratchFree[mem0.nScratchFree++] = i;
   16012       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
   16013       sqlite3_mutex_leave(mem0.mutex);
   16014     }
   16015   }
   16016 }
   16017 
   16018 /*
   16019 ** TRUE if p is a lookaside memory allocation from db
   16020 */
   16021 #ifndef SQLITE_OMIT_LOOKASIDE
   16022 static int isLookaside(sqlite3 *db, void *p){
   16023   return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
   16024 }
   16025 #else
   16026 #define isLookaside(A,B) 0
   16027 #endif
   16028 
   16029 /*
   16030 ** Return the size of a memory allocation previously obtained from
   16031 ** sqlite3Malloc() or sqlite3_malloc().
   16032 */
   16033 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
   16034   return sqlite3GlobalConfig.m.xSize(p);
   16035 }
   16036 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
   16037   assert( db==0 || sqlite3_mutex_held(db->mutex) );
   16038   if( isLookaside(db, p) ){
   16039     return db->lookaside.sz;
   16040   }else{
   16041     return sqlite3GlobalConfig.m.xSize(p);
   16042   }
   16043 }
   16044 
   16045 /*
   16046 ** Free memory previously obtained from sqlite3Malloc().
   16047 */
   16048 SQLITE_API void sqlite3_free(void *p){
   16049   if( p==0 ) return;
   16050   if( sqlite3GlobalConfig.bMemstat ){
   16051     sqlite3_mutex_enter(mem0.mutex);
   16052     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
   16053     sqlite3GlobalConfig.m.xFree(p);
   16054     sqlite3_mutex_leave(mem0.mutex);
   16055   }else{
   16056     sqlite3GlobalConfig.m.xFree(p);
   16057   }
   16058 }
   16059 
   16060 /*
   16061 ** Free memory that might be associated with a particular database
   16062 ** connection.
   16063 */
   16064 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
   16065   assert( db==0 || sqlite3_mutex_held(db->mutex) );
   16066   if( isLookaside(db, p) ){
   16067     LookasideSlot *pBuf = (LookasideSlot*)p;
   16068     pBuf->pNext = db->lookaside.pFree;
   16069     db->lookaside.pFree = pBuf;
   16070     db->lookaside.nOut--;
   16071   }else{
   16072     sqlite3_free(p);
   16073   }
   16074 }
   16075 
   16076 /*
   16077 ** Change the size of an existing memory allocation
   16078 */
   16079 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
   16080   int nOld, nNew;
   16081   void *pNew;
   16082   if( pOld==0 ){
   16083     return sqlite3Malloc(nBytes);
   16084   }
   16085   if( nBytes<=0 ){
   16086     sqlite3_free(pOld);
   16087     return 0;
   16088   }
   16089   if( nBytes>=0x7fffff00 ){
   16090     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
   16091     return 0;
   16092   }
   16093   nOld = sqlite3MallocSize(pOld);
   16094   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
   16095   if( nOld==nNew ){
   16096     pNew = pOld;
   16097   }else if( sqlite3GlobalConfig.bMemstat ){
   16098     sqlite3_mutex_enter(mem0.mutex);
   16099     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
   16100     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
   16101           mem0.alarmThreshold ){
   16102       sqlite3MallocAlarm(nNew-nOld);
   16103     }
   16104     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
   16105     if( pNew==0 && mem0.alarmCallback ){
   16106       sqlite3MallocAlarm(nBytes);
   16107       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
   16108     }
   16109     if( pNew ){
   16110       nNew = sqlite3MallocSize(pNew);
   16111       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
   16112     }
   16113     sqlite3_mutex_leave(mem0.mutex);
   16114   }else{
   16115     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
   16116   }
   16117   return pNew;
   16118 }
   16119 
   16120 /*
   16121 ** The public interface to sqlite3Realloc.  Make sure that the memory
   16122 ** subsystem is initialized prior to invoking sqliteRealloc.
   16123 */
   16124 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
   16125 #ifndef SQLITE_OMIT_AUTOINIT
   16126   if( sqlite3_initialize() ) return 0;
   16127 #endif
   16128   return sqlite3Realloc(pOld, n);
   16129 }
   16130 
   16131 
   16132 /*
   16133 ** Allocate and zero memory.
   16134 */
   16135 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
   16136   void *p = sqlite3Malloc(n);
   16137   if( p ){
   16138     memset(p, 0, n);
   16139   }
   16140   return p;
   16141 }
   16142 
   16143 /*
   16144 ** Allocate and zero memory.  If the allocation fails, make
   16145 ** the mallocFailed flag in the connection pointer.
   16146 */
   16147 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
   16148   void *p = sqlite3DbMallocRaw(db, n);
   16149   if( p ){
   16150     memset(p, 0, n);
   16151   }
   16152   return p;
   16153 }
   16154 
   16155 /*
   16156 ** Allocate and zero memory.  If the allocation fails, make
   16157 ** the mallocFailed flag in the connection pointer.
   16158 **
   16159 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
   16160 ** failure on the same database connection) then always return 0.
   16161 ** Hence for a particular database connection, once malloc starts
   16162 ** failing, it fails consistently until mallocFailed is reset.
   16163 ** This is an important assumption.  There are many places in the
   16164 ** code that do things like this:
   16165 **
   16166 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
   16167 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
   16168 **         if( b ) a[10] = 9;
   16169 **
   16170 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
   16171 ** that all prior mallocs (ex: "a") worked too.
   16172 */
   16173 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
   16174   void *p;
   16175   assert( db==0 || sqlite3_mutex_held(db->mutex) );
   16176 #ifndef SQLITE_OMIT_LOOKASIDE
   16177   if( db ){
   16178     LookasideSlot *pBuf;
   16179     if( db->mallocFailed ){
   16180       return 0;
   16181     }
   16182     if( db->lookaside.bEnabled && n<=db->lookaside.sz
   16183          && (pBuf = db->lookaside.pFree)!=0 ){
   16184       db->lookaside.pFree = pBuf->pNext;
   16185       db->lookaside.nOut++;
   16186       if( db->lookaside.nOut>db->lookaside.mxOut ){
   16187         db->lookaside.mxOut = db->lookaside.nOut;
   16188       }
   16189       return (void*)pBuf;
   16190     }
   16191   }
   16192 #else
   16193   if( db && db->mallocFailed ){
   16194     return 0;
   16195   }
   16196 #endif
   16197   p = sqlite3Malloc(n);
   16198   if( !p && db ){
   16199     db->mallocFailed = 1;
   16200   }
   16201   return p;
   16202 }
   16203 
   16204 /*
   16205 ** Resize the block of memory pointed to by p to n bytes. If the
   16206 ** resize fails, set the mallocFailed flag in the connection object.
   16207 */
   16208 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
   16209   void *pNew = 0;
   16210   assert( db!=0 );
   16211   assert( sqlite3_mutex_held(db->mutex) );
   16212   if( db->mallocFailed==0 ){
   16213     if( p==0 ){
   16214       return sqlite3DbMallocRaw(db, n);
   16215     }
   16216     if( isLookaside(db, p) ){
   16217       if( n<=db->lookaside.sz ){
   16218         return p;
   16219       }
   16220       pNew = sqlite3DbMallocRaw(db, n);
   16221       if( pNew ){
   16222         memcpy(pNew, p, db->lookaside.sz);
   16223         sqlite3DbFree(db, p);
   16224       }
   16225     }else{
   16226       pNew = sqlite3_realloc(p, n);
   16227       if( !pNew ){
   16228         db->mallocFailed = 1;
   16229       }
   16230     }
   16231   }
   16232   return pNew;
   16233 }
   16234 
   16235 /*
   16236 ** Attempt to reallocate p.  If the reallocation fails, then free p
   16237 ** and set the mallocFailed flag in the database connection.
   16238 */
   16239 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
   16240   void *pNew;
   16241   pNew = sqlite3DbRealloc(db, p, n);
   16242   if( !pNew ){
   16243     sqlite3DbFree(db, p);
   16244   }
   16245   return pNew;
   16246 }
   16247 
   16248 /*
   16249 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
   16250 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
   16251 ** is because when memory debugging is turned on, these two functions are
   16252 ** called via macros that record the current file and line number in the
   16253 ** ThreadData structure.
   16254 */
   16255 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
   16256   char *zNew;
   16257   size_t n;
   16258   if( z==0 ){
   16259     return 0;
   16260   }
   16261   n = sqlite3Strlen30(z) + 1;
   16262   assert( (n&0x7fffffff)==n );
   16263   zNew = sqlite3DbMallocRaw(db, (int)n);
   16264   if( zNew ){
   16265     memcpy(zNew, z, n);
   16266   }
   16267   return zNew;
   16268 }
   16269 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
   16270   char *zNew;
   16271   if( z==0 ){
   16272     return 0;
   16273   }
   16274   assert( (n&0x7fffffff)==n );
   16275   zNew = sqlite3DbMallocRaw(db, n+1);
   16276   if( zNew ){
   16277     memcpy(zNew, z, n);
   16278     zNew[n] = 0;
   16279   }
   16280   return zNew;
   16281 }
   16282 
   16283 /*
   16284 ** Create a string from the zFromat argument and the va_list that follows.
   16285 ** Store the string in memory obtained from sqliteMalloc() and make *pz
   16286 ** point to that string.
   16287 */
   16288 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
   16289   va_list ap;
   16290   char *z;
   16291 
   16292   va_start(ap, zFormat);
   16293   z = sqlite3VMPrintf(db, zFormat, ap);
   16294   va_end(ap);
   16295   sqlite3DbFree(db, *pz);
   16296   *pz = z;
   16297 }
   16298 
   16299 
   16300 /*
   16301 ** This function must be called before exiting any API function (i.e.
   16302 ** returning control to the user) that has called sqlite3_malloc or
   16303 ** sqlite3_realloc.
   16304 **
   16305 ** The returned value is normally a copy of the second argument to this
   16306 ** function. However, if a malloc() failure has occurred since the previous
   16307 ** invocation SQLITE_NOMEM is returned instead.
   16308 **
   16309 ** If the first argument, db, is not NULL and a malloc() error has occurred,
   16310 ** then the connection error-code (the value returned by sqlite3_errcode())
   16311 ** is set to SQLITE_NOMEM.
   16312 */
   16313 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
   16314   /* If the db handle is not NULL, then we must hold the connection handle
   16315   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
   16316   ** is unsafe, as is the call to sqlite3Error().
   16317   */
   16318   assert( !db || sqlite3_mutex_held(db->mutex) );
   16319   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
   16320     sqlite3Error(db, SQLITE_NOMEM, 0);
   16321     db->mallocFailed = 0;
   16322     rc = SQLITE_NOMEM;
   16323   }
   16324   return rc & (db ? db->errMask : 0xff);
   16325 }
   16326 
   16327 /************** End of malloc.c **********************************************/
   16328 /************** Begin file printf.c ******************************************/
   16329 /*
   16330 ** The "printf" code that follows dates from the 1980's.  It is in
   16331 ** the public domain.  The original comments are included here for
   16332 ** completeness.  They are very out-of-date but might be useful as
   16333 ** an historical reference.  Most of the "enhancements" have been backed
   16334 ** out so that the functionality is now the same as standard printf().
   16335 **
   16336 **************************************************************************
   16337 **
   16338 ** The following modules is an enhanced replacement for the "printf" subroutines
   16339 ** found in the standard C library.  The following enhancements are
   16340 ** supported:
   16341 **
   16342 **      +  Additional functions.  The standard set of "printf" functions
   16343 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
   16344 **         vsprintf.  This module adds the following:
   16345 **
   16346 **           *  snprintf -- Works like sprintf, but has an extra argument
   16347 **                          which is the size of the buffer written to.
   16348 **
   16349 **           *  mprintf --  Similar to sprintf.  Writes output to memory
   16350 **                          obtained from malloc.
   16351 **
   16352 **           *  xprintf --  Calls a function to dispose of output.
   16353 **
   16354 **           *  nprintf --  No output, but returns the number of characters
   16355 **                          that would have been output by printf.
   16356 **
   16357 **           *  A v- version (ex: vsnprintf) of every function is also
   16358 **              supplied.
   16359 **
   16360 **      +  A few extensions to the formatting notation are supported:
   16361 **
   16362 **           *  The "=" flag (similar to "-") causes the output to be
   16363 **              be centered in the appropriately sized field.
   16364 **
   16365 **           *  The %b field outputs an integer in binary notation.
   16366 **
   16367 **           *  The %c field now accepts a precision.  The character output
   16368 **              is repeated by the number of times the precision specifies.
   16369 **
   16370 **           *  The %' field works like %c, but takes as its character the
   16371 **              next character of the format string, instead of the next
   16372 **              argument.  For example,  printf("%.78'-")  prints 78 minus
   16373 **              signs, the same as  printf("%.78c",'-').
   16374 **
   16375 **      +  When compiled using GCC on a SPARC, this version of printf is
   16376 **         faster than the library printf for SUN OS 4.1.
   16377 **
   16378 **      +  All functions are fully reentrant.
   16379 **
   16380 */
   16381 
   16382 /*
   16383 ** Conversion types fall into various categories as defined by the
   16384 ** following enumeration.
   16385 */
   16386 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
   16387 #define etFLOAT       2 /* Floating point.  %f */
   16388 #define etEXP         3 /* Exponentional notation. %e and %E */
   16389 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
   16390 #define etSIZE        5 /* Return number of characters processed so far. %n */
   16391 #define etSTRING      6 /* Strings. %s */
   16392 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
   16393 #define etPERCENT     8 /* Percent symbol. %% */
   16394 #define etCHARX       9 /* Characters. %c */
   16395 /* The rest are extensions, not normally found in printf() */
   16396 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
   16397 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
   16398                           NULL pointers replaced by SQL NULL.  %Q */
   16399 #define etTOKEN      12 /* a pointer to a Token structure */
   16400 #define etSRCLIST    13 /* a pointer to a SrcList */
   16401 #define etPOINTER    14 /* The %p conversion */
   16402 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
   16403 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
   16404 
   16405 #define etINVALID     0 /* Any unrecognized conversion type */
   16406 
   16407 
   16408 /*
   16409 ** An "etByte" is an 8-bit unsigned value.
   16410 */
   16411 typedef unsigned char etByte;
   16412 
   16413 /*
   16414 ** Each builtin conversion character (ex: the 'd' in "%d") is described
   16415 ** by an instance of the following structure
   16416 */
   16417 typedef struct et_info {   /* Information about each format field */
   16418   char fmttype;            /* The format field code letter */
   16419   etByte base;             /* The base for radix conversion */
   16420   etByte flags;            /* One or more of FLAG_ constants below */
   16421   etByte type;             /* Conversion paradigm */
   16422   etByte charset;          /* Offset into aDigits[] of the digits string */
   16423   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
   16424 } et_info;
   16425 
   16426 /*
   16427 ** Allowed values for et_info.flags
   16428 */
   16429 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
   16430 #define FLAG_INTERN  2     /* True if for internal use only */
   16431 #define FLAG_STRING  4     /* Allow infinity precision */
   16432 
   16433 
   16434 /*
   16435 ** The following table is searched linearly, so it is good to put the
   16436 ** most frequently used conversion types first.
   16437 */
   16438 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
   16439 static const char aPrefix[] = "-x0\000X0";
   16440 static const et_info fmtinfo[] = {
   16441   {  'd', 10, 1, etRADIX,      0,  0 },
   16442   {  's',  0, 4, etSTRING,     0,  0 },
   16443   {  'g',  0, 1, etGENERIC,    30, 0 },
   16444   {  'z',  0, 4, etDYNSTRING,  0,  0 },
   16445   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
   16446   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
   16447   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
   16448   {  'c',  0, 0, etCHARX,      0,  0 },
   16449   {  'o',  8, 0, etRADIX,      0,  2 },
   16450   {  'u', 10, 0, etRADIX,      0,  0 },
   16451   {  'x', 16, 0, etRADIX,      16, 1 },
   16452   {  'X', 16, 0, etRADIX,      0,  4 },
   16453 #ifndef SQLITE_OMIT_FLOATING_POINT
   16454   {  'f',  0, 1, etFLOAT,      0,  0 },
   16455   {  'e',  0, 1, etEXP,        30, 0 },
   16456   {  'E',  0, 1, etEXP,        14, 0 },
   16457   {  'G',  0, 1, etGENERIC,    14, 0 },
   16458 #endif
   16459   {  'i', 10, 1, etRADIX,      0,  0 },
   16460   {  'n',  0, 0, etSIZE,       0,  0 },
   16461   {  '%',  0, 0, etPERCENT,    0,  0 },
   16462   {  'p', 16, 0, etPOINTER,    0,  1 },
   16463 
   16464 /* All the rest have the FLAG_INTERN bit set and are thus for internal
   16465 ** use only */
   16466   {  'T',  0, 2, etTOKEN,      0,  0 },
   16467   {  'S',  0, 2, etSRCLIST,    0,  0 },
   16468   {  'r', 10, 3, etORDINAL,    0,  0 },
   16469 };
   16470 
   16471 /*
   16472 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
   16473 ** conversions will work.
   16474 */
   16475 #ifndef SQLITE_OMIT_FLOATING_POINT
   16476 /*
   16477 ** "*val" is a double such that 0.1 <= *val < 10.0
   16478 ** Return the ascii code for the leading digit of *val, then
   16479 ** multiply "*val" by 10.0 to renormalize.
   16480 **
   16481 ** Example:
   16482 **     input:     *val = 3.14159
   16483 **     output:    *val = 1.4159    function return = '3'
   16484 **
   16485 ** The counter *cnt is incremented each time.  After counter exceeds
   16486 ** 16 (the number of significant digits in a 64-bit float) '0' is
   16487 ** always returned.
   16488 */
   16489 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
   16490   int digit;
   16491   LONGDOUBLE_TYPE d;
   16492   if( (*cnt)++ >= 16 ) return '0';
   16493   digit = (int)*val;
   16494   d = digit;
   16495   digit += '0';
   16496   *val = (*val - d)*10.0;
   16497   return (char)digit;
   16498 }
   16499 #endif /* SQLITE_OMIT_FLOATING_POINT */
   16500 
   16501 /*
   16502 ** Append N space characters to the given string buffer.
   16503 */
   16504 static void appendSpace(StrAccum *pAccum, int N){
   16505   static const char zSpaces[] = "                             ";
   16506   while( N>=(int)sizeof(zSpaces)-1 ){
   16507     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
   16508     N -= sizeof(zSpaces)-1;
   16509   }
   16510   if( N>0 ){
   16511     sqlite3StrAccumAppend(pAccum, zSpaces, N);
   16512   }
   16513 }
   16514 
   16515 /*
   16516 ** On machines with a small stack size, you can redefine the
   16517 ** SQLITE_PRINT_BUF_SIZE to be less than 350.
   16518 */
   16519 #ifndef SQLITE_PRINT_BUF_SIZE
   16520 # if defined(SQLITE_SMALL_STACK)
   16521 #   define SQLITE_PRINT_BUF_SIZE 50
   16522 # else
   16523 #   define SQLITE_PRINT_BUF_SIZE 350
   16524 # endif
   16525 #endif
   16526 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
   16527 
   16528 /*
   16529 ** The root program.  All variations call this core.
   16530 **
   16531 ** INPUTS:
   16532 **   func   This is a pointer to a function taking three arguments
   16533 **            1. A pointer to anything.  Same as the "arg" parameter.
   16534 **            2. A pointer to the list of characters to be output
   16535 **               (Note, this list is NOT null terminated.)
   16536 **            3. An integer number of characters to be output.
   16537 **               (Note: This number might be zero.)
   16538 **
   16539 **   arg    This is the pointer to anything which will be passed as the
   16540 **          first argument to "func".  Use it for whatever you like.
   16541 **
   16542 **   fmt    This is the format string, as in the usual print.
   16543 **
   16544 **   ap     This is a pointer to a list of arguments.  Same as in
   16545 **          vfprint.
   16546 **
   16547 ** OUTPUTS:
   16548 **          The return value is the total number of characters sent to
   16549 **          the function "func".  Returns -1 on a error.
   16550 **
   16551 ** Note that the order in which automatic variables are declared below
   16552 ** seems to make a big difference in determining how fast this beast
   16553 ** will run.
   16554 */
   16555 SQLITE_PRIVATE void sqlite3VXPrintf(
   16556   StrAccum *pAccum,                  /* Accumulate results here */
   16557   int useExtended,                   /* Allow extended %-conversions */
   16558   const char *fmt,                   /* Format string */
   16559   va_list ap                         /* arguments */
   16560 ){
   16561   int c;                     /* Next character in the format string */
   16562   char *bufpt;               /* Pointer to the conversion buffer */
   16563   int precision;             /* Precision of the current field */
   16564   int length;                /* Length of the field */
   16565   int idx;                   /* A general purpose loop counter */
   16566   int width;                 /* Width of the current field */
   16567   etByte flag_leftjustify;   /* True if "-" flag is present */
   16568   etByte flag_plussign;      /* True if "+" flag is present */
   16569   etByte flag_blanksign;     /* True if " " flag is present */
   16570   etByte flag_alternateform; /* True if "#" flag is present */
   16571   etByte flag_altform2;      /* True if "!" flag is present */
   16572   etByte flag_zeropad;       /* True if field width constant starts with zero */
   16573   etByte flag_long;          /* True if "l" flag is present */
   16574   etByte flag_longlong;      /* True if the "ll" flag is present */
   16575   etByte done;               /* Loop termination flag */
   16576   sqlite_uint64 longvalue;   /* Value for integer types */
   16577   LONGDOUBLE_TYPE realvalue; /* Value for real types */
   16578   const et_info *infop;      /* Pointer to the appropriate info structure */
   16579   char buf[etBUFSIZE];       /* Conversion buffer */
   16580   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
   16581   etByte xtype = 0;          /* Conversion paradigm */
   16582   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
   16583 #ifndef SQLITE_OMIT_FLOATING_POINT
   16584   int  exp, e2;              /* exponent of real numbers */
   16585   double rounder;            /* Used for rounding floating point values */
   16586   etByte flag_dp;            /* True if decimal point should be shown */
   16587   etByte flag_rtz;           /* True if trailing zeros should be removed */
   16588   etByte flag_exp;           /* True to force display of the exponent */
   16589   int nsd;                   /* Number of significant digits returned */
   16590 #endif
   16591 
   16592   length = 0;
   16593   bufpt = 0;
   16594   for(; (c=(*fmt))!=0; ++fmt){
   16595     if( c!='%' ){
   16596       int amt;
   16597       bufpt = (char *)fmt;
   16598       amt = 1;
   16599       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
   16600       sqlite3StrAccumAppend(pAccum, bufpt, amt);
   16601       if( c==0 ) break;
   16602     }
   16603     if( (c=(*++fmt))==0 ){
   16604       sqlite3StrAccumAppend(pAccum, "%", 1);
   16605       break;
   16606     }
   16607     /* Find out what flags are present */
   16608     flag_leftjustify = flag_plussign = flag_blanksign =
   16609      flag_alternateform = flag_altform2 = flag_zeropad = 0;
   16610     done = 0;
   16611     do{
   16612       switch( c ){
   16613         case '-':   flag_leftjustify = 1;     break;
   16614         case '+':   flag_plussign = 1;        break;
   16615         case ' ':   flag_blanksign = 1;       break;
   16616         case '#':   flag_alternateform = 1;   break;
   16617         case '!':   flag_altform2 = 1;        break;
   16618         case '0':   flag_zeropad = 1;         break;
   16619         default:    done = 1;                 break;
   16620       }
   16621     }while( !done && (c=(*++fmt))!=0 );
   16622     /* Get the field width */
   16623     width = 0;
   16624     if( c=='*' ){
   16625       width = va_arg(ap,int);
   16626       if( width<0 ){
   16627         flag_leftjustify = 1;
   16628         width = -width;
   16629       }
   16630       c = *++fmt;
   16631     }else{
   16632       while( c>='0' && c<='9' ){
   16633         width = width*10 + c - '0';
   16634         c = *++fmt;
   16635       }
   16636     }
   16637     if( width > etBUFSIZE-10 ){
   16638       width = etBUFSIZE-10;
   16639     }
   16640     /* Get the precision */
   16641     if( c=='.' ){
   16642       precision = 0;
   16643       c = *++fmt;
   16644       if( c=='*' ){
   16645         precision = va_arg(ap,int);
   16646         if( precision<0 ) precision = -precision;
   16647         c = *++fmt;
   16648       }else{
   16649         while( c>='0' && c<='9' ){
   16650           precision = precision*10 + c - '0';
   16651           c = *++fmt;
   16652         }
   16653       }
   16654     }else{
   16655       precision = -1;
   16656     }
   16657     /* Get the conversion type modifier */
   16658     if( c=='l' ){
   16659       flag_long = 1;
   16660       c = *++fmt;
   16661       if( c=='l' ){
   16662         flag_longlong = 1;
   16663         c = *++fmt;
   16664       }else{
   16665         flag_longlong = 0;
   16666       }
   16667     }else{
   16668       flag_long = flag_longlong = 0;
   16669     }
   16670     /* Fetch the info entry for the field */
   16671     infop = &fmtinfo[0];
   16672     xtype = etINVALID;
   16673     for(idx=0; idx<ArraySize(fmtinfo); idx++){
   16674       if( c==fmtinfo[idx].fmttype ){
   16675         infop = &fmtinfo[idx];
   16676         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
   16677           xtype = infop->type;
   16678         }else{
   16679           return;
   16680         }
   16681         break;
   16682       }
   16683     }
   16684     zExtra = 0;
   16685 
   16686 
   16687     /* Limit the precision to prevent overflowing buf[] during conversion */
   16688     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
   16689       precision = etBUFSIZE-40;
   16690     }
   16691 
   16692     /*
   16693     ** At this point, variables are initialized as follows:
   16694     **
   16695     **   flag_alternateform          TRUE if a '#' is present.
   16696     **   flag_altform2               TRUE if a '!' is present.
   16697     **   flag_plussign               TRUE if a '+' is present.
   16698     **   flag_leftjustify            TRUE if a '-' is present or if the
   16699     **                               field width was negative.
   16700     **   flag_zeropad                TRUE if the width began with 0.
   16701     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
   16702     **                               the conversion character.
   16703     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
   16704     **                               the conversion character.
   16705     **   flag_blanksign              TRUE if a ' ' is present.
   16706     **   width                       The specified field width.  This is
   16707     **                               always non-negative.  Zero is the default.
   16708     **   precision                   The specified precision.  The default
   16709     **                               is -1.
   16710     **   xtype                       The class of the conversion.
   16711     **   infop                       Pointer to the appropriate info struct.
   16712     */
   16713     switch( xtype ){
   16714       case etPOINTER:
   16715         flag_longlong = sizeof(char*)==sizeof(i64);
   16716         flag_long = sizeof(char*)==sizeof(long int);
   16717         /* Fall through into the next case */
   16718       case etORDINAL:
   16719       case etRADIX:
   16720         if( infop->flags & FLAG_SIGNED ){
   16721           i64 v;
   16722           if( flag_longlong ){
   16723             v = va_arg(ap,i64);
   16724           }else if( flag_long ){
   16725             v = va_arg(ap,long int);
   16726           }else{
   16727             v = va_arg(ap,int);
   16728           }
   16729           if( v<0 ){
   16730             longvalue = -v;
   16731             prefix = '-';
   16732           }else{
   16733             longvalue = v;
   16734             if( flag_plussign )        prefix = '+';
   16735             else if( flag_blanksign )  prefix = ' ';
   16736             else                       prefix = 0;
   16737           }
   16738         }else{
   16739           if( flag_longlong ){
   16740             longvalue = va_arg(ap,u64);
   16741           }else if( flag_long ){
   16742             longvalue = va_arg(ap,unsigned long int);
   16743           }else{
   16744             longvalue = va_arg(ap,unsigned int);
   16745           }
   16746           prefix = 0;
   16747         }
   16748         if( longvalue==0 ) flag_alternateform = 0;
   16749         if( flag_zeropad && precision<width-(prefix!=0) ){
   16750           precision = width-(prefix!=0);
   16751         }
   16752         bufpt = &buf[etBUFSIZE-1];
   16753         if( xtype==etORDINAL ){
   16754           static const char zOrd[] = "thstndrd";
   16755           int x = (int)(longvalue % 10);
   16756           if( x>=4 || (longvalue/10)%10==1 ){
   16757             x = 0;
   16758           }
   16759           buf[etBUFSIZE-3] = zOrd[x*2];
   16760           buf[etBUFSIZE-2] = zOrd[x*2+1];
   16761           bufpt -= 2;
   16762         }
   16763         {
   16764           register const char *cset;      /* Use registers for speed */
   16765           register int base;
   16766           cset = &aDigits[infop->charset];
   16767           base = infop->base;
   16768           do{                                           /* Convert to ascii */
   16769             *(--bufpt) = cset[longvalue%base];
   16770             longvalue = longvalue/base;
   16771           }while( longvalue>0 );
   16772         }
   16773         length = (int)(&buf[etBUFSIZE-1]-bufpt);
   16774         for(idx=precision-length; idx>0; idx--){
   16775           *(--bufpt) = '0';                             /* Zero pad */
   16776         }
   16777         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
   16778         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
   16779           const char *pre;
   16780           char x;
   16781           pre = &aPrefix[infop->prefix];
   16782           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
   16783         }
   16784         length = (int)(&buf[etBUFSIZE-1]-bufpt);
   16785         break;
   16786       case etFLOAT:
   16787       case etEXP:
   16788       case etGENERIC:
   16789         realvalue = va_arg(ap,double);
   16790 #ifndef SQLITE_OMIT_FLOATING_POINT
   16791         if( precision<0 ) precision = 6;         /* Set default precision */
   16792         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
   16793         if( realvalue<0.0 ){
   16794           realvalue = -realvalue;
   16795           prefix = '-';
   16796         }else{
   16797           if( flag_plussign )          prefix = '+';
   16798           else if( flag_blanksign )    prefix = ' ';
   16799           else                         prefix = 0;
   16800         }
   16801         if( xtype==etGENERIC && precision>0 ) precision--;
   16802 #if 0
   16803         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
   16804         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
   16805 #else
   16806         /* It makes more sense to use 0.5 */
   16807         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
   16808 #endif
   16809         if( xtype==etFLOAT ) realvalue += rounder;
   16810         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
   16811         exp = 0;
   16812         if( sqlite3IsNaN((double)realvalue) ){
   16813           bufpt = "NaN";
   16814           length = 3;
   16815           break;
   16816         }
   16817         if( realvalue>0.0 ){
   16818           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
   16819           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
   16820           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
   16821           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
   16822           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
   16823           if( exp>350 ){
   16824             if( prefix=='-' ){
   16825               bufpt = "-Inf";
   16826             }else if( prefix=='+' ){
   16827               bufpt = "+Inf";
   16828             }else{
   16829               bufpt = "Inf";
   16830             }
   16831             length = sqlite3Strlen30(bufpt);
   16832             break;
   16833           }
   16834         }
   16835         bufpt = buf;
   16836         /*
   16837         ** If the field type is etGENERIC, then convert to either etEXP
   16838         ** or etFLOAT, as appropriate.
   16839         */
   16840         flag_exp = xtype==etEXP;
   16841         if( xtype!=etFLOAT ){
   16842           realvalue += rounder;
   16843           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
   16844         }
   16845         if( xtype==etGENERIC ){
   16846           flag_rtz = !flag_alternateform;
   16847           if( exp<-4 || exp>precision ){
   16848             xtype = etEXP;
   16849           }else{
   16850             precision = precision - exp;
   16851             xtype = etFLOAT;
   16852           }
   16853         }else{
   16854           flag_rtz = 0;
   16855         }
   16856         if( xtype==etEXP ){
   16857           e2 = 0;
   16858         }else{
   16859           e2 = exp;
   16860         }
   16861         nsd = 0;
   16862         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
   16863         /* The sign in front of the number */
   16864         if( prefix ){
   16865           *(bufpt++) = prefix;
   16866         }
   16867         /* Digits prior to the decimal point */
   16868         if( e2<0 ){
   16869           *(bufpt++) = '0';
   16870         }else{
   16871           for(; e2>=0; e2--){
   16872             *(bufpt++) = et_getdigit(&realvalue,&nsd);
   16873           }
   16874         }
   16875         /* The decimal point */
   16876         if( flag_dp ){
   16877           *(bufpt++) = '.';
   16878         }
   16879         /* "0" digits after the decimal point but before the first
   16880         ** significant digit of the number */
   16881         for(e2++; e2<0; precision--, e2++){
   16882           assert( precision>0 );
   16883           *(bufpt++) = '0';
   16884         }
   16885         /* Significant digits after the decimal point */
   16886         while( (precision--)>0 ){
   16887           *(bufpt++) = et_getdigit(&realvalue,&nsd);
   16888         }
   16889         /* Remove trailing zeros and the "." if no digits follow the "." */
   16890         if( flag_rtz && flag_dp ){
   16891           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
   16892           assert( bufpt>buf );
   16893           if( bufpt[-1]=='.' ){
   16894             if( flag_altform2 ){
   16895               *(bufpt++) = '0';
   16896             }else{
   16897               *(--bufpt) = 0;
   16898             }
   16899           }
   16900         }
   16901         /* Add the "eNNN" suffix */
   16902         if( flag_exp || xtype==etEXP ){
   16903           *(bufpt++) = aDigits[infop->charset];
   16904           if( exp<0 ){
   16905             *(bufpt++) = '-'; exp = -exp;
   16906           }else{
   16907             *(bufpt++) = '+';
   16908           }
   16909           if( exp>=100 ){
   16910             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
   16911             exp %= 100;
   16912           }
   16913           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
   16914           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
   16915         }
   16916         *bufpt = 0;
   16917 
   16918         /* The converted number is in buf[] and zero terminated. Output it.
   16919         ** Note that the number is in the usual order, not reversed as with
   16920         ** integer conversions. */
   16921         length = (int)(bufpt-buf);
   16922         bufpt = buf;
   16923 
   16924         /* Special case:  Add leading zeros if the flag_zeropad flag is
   16925         ** set and we are not left justified */
   16926         if( flag_zeropad && !flag_leftjustify && length < width){
   16927           int i;
   16928           int nPad = width - length;
   16929           for(i=width; i>=nPad; i--){
   16930             bufpt[i] = bufpt[i-nPad];
   16931           }
   16932           i = prefix!=0;
   16933           while( nPad-- ) bufpt[i++] = '0';
   16934           length = width;
   16935         }
   16936 #endif
   16937         break;
   16938       case etSIZE:
   16939         *(va_arg(ap,int*)) = pAccum->nChar;
   16940         length = width = 0;
   16941         break;
   16942       case etPERCENT:
   16943         buf[0] = '%';
   16944         bufpt = buf;
   16945         length = 1;
   16946         break;
   16947       case etCHARX:
   16948         c = va_arg(ap,int);
   16949         buf[0] = (char)c;
   16950         if( precision>=0 ){
   16951           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
   16952           length = precision;
   16953         }else{
   16954           length =1;
   16955         }
   16956         bufpt = buf;
   16957         break;
   16958       case etSTRING:
   16959       case etDYNSTRING:
   16960         bufpt = va_arg(ap,char*);
   16961         if( bufpt==0 ){
   16962           bufpt = "";
   16963         }else if( xtype==etDYNSTRING ){
   16964           zExtra = bufpt;
   16965         }
   16966         if( precision>=0 ){
   16967           for(length=0; length<precision && bufpt[length]; length++){}
   16968         }else{
   16969           length = sqlite3Strlen30(bufpt);
   16970         }
   16971         break;
   16972       case etSQLESCAPE:
   16973       case etSQLESCAPE2:
   16974       case etSQLESCAPE3: {
   16975         int i, j, k, n, isnull;
   16976         int needQuote;
   16977         char ch;
   16978         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
   16979         char *escarg = va_arg(ap,char*);
   16980         isnull = escarg==0;
   16981         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
   16982         k = precision;
   16983         for(i=n=0; (ch=escarg[i])!=0 && k!=0; i++, k--){
   16984           if( ch==q )  n++;
   16985         }
   16986         needQuote = !isnull && xtype==etSQLESCAPE2;
   16987         n += i + 1 + needQuote*2;
   16988         if( n>etBUFSIZE ){
   16989           bufpt = zExtra = sqlite3Malloc( n );
   16990           if( bufpt==0 ){
   16991             pAccum->mallocFailed = 1;
   16992             return;
   16993           }
   16994         }else{
   16995           bufpt = buf;
   16996         }
   16997         j = 0;
   16998         if( needQuote ) bufpt[j++] = q;
   16999         k = i;
   17000         for(i=0; i<k; i++){
   17001           bufpt[j++] = ch = escarg[i];
   17002           if( ch==q ) bufpt[j++] = ch;
   17003         }
   17004         if( needQuote ) bufpt[j++] = q;
   17005         bufpt[j] = 0;
   17006         length = j;
   17007         /* The precision in %q and %Q means how many input characters to
   17008         ** consume, not the length of the output...
   17009         ** if( precision>=0 && precision<length ) length = precision; */
   17010         break;
   17011       }
   17012       case etTOKEN: {
   17013         Token *pToken = va_arg(ap, Token*);
   17014         if( pToken ){
   17015           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
   17016         }
   17017         length = width = 0;
   17018         break;
   17019       }
   17020       case etSRCLIST: {
   17021         SrcList *pSrc = va_arg(ap, SrcList*);
   17022         int k = va_arg(ap, int);
   17023         struct SrcList_item *pItem = &pSrc->a[k];
   17024         assert( k>=0 && k<pSrc->nSrc );
   17025         if( pItem->zDatabase ){
   17026           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
   17027           sqlite3StrAccumAppend(pAccum, ".", 1);
   17028         }
   17029         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
   17030         length = width = 0;
   17031         break;
   17032       }
   17033       default: {
   17034         assert( xtype==etINVALID );
   17035         return;
   17036       }
   17037     }/* End switch over the format type */
   17038     /*
   17039     ** The text of the conversion is pointed to by "bufpt" and is
   17040     ** "length" characters long.  The field width is "width".  Do
   17041     ** the output.
   17042     */
   17043     if( !flag_leftjustify ){
   17044       register int nspace;
   17045       nspace = width-length;
   17046       if( nspace>0 ){
   17047         appendSpace(pAccum, nspace);
   17048       }
   17049     }
   17050     if( length>0 ){
   17051       sqlite3StrAccumAppend(pAccum, bufpt, length);
   17052     }
   17053     if( flag_leftjustify ){
   17054       register int nspace;
   17055       nspace = width-length;
   17056       if( nspace>0 ){
   17057         appendSpace(pAccum, nspace);
   17058       }
   17059     }
   17060     if( zExtra ){
   17061       sqlite3_free(zExtra);
   17062     }
   17063   }/* End for loop over the format string */
   17064 } /* End of function */
   17065 
   17066 /*
   17067 ** Append N bytes of text from z to the StrAccum object.
   17068 */
   17069 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
   17070   assert( z!=0 || N==0 );
   17071   if( p->tooBig | p->mallocFailed ){
   17072     testcase(p->tooBig);
   17073     testcase(p->mallocFailed);
   17074     return;
   17075   }
   17076   if( N<0 ){
   17077     N = sqlite3Strlen30(z);
   17078   }
   17079   if( N==0 || NEVER(z==0) ){
   17080     return;
   17081   }
   17082   if( p->nChar+N >= p->nAlloc ){
   17083     char *zNew;
   17084     if( !p->useMalloc ){
   17085       p->tooBig = 1;
   17086       N = p->nAlloc - p->nChar - 1;
   17087       if( N<=0 ){
   17088         return;
   17089       }
   17090     }else{
   17091       i64 szNew = p->nChar;
   17092       szNew += N + 1;
   17093       if( szNew > p->mxAlloc ){
   17094         sqlite3StrAccumReset(p);
   17095         p->tooBig = 1;
   17096         return;
   17097       }else{
   17098         p->nAlloc = (int)szNew;
   17099       }
   17100       zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
   17101       if( zNew ){
   17102         memcpy(zNew, p->zText, p->nChar);
   17103         sqlite3StrAccumReset(p);
   17104         p->zText = zNew;
   17105       }else{
   17106         p->mallocFailed = 1;
   17107         sqlite3StrAccumReset(p);
   17108         return;
   17109       }
   17110     }
   17111   }
   17112   memcpy(&p->zText[p->nChar], z, N);
   17113   p->nChar += N;
   17114 }
   17115 
   17116 /*
   17117 ** Finish off a string by making sure it is zero-terminated.
   17118 ** Return a pointer to the resulting string.  Return a NULL
   17119 ** pointer if any kind of error was encountered.
   17120 */
   17121 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
   17122   if( p->zText ){
   17123     p->zText[p->nChar] = 0;
   17124     if( p->useMalloc && p->zText==p->zBase ){
   17125       p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
   17126       if( p->zText ){
   17127         memcpy(p->zText, p->zBase, p->nChar+1);
   17128       }else{
   17129         p->mallocFailed = 1;
   17130       }
   17131     }
   17132   }
   17133   return p->zText;
   17134 }
   17135 
   17136 /*
   17137 ** Reset an StrAccum string.  Reclaim all malloced memory.
   17138 */
   17139 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
   17140   if( p->zText!=p->zBase ){
   17141     sqlite3DbFree(p->db, p->zText);
   17142   }
   17143   p->zText = 0;
   17144 }
   17145 
   17146 /*
   17147 ** Initialize a string accumulator
   17148 */
   17149 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
   17150   p->zText = p->zBase = zBase;
   17151   p->db = 0;
   17152   p->nChar = 0;
   17153   p->nAlloc = n;
   17154   p->mxAlloc = mx;
   17155   p->useMalloc = 1;
   17156   p->tooBig = 0;
   17157   p->mallocFailed = 0;
   17158 }
   17159 
   17160 /*
   17161 ** Print into memory obtained from sqliteMalloc().  Use the internal
   17162 ** %-conversion extensions.
   17163 */
   17164 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
   17165   char *z;
   17166   char zBase[SQLITE_PRINT_BUF_SIZE];
   17167   StrAccum acc;
   17168   assert( db!=0 );
   17169   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
   17170                       db->aLimit[SQLITE_LIMIT_LENGTH]);
   17171   acc.db = db;
   17172   sqlite3VXPrintf(&acc, 1, zFormat, ap);
   17173   z = sqlite3StrAccumFinish(&acc);
   17174   if( acc.mallocFailed ){
   17175     db->mallocFailed = 1;
   17176   }
   17177   return z;
   17178 }
   17179 
   17180 /*
   17181 ** Print into memory obtained from sqliteMalloc().  Use the internal
   17182 ** %-conversion extensions.
   17183 */
   17184 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
   17185   va_list ap;
   17186   char *z;
   17187   va_start(ap, zFormat);
   17188   z = sqlite3VMPrintf(db, zFormat, ap);
   17189   va_end(ap);
   17190   return z;
   17191 }
   17192 
   17193 /*
   17194 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
   17195 ** the string and before returnning.  This routine is intended to be used
   17196 ** to modify an existing string.  For example:
   17197 **
   17198 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
   17199 **
   17200 */
   17201 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
   17202   va_list ap;
   17203   char *z;
   17204   va_start(ap, zFormat);
   17205   z = sqlite3VMPrintf(db, zFormat, ap);
   17206   va_end(ap);
   17207   sqlite3DbFree(db, zStr);
   17208   return z;
   17209 }
   17210 
   17211 /*
   17212 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
   17213 ** %-conversion extensions.
   17214 */
   17215 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
   17216   char *z;
   17217   char zBase[SQLITE_PRINT_BUF_SIZE];
   17218   StrAccum acc;
   17219 #ifndef SQLITE_OMIT_AUTOINIT
   17220   if( sqlite3_initialize() ) return 0;
   17221 #endif
   17222   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
   17223   sqlite3VXPrintf(&acc, 0, zFormat, ap);
   17224   z = sqlite3StrAccumFinish(&acc);
   17225   return z;
   17226 }
   17227 
   17228 /*
   17229 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
   17230 ** %-conversion extensions.
   17231 */
   17232 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
   17233   va_list ap;
   17234   char *z;
   17235 #ifndef SQLITE_OMIT_AUTOINIT
   17236   if( sqlite3_initialize() ) return 0;
   17237 #endif
   17238   va_start(ap, zFormat);
   17239   z = sqlite3_vmprintf(zFormat, ap);
   17240   va_end(ap);
   17241   return z;
   17242 }
   17243 
   17244 /*
   17245 ** sqlite3_snprintf() works like snprintf() except that it ignores the
   17246 ** current locale settings.  This is important for SQLite because we
   17247 ** are not able to use a "," as the decimal point in place of "." as
   17248 ** specified by some locales.
   17249 */
   17250 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
   17251   char *z;
   17252   va_list ap;
   17253   StrAccum acc;
   17254 
   17255   if( n<=0 ){
   17256     return zBuf;
   17257   }
   17258   sqlite3StrAccumInit(&acc, zBuf, n, 0);
   17259   acc.useMalloc = 0;
   17260   va_start(ap,zFormat);
   17261   sqlite3VXPrintf(&acc, 0, zFormat, ap);
   17262   va_end(ap);
   17263   z = sqlite3StrAccumFinish(&acc);
   17264   return z;
   17265 }
   17266 
   17267 /*
   17268 ** This is the routine that actually formats the sqlite3_log() message.
   17269 ** We house it in a separate routine from sqlite3_log() to avoid using
   17270 ** stack space on small-stack systems when logging is disabled.
   17271 **
   17272 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
   17273 ** allocate memory because it might be called while the memory allocator
   17274 ** mutex is held.
   17275 */
   17276 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
   17277   StrAccum acc;                           /* String accumulator */
   17278 #ifdef SQLITE_SMALL_STACK
   17279   char zMsg[150];                         /* Complete log message */
   17280 #else
   17281   char zMsg[400];                         /* Complete log message */
   17282 #endif
   17283 
   17284   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
   17285   acc.useMalloc = 0;
   17286   sqlite3VXPrintf(&acc, 0, zFormat, ap);
   17287   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
   17288                            sqlite3StrAccumFinish(&acc));
   17289 }
   17290 
   17291 /*
   17292 ** Format and write a message to the log if logging is enabled.
   17293 */
   17294 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
   17295   va_list ap;                             /* Vararg list */
   17296   if( sqlite3GlobalConfig.xLog ){
   17297     va_start(ap, zFormat);
   17298     renderLogMsg(iErrCode, zFormat, ap);
   17299     va_end(ap);
   17300   }
   17301 }
   17302 
   17303 #if defined(SQLITE_DEBUG)
   17304 /*
   17305 ** A version of printf() that understands %lld.  Used for debugging.
   17306 ** The printf() built into some versions of windows does not understand %lld
   17307 ** and segfaults if you give it a long long int.
   17308 */
   17309 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
   17310   va_list ap;
   17311   StrAccum acc;
   17312   char zBuf[500];
   17313   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
   17314   acc.useMalloc = 0;
   17315   va_start(ap,zFormat);
   17316   sqlite3VXPrintf(&acc, 0, zFormat, ap);
   17317   va_end(ap);
   17318   sqlite3StrAccumFinish(&acc);
   17319   fprintf(stdout,"%s", zBuf);
   17320   fflush(stdout);
   17321 }
   17322 #endif
   17323 
   17324 #ifndef SQLITE_OMIT_TRACE
   17325 /*
   17326 ** variable-argument wrapper around sqlite3VXPrintf().
   17327 */
   17328 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
   17329   va_list ap;
   17330   va_start(ap,zFormat);
   17331   sqlite3VXPrintf(p, 1, zFormat, ap);
   17332   va_end(ap);
   17333 }
   17334 #endif
   17335 
   17336 /************** End of printf.c **********************************************/
   17337 /************** Begin file random.c ******************************************/
   17338 /*
   17339 ** 2001 September 15
   17340 **
   17341 ** The author disclaims copyright to this source code.  In place of
   17342 ** a legal notice, here is a blessing:
   17343 **
   17344 **    May you do good and not evil.
   17345 **    May you find forgiveness for yourself and forgive others.
   17346 **    May you share freely, never taking more than you give.
   17347 **
   17348 *************************************************************************
   17349 ** This file contains code to implement a pseudo-random number
   17350 ** generator (PRNG) for SQLite.
   17351 **
   17352 ** Random numbers are used by some of the database backends in order
   17353 ** to generate random integer keys for tables or random filenames.
   17354 */
   17355 
   17356 
   17357 /* All threads share a single random number generator.
   17358 ** This structure is the current state of the generator.
   17359 */
   17360 static SQLITE_WSD struct sqlite3PrngType {
   17361   unsigned char isInit;          /* True if initialized */
   17362   unsigned char i, j;            /* State variables */
   17363   unsigned char s[256];          /* State variables */
   17364 } sqlite3Prng;
   17365 
   17366 /*
   17367 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
   17368 ** must be held while executing this routine.
   17369 **
   17370 ** Why not just use a library random generator like lrand48() for this?
   17371 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
   17372 ** good source of random numbers.  The lrand48() library function may
   17373 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
   17374 ** subtle problems on some systems that could cause problems.  It is hard
   17375 ** to know.  To minimize the risk of problems due to bad lrand48()
   17376 ** implementations, SQLite uses this random number generator based
   17377 ** on RC4, which we know works very well.
   17378 **
   17379 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
   17380 ** randomness any more.  But we will leave this code in all the same.
   17381 */
   17382 static u8 randomByte(void){
   17383   unsigned char t;
   17384 
   17385 
   17386   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
   17387   ** state vector.  If writable static data is unsupported on the target,
   17388   ** we have to locate the state vector at run-time.  In the more common
   17389   ** case where writable static data is supported, wsdPrng can refer directly
   17390   ** to the "sqlite3Prng" state vector declared above.
   17391   */
   17392 #ifdef SQLITE_OMIT_WSD
   17393   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
   17394 # define wsdPrng p[0]
   17395 #else
   17396 # define wsdPrng sqlite3Prng
   17397 #endif
   17398 
   17399 
   17400   /* Initialize the state of the random number generator once,
   17401   ** the first time this routine is called.  The seed value does
   17402   ** not need to contain a lot of randomness since we are not
   17403   ** trying to do secure encryption or anything like that...
   17404   **
   17405   ** Nothing in this file or anywhere else in SQLite does any kind of
   17406   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
   17407   ** number generator) not as an encryption device.
   17408   */
   17409   if( !wsdPrng.isInit ){
   17410     int i;
   17411     char k[256];
   17412     wsdPrng.j = 0;
   17413     wsdPrng.i = 0;
   17414     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
   17415     for(i=0; i<256; i++){
   17416       wsdPrng.s[i] = (u8)i;
   17417     }
   17418     for(i=0; i<256; i++){
   17419       wsdPrng.j += wsdPrng.s[i] + k[i];
   17420       t = wsdPrng.s[wsdPrng.j];
   17421       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
   17422       wsdPrng.s[i] = t;
   17423     }
   17424     wsdPrng.isInit = 1;
   17425   }
   17426 
   17427   /* Generate and return single random byte
   17428   */
   17429   wsdPrng.i++;
   17430   t = wsdPrng.s[wsdPrng.i];
   17431   wsdPrng.j += t;
   17432   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
   17433   wsdPrng.s[wsdPrng.j] = t;
   17434   t += wsdPrng.s[wsdPrng.i];
   17435   return wsdPrng.s[t];
   17436 }
   17437 
   17438 /*
   17439 ** Return N random bytes.
   17440 */
   17441 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
   17442   unsigned char *zBuf = pBuf;
   17443 #if SQLITE_THREADSAFE
   17444   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
   17445 #endif
   17446   sqlite3_mutex_enter(mutex);
   17447   while( N-- ){
   17448     *(zBuf++) = randomByte();
   17449   }
   17450   sqlite3_mutex_leave(mutex);
   17451 }
   17452 
   17453 #ifndef SQLITE_OMIT_BUILTIN_TEST
   17454 /*
   17455 ** For testing purposes, we sometimes want to preserve the state of
   17456 ** PRNG and restore the PRNG to its saved state at a later time, or
   17457 ** to reset the PRNG to its initial state.  These routines accomplish
   17458 ** those tasks.
   17459 **
   17460 ** The sqlite3_test_control() interface calls these routines to
   17461 ** control the PRNG.
   17462 */
   17463 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
   17464 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
   17465   memcpy(
   17466     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
   17467     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
   17468     sizeof(sqlite3Prng)
   17469   );
   17470 }
   17471 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
   17472   memcpy(
   17473     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
   17474     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
   17475     sizeof(sqlite3Prng)
   17476   );
   17477 }
   17478 SQLITE_PRIVATE void sqlite3PrngResetState(void){
   17479   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
   17480 }
   17481 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   17482 
   17483 /************** End of random.c **********************************************/
   17484 /************** Begin file utf.c *********************************************/
   17485 /*
   17486 ** 2004 April 13
   17487 **
   17488 ** The author disclaims copyright to this source code.  In place of
   17489 ** a legal notice, here is a blessing:
   17490 **
   17491 **    May you do good and not evil.
   17492 **    May you find forgiveness for yourself and forgive others.
   17493 **    May you share freely, never taking more than you give.
   17494 **
   17495 *************************************************************************
   17496 ** This file contains routines used to translate between UTF-8,
   17497 ** UTF-16, UTF-16BE, and UTF-16LE.
   17498 **
   17499 ** Notes on UTF-8:
   17500 **
   17501 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
   17502 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
   17503 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
   17504 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
   17505 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
   17506 **
   17507 **
   17508 ** Notes on UTF-16:  (with wwww+1==uuuuu)
   17509 **
   17510 **      Word-0               Word-1          Value
   17511 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
   17512 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
   17513 **
   17514 **
   17515 ** BOM or Byte Order Mark:
   17516 **     0xff 0xfe   little-endian utf-16 follows
   17517 **     0xfe 0xff   big-endian utf-16 follows
   17518 **
   17519 */
   17520 /************** Include vdbeInt.h in the middle of utf.c *********************/
   17521 /************** Begin file vdbeInt.h *****************************************/
   17522 /*
   17523 ** 2003 September 6
   17524 **
   17525 ** The author disclaims copyright to this source code.  In place of
   17526 ** a legal notice, here is a blessing:
   17527 **
   17528 **    May you do good and not evil.
   17529 **    May you find forgiveness for yourself and forgive others.
   17530 **    May you share freely, never taking more than you give.
   17531 **
   17532 *************************************************************************
   17533 ** This is the header file for information that is private to the
   17534 ** VDBE.  This information used to all be at the top of the single
   17535 ** source code file "vdbe.c".  When that file became too big (over
   17536 ** 6000 lines long) it was split up into several smaller files and
   17537 ** this header information was factored out.
   17538 */
   17539 #ifndef _VDBEINT_H_
   17540 #define _VDBEINT_H_
   17541 
   17542 /*
   17543 ** SQL is translated into a sequence of instructions to be
   17544 ** executed by a virtual machine.  Each instruction is an instance
   17545 ** of the following structure.
   17546 */
   17547 typedef struct VdbeOp Op;
   17548 
   17549 /*
   17550 ** Boolean values
   17551 */
   17552 typedef unsigned char Bool;
   17553 
   17554 /*
   17555 ** A cursor is a pointer into a single BTree within a database file.
   17556 ** The cursor can seek to a BTree entry with a particular key, or
   17557 ** loop over all entries of the Btree.  You can also insert new BTree
   17558 ** entries or retrieve the key or data from the entry that the cursor
   17559 ** is currently pointing to.
   17560 **
   17561 ** Every cursor that the virtual machine has open is represented by an
   17562 ** instance of the following structure.
   17563 **
   17564 ** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
   17565 ** really a single row that represents the NEW or OLD pseudo-table of
   17566 ** a row trigger.  The data for the row is stored in VdbeCursor.pData and
   17567 ** the rowid is in VdbeCursor.iKey.
   17568 */
   17569 struct VdbeCursor {
   17570   BtCursor *pCursor;    /* The cursor structure of the backend */
   17571   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
   17572   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
   17573   Bool zeroed;          /* True if zeroed out and ready for reuse */
   17574   Bool rowidIsValid;    /* True if lastRowid is valid */
   17575   Bool atFirst;         /* True if pointing to first entry */
   17576   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
   17577   Bool nullRow;         /* True if pointing to a row with no data */
   17578   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
   17579   Bool isTable;         /* True if a table requiring integer keys */
   17580   Bool isIndex;         /* True if an index containing keys only - no data */
   17581   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
   17582   Btree *pBt;           /* Separate file holding temporary table */
   17583   int pseudoTableReg;   /* Register holding pseudotable content. */
   17584   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
   17585   int nField;           /* Number of fields in the header */
   17586   i64 seqCount;         /* Sequence counter */
   17587   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
   17588   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
   17589 
   17590   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
   17591   ** OP_IsUnique opcode on this cursor. */
   17592   int seekResult;
   17593 
   17594   /* Cached information about the header for the data record that the
   17595   ** cursor is currently pointing to.  Only valid if cacheStatus matches
   17596   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
   17597   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
   17598   ** the cache is out of date.
   17599   **
   17600   ** aRow might point to (ephemeral) data for the current row, or it might
   17601   ** be NULL.
   17602   */
   17603   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
   17604   int payloadSize;      /* Total number of bytes in the record */
   17605   u32 *aType;           /* Type values for all entries in the record */
   17606   u32 *aOffset;         /* Cached offsets to the start of each columns data */
   17607   u8 *aRow;             /* Data for the current row, if all on one page */
   17608 };
   17609 typedef struct VdbeCursor VdbeCursor;
   17610 
   17611 /*
   17612 ** When a sub-program is executed (OP_Program), a structure of this type
   17613 ** is allocated to store the current value of the program counter, as
   17614 ** well as the current memory cell array and various other frame specific
   17615 ** values stored in the Vdbe struct. When the sub-program is finished,
   17616 ** these values are copied back to the Vdbe from the VdbeFrame structure,
   17617 ** restoring the state of the VM to as it was before the sub-program
   17618 ** began executing.
   17619 **
   17620 ** Frames are stored in a linked list headed at Vdbe.pParent. Vdbe.pParent
   17621 ** is the parent of the current frame, or zero if the current frame
   17622 ** is the main Vdbe program.
   17623 */
   17624 typedef struct VdbeFrame VdbeFrame;
   17625 struct VdbeFrame {
   17626   Vdbe *v;                /* VM this frame belongs to */
   17627   int pc;                 /* Program Counter */
   17628   Op *aOp;                /* Program instructions */
   17629   int nOp;                /* Size of aOp array */
   17630   Mem *aMem;              /* Array of memory cells */
   17631   int nMem;               /* Number of entries in aMem */
   17632   VdbeCursor **apCsr;     /* Element of Vdbe cursors */
   17633   u16 nCursor;            /* Number of entries in apCsr */
   17634   void *token;            /* Copy of SubProgram.token */
   17635   int nChildMem;          /* Number of memory cells for child frame */
   17636   int nChildCsr;          /* Number of cursors for child frame */
   17637   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
   17638   int nChange;            /* Statement changes (Vdbe.nChanges)     */
   17639   VdbeFrame *pParent;     /* Parent of this frame */
   17640 };
   17641 
   17642 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
   17643 
   17644 /*
   17645 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
   17646 */
   17647 #define CACHE_STALE 0
   17648 
   17649 /*
   17650 ** Internally, the vdbe manipulates nearly all SQL values as Mem
   17651 ** structures. Each Mem struct may cache multiple representations (string,
   17652 ** integer etc.) of the same value.  A value (and therefore Mem structure)
   17653 ** has the following properties:
   17654 **
   17655 ** Each value has a manifest type. The manifest type of the value stored
   17656 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
   17657 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
   17658 ** SQLITE_BLOB.
   17659 */
   17660 struct Mem {
   17661   union {
   17662     i64 i;              /* Integer value. */
   17663     int nZero;          /* Used when bit MEM_Zero is set in flags */
   17664     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
   17665     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
   17666     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
   17667   } u;
   17668   double r;           /* Real value */
   17669   sqlite3 *db;        /* The associated database connection */
   17670   char *z;            /* String or BLOB value */
   17671   int n;              /* Number of characters in string value, excluding '\0' */
   17672   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
   17673   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
   17674   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
   17675   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
   17676   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
   17677 };
   17678 
   17679 /* One or more of the following flags are set to indicate the validOK
   17680 ** representations of the value stored in the Mem struct.
   17681 **
   17682 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
   17683 ** No other flags may be set in this case.
   17684 **
   17685 ** If the MEM_Str flag is set then Mem.z points at a string representation.
   17686 ** Usually this is encoded in the same unicode encoding as the main
   17687 ** database (see below for exceptions). If the MEM_Term flag is also
   17688 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
   17689 ** flags may coexist with the MEM_Str flag.
   17690 **
   17691 ** Multiple of these values can appear in Mem.flags.  But only one
   17692 ** at a time can appear in Mem.type.
   17693 */
   17694 #define MEM_Null      0x0001   /* Value is NULL */
   17695 #define MEM_Str       0x0002   /* Value is a string */
   17696 #define MEM_Int       0x0004   /* Value is an integer */
   17697 #define MEM_Real      0x0008   /* Value is a real number */
   17698 #define MEM_Blob      0x0010   /* Value is a BLOB */
   17699 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
   17700 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
   17701 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
   17702 
   17703 /* Whenever Mem contains a valid string or blob representation, one of
   17704 ** the following flags must be set to determine the memory management
   17705 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
   17706 ** string is \000 or \u0000 terminated
   17707 */
   17708 #define MEM_Term      0x0200   /* String rep is nul terminated */
   17709 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
   17710 #define MEM_Static    0x0800   /* Mem.z points to a static string */
   17711 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
   17712 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
   17713 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
   17714 
   17715 #ifdef SQLITE_OMIT_INCRBLOB
   17716   #undef MEM_Zero
   17717   #define MEM_Zero 0x0000
   17718 #endif
   17719 
   17720 
   17721 /*
   17722 ** Clear any existing type flags from a Mem and replace them with f
   17723 */
   17724 #define MemSetTypeFlag(p, f) \
   17725    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
   17726 
   17727 
   17728 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
   17729 ** additional information about auxiliary information bound to arguments
   17730 ** of the function.  This is used to implement the sqlite3_get_auxdata()
   17731 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
   17732 ** that can be associated with a constant argument to a function.  This
   17733 ** allows functions such as "regexp" to compile their constant regular
   17734 ** expression argument once and reused the compiled code for multiple
   17735 ** invocations.
   17736 */
   17737 struct VdbeFunc {
   17738   FuncDef *pFunc;               /* The definition of the function */
   17739   int nAux;                     /* Number of entries allocated for apAux[] */
   17740   struct AuxData {
   17741     void *pAux;                   /* Aux data for the i-th argument */
   17742     void (*xDelete)(void *);      /* Destructor for the aux data */
   17743   } apAux[1];                   /* One slot for each function argument */
   17744 };
   17745 
   17746 /*
   17747 ** The "context" argument for a installable function.  A pointer to an
   17748 ** instance of this structure is the first argument to the routines used
   17749 ** implement the SQL functions.
   17750 **
   17751 ** There is a typedef for this structure in sqlite.h.  So all routines,
   17752 ** even the public interface to SQLite, can use a pointer to this structure.
   17753 ** But this file is the only place where the internal details of this
   17754 ** structure are known.
   17755 **
   17756 ** This structure is defined inside of vdbeInt.h because it uses substructures
   17757 ** (Mem) which are only defined there.
   17758 */
   17759 struct sqlite3_context {
   17760   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
   17761   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
   17762   Mem s;                /* The return value is stored here */
   17763   Mem *pMem;            /* Memory cell used to store aggregate context */
   17764   int isError;          /* Error code returned by the function. */
   17765   CollSeq *pColl;       /* Collating sequence */
   17766 };
   17767 
   17768 /*
   17769 ** A Set structure is used for quick testing to see if a value
   17770 ** is part of a small set.  Sets are used to implement code like
   17771 ** this:
   17772 **            x.y IN ('hi','hoo','hum')
   17773 */
   17774 typedef struct Set Set;
   17775 struct Set {
   17776   Hash hash;             /* A set is just a hash table */
   17777   HashElem *prev;        /* Previously accessed hash elemen */
   17778 };
   17779 
   17780 /*
   17781 ** An instance of the virtual machine.  This structure contains the complete
   17782 ** state of the virtual machine.
   17783 **
   17784 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
   17785 ** is really a pointer to an instance of this structure.
   17786 **
   17787 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
   17788 ** any virtual table method invocations made by the vdbe program. It is
   17789 ** set to 2 for xDestroy method calls and 1 for all other methods. This
   17790 ** variable is used for two purposes: to allow xDestroy methods to execute
   17791 ** "DROP TABLE" statements and to prevent some nasty side effects of
   17792 ** malloc failure when SQLite is invoked recursively by a virtual table
   17793 ** method function.
   17794 */
   17795 struct Vdbe {
   17796   sqlite3 *db;            /* The database connection that owns this statement */
   17797   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
   17798   int nOp;                /* Number of instructions in the program */
   17799   int nOpAlloc;           /* Number of slots allocated for aOp[] */
   17800   Op *aOp;                /* Space to hold the virtual machine's program */
   17801   int nLabel;             /* Number of labels used */
   17802   int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
   17803   int *aLabel;            /* Space to hold the labels */
   17804   Mem **apArg;            /* Arguments to currently executing user function */
   17805   Mem *aColName;          /* Column names to return */
   17806   Mem *pResultSet;        /* Pointer to an array of results */
   17807   u16 nResColumn;         /* Number of columns in one row of the result set */
   17808   u16 nCursor;            /* Number of slots in apCsr[] */
   17809   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
   17810   u8 errorAction;         /* Recovery action to do in case of an error */
   17811   u8 okVar;               /* True if azVar[] has been initialized */
   17812   ynVar nVar;             /* Number of entries in aVar[] */
   17813   Mem *aVar;              /* Values for the OP_Variable opcode. */
   17814   char **azVar;           /* Name of variables */
   17815   u32 magic;              /* Magic number for sanity checking */
   17816   int nMem;               /* Number of memory locations currently allocated */
   17817   Mem *aMem;              /* The memory locations */
   17818   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
   17819   int pc;                 /* The program counter */
   17820   int rc;                 /* Value to return */
   17821   char *zErrMsg;          /* Error message written here */
   17822   u8 explain;             /* True if EXPLAIN present on SQL command */
   17823   u8 changeCntOn;         /* True to update the change-counter */
   17824   u8 expired;             /* True if the VM needs to be recompiled */
   17825   u8 runOnlyOnce;         /* Automatically expire on reset */
   17826   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
   17827   u8 inVtabMethod;        /* See comments above */
   17828   u8 usesStmtJournal;     /* True if uses a statement journal */
   17829   u8 readOnly;            /* True for read-only statements */
   17830   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
   17831   int nChange;            /* Number of db changes made since last reset */
   17832   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
   17833   i64 startTime;          /* Time when query started - used for profiling */
   17834   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
   17835   int aCounter[2];        /* Counters used by sqlite3_stmt_status() */
   17836   char *zSql;             /* Text of the SQL statement that generated this */
   17837   void *pFree;            /* Free this when deleting the vdbe */
   17838   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
   17839   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
   17840   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
   17841 #ifdef SQLITE_DEBUG
   17842   FILE *trace;            /* Write an execution trace here, if not NULL */
   17843 #endif
   17844   VdbeFrame *pFrame;      /* Parent frame */
   17845   int nFrame;             /* Number of frames in pFrame list */
   17846   u32 expmask;            /* Binding to these vars invalidates VM */
   17847 };
   17848 
   17849 /*
   17850 ** The following are allowed values for Vdbe.magic
   17851 */
   17852 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
   17853 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
   17854 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
   17855 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
   17856 
   17857 /*
   17858 ** Function prototypes
   17859 */
   17860 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
   17861 void sqliteVdbePopStack(Vdbe*,int);
   17862 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
   17863 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
   17864 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
   17865 #endif
   17866 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
   17867 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
   17868 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
   17869 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
   17870 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
   17871 
   17872 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
   17873 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
   17874 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
   17875 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
   17876 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
   17877 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
   17878 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
   17879 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
   17880 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
   17881 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
   17882 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
   17883 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
   17884 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
   17885 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
   17886 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
   17887 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
   17888 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
   17889 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
   17890 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
   17891 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
   17892 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
   17893 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
   17894 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
   17895 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
   17896 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
   17897 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
   17898 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
   17899 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
   17900 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
   17901 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
   17902 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
   17903 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
   17904 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
   17905 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
   17906 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
   17907 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
   17908 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
   17909 
   17910 #ifndef SQLITE_OMIT_FOREIGN_KEY
   17911 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
   17912 #else
   17913 # define sqlite3VdbeCheckFk(p,i) 0
   17914 #endif
   17915 
   17916 #ifndef SQLITE_OMIT_SHARED_CACHE
   17917 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p);
   17918 #else
   17919 # define sqlite3VdbeMutexArrayEnter(p)
   17920 #endif
   17921 
   17922 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
   17923 #ifdef SQLITE_DEBUG
   17924 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
   17925 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
   17926 #endif
   17927 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
   17928 
   17929 #ifndef SQLITE_OMIT_INCRBLOB
   17930 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
   17931 #else
   17932   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
   17933 #endif
   17934 
   17935 #endif /* !defined(_VDBEINT_H_) */
   17936 
   17937 /************** End of vdbeInt.h *********************************************/
   17938 /************** Continuing where we left off in utf.c ************************/
   17939 
   17940 #ifndef SQLITE_AMALGAMATION
   17941 /*
   17942 ** The following constant value is used by the SQLITE_BIGENDIAN and
   17943 ** SQLITE_LITTLEENDIAN macros.
   17944 */
   17945 SQLITE_PRIVATE const int sqlite3one = 1;
   17946 #endif /* SQLITE_AMALGAMATION */
   17947 
   17948 /*
   17949 ** This lookup table is used to help decode the first byte of
   17950 ** a multi-byte UTF8 character.
   17951 */
   17952 static const unsigned char sqlite3Utf8Trans1[] = {
   17953   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   17954   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   17955   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
   17956   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
   17957   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   17958   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   17959   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   17960   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
   17961 };
   17962 
   17963 
   17964 #define WRITE_UTF8(zOut, c) {                          \
   17965   if( c<0x00080 ){                                     \
   17966     *zOut++ = (u8)(c&0xFF);                            \
   17967   }                                                    \
   17968   else if( c<0x00800 ){                                \
   17969     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
   17970     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   17971   }                                                    \
   17972   else if( c<0x10000 ){                                \
   17973     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
   17974     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
   17975     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   17976   }else{                                               \
   17977     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
   17978     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
   17979     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
   17980     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   17981   }                                                    \
   17982 }
   17983 
   17984 #define WRITE_UTF16LE(zOut, c) {                                    \
   17985   if( c<=0xFFFF ){                                                  \
   17986     *zOut++ = (u8)(c&0x00FF);                                       \
   17987     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
   17988   }else{                                                            \
   17989     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
   17990     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
   17991     *zOut++ = (u8)(c&0x00FF);                                       \
   17992     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
   17993   }                                                                 \
   17994 }
   17995 
   17996 #define WRITE_UTF16BE(zOut, c) {                                    \
   17997   if( c<=0xFFFF ){                                                  \
   17998     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
   17999     *zOut++ = (u8)(c&0x00FF);                                       \
   18000   }else{                                                            \
   18001     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
   18002     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
   18003     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
   18004     *zOut++ = (u8)(c&0x00FF);                                       \
   18005   }                                                                 \
   18006 }
   18007 
   18008 #define READ_UTF16LE(zIn, TERM, c){                                   \
   18009   c = (*zIn++);                                                       \
   18010   c += ((*zIn++)<<8);                                                 \
   18011   if( c>=0xD800 && c<0xE000 && TERM ){                                \
   18012     int c2 = (*zIn++);                                                \
   18013     c2 += ((*zIn++)<<8);                                              \
   18014     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
   18015   }                                                                   \
   18016 }
   18017 
   18018 #define READ_UTF16BE(zIn, TERM, c){                                   \
   18019   c = ((*zIn++)<<8);                                                  \
   18020   c += (*zIn++);                                                      \
   18021   if( c>=0xD800 && c<0xE000 && TERM ){                                \
   18022     int c2 = ((*zIn++)<<8);                                           \
   18023     c2 += (*zIn++);                                                   \
   18024     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
   18025   }                                                                   \
   18026 }
   18027 
   18028 /*
   18029 ** Translate a single UTF-8 character.  Return the unicode value.
   18030 **
   18031 ** During translation, assume that the byte that zTerm points
   18032 ** is a 0x00.
   18033 **
   18034 ** Write a pointer to the next unread byte back into *pzNext.
   18035 **
   18036 ** Notes On Invalid UTF-8:
   18037 **
   18038 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
   18039 **     be encoded as a multi-byte character.  Any multi-byte character that
   18040 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
   18041 **
   18042 **  *  This routine never allows a UTF16 surrogate value to be encoded.
   18043 **     If a multi-byte character attempts to encode a value between
   18044 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
   18045 **
   18046 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
   18047 **     byte of a character are interpreted as single-byte characters
   18048 **     and rendered as themselves even though they are technically
   18049 **     invalid characters.
   18050 **
   18051 **  *  This routine accepts an infinite number of different UTF8 encodings
   18052 **     for unicode values 0x80 and greater.  It do not change over-length
   18053 **     encodings to 0xfffd as some systems recommend.
   18054 */
   18055 #define READ_UTF8(zIn, zTerm, c)                           \
   18056   c = *(zIn++);                                            \
   18057   if( c>=0xc0 ){                                           \
   18058     c = sqlite3Utf8Trans1[c-0xc0];                         \
   18059     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
   18060       c = (c<<6) + (0x3f & *(zIn++));                      \
   18061     }                                                      \
   18062     if( c<0x80                                             \
   18063         || (c&0xFFFFF800)==0xD800                          \
   18064         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
   18065   }
   18066 SQLITE_PRIVATE int sqlite3Utf8Read(
   18067   const unsigned char *zIn,       /* First byte of UTF-8 character */
   18068   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
   18069 ){
   18070   int c;
   18071 
   18072   /* Same as READ_UTF8() above but without the zTerm parameter.
   18073   ** For this routine, we assume the UTF8 string is always zero-terminated.
   18074   */
   18075   c = *(zIn++);
   18076   if( c>=0xc0 ){
   18077     c = sqlite3Utf8Trans1[c-0xc0];
   18078     while( (*zIn & 0xc0)==0x80 ){
   18079       c = (c<<6) + (0x3f & *(zIn++));
   18080     }
   18081     if( c<0x80
   18082         || (c&0xFFFFF800)==0xD800
   18083         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
   18084   }
   18085   *pzNext = zIn;
   18086   return c;
   18087 }
   18088 
   18089 
   18090 
   18091 
   18092 /*
   18093 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
   18094 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
   18095 */
   18096 /* #define TRANSLATE_TRACE 1 */
   18097 
   18098 #ifndef SQLITE_OMIT_UTF16
   18099 /*
   18100 ** This routine transforms the internal text encoding used by pMem to
   18101 ** desiredEnc. It is an error if the string is already of the desired
   18102 ** encoding, or if *pMem does not contain a string value.
   18103 */
   18104 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
   18105   int len;                    /* Maximum length of output string in bytes */
   18106   unsigned char *zOut;                  /* Output buffer */
   18107   unsigned char *zIn;                   /* Input iterator */
   18108   unsigned char *zTerm;                 /* End of input */
   18109   unsigned char *z;                     /* Output iterator */
   18110   unsigned int c;
   18111 
   18112   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   18113   assert( pMem->flags&MEM_Str );
   18114   assert( pMem->enc!=desiredEnc );
   18115   assert( pMem->enc!=0 );
   18116   assert( pMem->n>=0 );
   18117 
   18118 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
   18119   {
   18120     char zBuf[100];
   18121     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
   18122     fprintf(stderr, "INPUT:  %s\n", zBuf);
   18123   }
   18124 #endif
   18125 
   18126   /* If the translation is between UTF-16 little and big endian, then
   18127   ** all that is required is to swap the byte order. This case is handled
   18128   ** differently from the others.
   18129   */
   18130   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
   18131     u8 temp;
   18132     int rc;
   18133     rc = sqlite3VdbeMemMakeWriteable(pMem);
   18134     if( rc!=SQLITE_OK ){
   18135       assert( rc==SQLITE_NOMEM );
   18136       return SQLITE_NOMEM;
   18137     }
   18138     zIn = (u8*)pMem->z;
   18139     zTerm = &zIn[pMem->n&~1];
   18140     while( zIn<zTerm ){
   18141       temp = *zIn;
   18142       *zIn = *(zIn+1);
   18143       zIn++;
   18144       *zIn++ = temp;
   18145     }
   18146     pMem->enc = desiredEnc;
   18147     goto translate_out;
   18148   }
   18149 
   18150   /* Set len to the maximum number of bytes required in the output buffer. */
   18151   if( desiredEnc==SQLITE_UTF8 ){
   18152     /* When converting from UTF-16, the maximum growth results from
   18153     ** translating a 2-byte character to a 4-byte UTF-8 character.
   18154     ** A single byte is required for the output string
   18155     ** nul-terminator.
   18156     */
   18157     pMem->n &= ~1;
   18158     len = pMem->n * 2 + 1;
   18159   }else{
   18160     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
   18161     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
   18162     ** character. Two bytes are required in the output buffer for the
   18163     ** nul-terminator.
   18164     */
   18165     len = pMem->n * 2 + 2;
   18166   }
   18167 
   18168   /* Set zIn to point at the start of the input buffer and zTerm to point 1
   18169   ** byte past the end.
   18170   **
   18171   ** Variable zOut is set to point at the output buffer, space obtained
   18172   ** from sqlite3_malloc().
   18173   */
   18174   zIn = (u8*)pMem->z;
   18175   zTerm = &zIn[pMem->n];
   18176   zOut = sqlite3DbMallocRaw(pMem->db, len);
   18177   if( !zOut ){
   18178     return SQLITE_NOMEM;
   18179   }
   18180   z = zOut;
   18181 
   18182   if( pMem->enc==SQLITE_UTF8 ){
   18183     if( desiredEnc==SQLITE_UTF16LE ){
   18184       /* UTF-8 -> UTF-16 Little-endian */
   18185       while( zIn<zTerm ){
   18186         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
   18187         READ_UTF8(zIn, zTerm, c);
   18188         WRITE_UTF16LE(z, c);
   18189       }
   18190     }else{
   18191       assert( desiredEnc==SQLITE_UTF16BE );
   18192       /* UTF-8 -> UTF-16 Big-endian */
   18193       while( zIn<zTerm ){
   18194         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
   18195         READ_UTF8(zIn, zTerm, c);
   18196         WRITE_UTF16BE(z, c);
   18197       }
   18198     }
   18199     pMem->n = (int)(z - zOut);
   18200     *z++ = 0;
   18201   }else{
   18202     assert( desiredEnc==SQLITE_UTF8 );
   18203     if( pMem->enc==SQLITE_UTF16LE ){
   18204       /* UTF-16 Little-endian -> UTF-8 */
   18205       while( zIn<zTerm ){
   18206         READ_UTF16LE(zIn, zIn<zTerm, c);
   18207         WRITE_UTF8(z, c);
   18208       }
   18209     }else{
   18210       /* UTF-16 Big-endian -> UTF-8 */
   18211       while( zIn<zTerm ){
   18212         READ_UTF16BE(zIn, zIn<zTerm, c);
   18213         WRITE_UTF8(z, c);
   18214       }
   18215     }
   18216     pMem->n = (int)(z - zOut);
   18217   }
   18218   *z = 0;
   18219   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
   18220 
   18221   sqlite3VdbeMemRelease(pMem);
   18222   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
   18223   pMem->enc = desiredEnc;
   18224   pMem->flags |= (MEM_Term|MEM_Dyn);
   18225   pMem->z = (char*)zOut;
   18226   pMem->zMalloc = pMem->z;
   18227 
   18228 translate_out:
   18229 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
   18230   {
   18231     char zBuf[100];
   18232     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
   18233     fprintf(stderr, "OUTPUT: %s\n", zBuf);
   18234   }
   18235 #endif
   18236   return SQLITE_OK;
   18237 }
   18238 
   18239 /*
   18240 ** This routine checks for a byte-order mark at the beginning of the
   18241 ** UTF-16 string stored in *pMem. If one is present, it is removed and
   18242 ** the encoding of the Mem adjusted. This routine does not do any
   18243 ** byte-swapping, it just sets Mem.enc appropriately.
   18244 **
   18245 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
   18246 ** changed by this function.
   18247 */
   18248 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
   18249   int rc = SQLITE_OK;
   18250   u8 bom = 0;
   18251 
   18252   assert( pMem->n>=0 );
   18253   if( pMem->n>1 ){
   18254     u8 b1 = *(u8 *)pMem->z;
   18255     u8 b2 = *(((u8 *)pMem->z) + 1);
   18256     if( b1==0xFE && b2==0xFF ){
   18257       bom = SQLITE_UTF16BE;
   18258     }
   18259     if( b1==0xFF && b2==0xFE ){
   18260       bom = SQLITE_UTF16LE;
   18261     }
   18262   }
   18263 
   18264   if( bom ){
   18265     rc = sqlite3VdbeMemMakeWriteable(pMem);
   18266     if( rc==SQLITE_OK ){
   18267       pMem->n -= 2;
   18268       memmove(pMem->z, &pMem->z[2], pMem->n);
   18269       pMem->z[pMem->n] = '\0';
   18270       pMem->z[pMem->n+1] = '\0';
   18271       pMem->flags |= MEM_Term;
   18272       pMem->enc = bom;
   18273     }
   18274   }
   18275   return rc;
   18276 }
   18277 #endif /* SQLITE_OMIT_UTF16 */
   18278 
   18279 /*
   18280 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
   18281 ** return the number of unicode characters in pZ up to (but not including)
   18282 ** the first 0x00 byte. If nByte is not less than zero, return the
   18283 ** number of unicode characters in the first nByte of pZ (or up to
   18284 ** the first 0x00, whichever comes first).
   18285 */
   18286 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
   18287   int r = 0;
   18288   const u8 *z = (const u8*)zIn;
   18289   const u8 *zTerm;
   18290   if( nByte>=0 ){
   18291     zTerm = &z[nByte];
   18292   }else{
   18293     zTerm = (const u8*)(-1);
   18294   }
   18295   assert( z<=zTerm );
   18296   while( *z!=0 && z<zTerm ){
   18297     SQLITE_SKIP_UTF8(z);
   18298     r++;
   18299   }
   18300   return r;
   18301 }
   18302 
   18303 /* This test function is not currently used by the automated test-suite.
   18304 ** Hence it is only available in debug builds.
   18305 */
   18306 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   18307 /*
   18308 ** Translate UTF-8 to UTF-8.
   18309 **
   18310 ** This has the effect of making sure that the string is well-formed
   18311 ** UTF-8.  Miscoded characters are removed.
   18312 **
   18313 ** The translation is done in-place (since it is impossible for the
   18314 ** correct UTF-8 encoding to be longer than a malformed encoding).
   18315 */
   18316 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
   18317   unsigned char *zOut = zIn;
   18318   unsigned char *zStart = zIn;
   18319   u32 c;
   18320 
   18321   while( zIn[0] ){
   18322     c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
   18323     if( c!=0xfffd ){
   18324       WRITE_UTF8(zOut, c);
   18325     }
   18326   }
   18327   *zOut = 0;
   18328   return (int)(zOut - zStart);
   18329 }
   18330 #endif
   18331 
   18332 #ifndef SQLITE_OMIT_UTF16
   18333 /*
   18334 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
   18335 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
   18336 ** be freed by the calling function.
   18337 **
   18338 ** NULL is returned if there is an allocation error.
   18339 */
   18340 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
   18341   Mem m;
   18342   memset(&m, 0, sizeof(m));
   18343   m.db = db;
   18344   sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   18345   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
   18346   if( db->mallocFailed ){
   18347     sqlite3VdbeMemRelease(&m);
   18348     m.z = 0;
   18349   }
   18350   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
   18351   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
   18352   return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
   18353 }
   18354 
   18355 /*
   18356 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
   18357 ** enc. A pointer to the new string is returned, and the value of *pnOut
   18358 ** is set to the length of the returned string in bytes. The call should
   18359 ** arrange to call sqlite3DbFree() on the returned pointer when it is
   18360 ** no longer required.
   18361 **
   18362 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
   18363 ** flag set.
   18364 */
   18365 #ifdef SQLITE_ENABLE_STAT2
   18366 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
   18367   Mem m;
   18368   memset(&m, 0, sizeof(m));
   18369   m.db = db;
   18370   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
   18371   if( sqlite3VdbeMemTranslate(&m, enc) ){
   18372     assert( db->mallocFailed );
   18373     return 0;
   18374   }
   18375   assert( m.z==m.zMalloc );
   18376   *pnOut = m.n;
   18377   return m.z;
   18378 }
   18379 #endif
   18380 
   18381 /*
   18382 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
   18383 ** Return the number of bytes in the first nChar unicode characters
   18384 ** in pZ.  nChar must be non-negative.
   18385 */
   18386 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
   18387   int c;
   18388   unsigned char const *z = zIn;
   18389   int n = 0;
   18390 
   18391   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
   18392     while( n<nChar ){
   18393       READ_UTF16BE(z, 1, c);
   18394       n++;
   18395     }
   18396   }else{
   18397     while( n<nChar ){
   18398       READ_UTF16LE(z, 1, c);
   18399       n++;
   18400     }
   18401   }
   18402   return (int)(z-(unsigned char const *)zIn);
   18403 }
   18404 
   18405 #if defined(SQLITE_TEST)
   18406 /*
   18407 ** This routine is called from the TCL test function "translate_selftest".
   18408 ** It checks that the primitives for serializing and deserializing
   18409 ** characters in each encoding are inverses of each other.
   18410 */
   18411 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
   18412   unsigned int i, t;
   18413   unsigned char zBuf[20];
   18414   unsigned char *z;
   18415   int n;
   18416   unsigned int c;
   18417 
   18418   for(i=0; i<0x00110000; i++){
   18419     z = zBuf;
   18420     WRITE_UTF8(z, i);
   18421     n = (int)(z-zBuf);
   18422     assert( n>0 && n<=4 );
   18423     z[0] = 0;
   18424     z = zBuf;
   18425     c = sqlite3Utf8Read(z, (const u8**)&z);
   18426     t = i;
   18427     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
   18428     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
   18429     assert( c==t );
   18430     assert( (z-zBuf)==n );
   18431   }
   18432   for(i=0; i<0x00110000; i++){
   18433     if( i>=0xD800 && i<0xE000 ) continue;
   18434     z = zBuf;
   18435     WRITE_UTF16LE(z, i);
   18436     n = (int)(z-zBuf);
   18437     assert( n>0 && n<=4 );
   18438     z[0] = 0;
   18439     z = zBuf;
   18440     READ_UTF16LE(z, 1, c);
   18441     assert( c==i );
   18442     assert( (z-zBuf)==n );
   18443   }
   18444   for(i=0; i<0x00110000; i++){
   18445     if( i>=0xD800 && i<0xE000 ) continue;
   18446     z = zBuf;
   18447     WRITE_UTF16BE(z, i);
   18448     n = (int)(z-zBuf);
   18449     assert( n>0 && n<=4 );
   18450     z[0] = 0;
   18451     z = zBuf;
   18452     READ_UTF16BE(z, 1, c);
   18453     assert( c==i );
   18454     assert( (z-zBuf)==n );
   18455   }
   18456 }
   18457 #endif /* SQLITE_TEST */
   18458 #endif /* SQLITE_OMIT_UTF16 */
   18459 
   18460 /************** End of utf.c *************************************************/
   18461 /************** Begin file util.c ********************************************/
   18462 /*
   18463 ** 2001 September 15
   18464 **
   18465 ** The author disclaims copyright to this source code.  In place of
   18466 ** a legal notice, here is a blessing:
   18467 **
   18468 **    May you do good and not evil.
   18469 **    May you find forgiveness for yourself and forgive others.
   18470 **    May you share freely, never taking more than you give.
   18471 **
   18472 *************************************************************************
   18473 ** Utility functions used throughout sqlite.
   18474 **
   18475 ** This file contains functions for allocating memory, comparing
   18476 ** strings, and stuff like that.
   18477 **
   18478 */
   18479 #ifdef SQLITE_HAVE_ISNAN
   18480 # include <math.h>
   18481 #endif
   18482 
   18483 /*
   18484 ** Routine needed to support the testcase() macro.
   18485 */
   18486 #ifdef SQLITE_COVERAGE_TEST
   18487 SQLITE_PRIVATE void sqlite3Coverage(int x){
   18488   static int dummy = 0;
   18489   dummy += x;
   18490 }
   18491 #endif
   18492 
   18493 /*
   18494 ** Return true if the floating point value is Not a Number (NaN).
   18495 **
   18496 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
   18497 ** Otherwise, we have our own implementation that works on most systems.
   18498 */
   18499 SQLITE_PRIVATE int sqlite3IsNaN(double x){
   18500   int rc;   /* The value return */
   18501 #if !defined(SQLITE_HAVE_ISNAN)
   18502   /*
   18503   ** Systems that support the isnan() library function should probably
   18504   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
   18505   ** found that many systems do not have a working isnan() function so
   18506   ** this implementation is provided as an alternative.
   18507   **
   18508   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
   18509   ** On the other hand, the use of -ffast-math comes with the following
   18510   ** warning:
   18511   **
   18512   **      This option [-ffast-math] should never be turned on by any
   18513   **      -O option since it can result in incorrect output for programs
   18514   **      which depend on an exact implementation of IEEE or ISO
   18515   **      rules/specifications for math functions.
   18516   **
   18517   ** Under MSVC, this NaN test may fail if compiled with a floating-
   18518   ** point precision mode other than /fp:precise.  From the MSDN
   18519   ** documentation:
   18520   **
   18521   **      The compiler [with /fp:precise] will properly handle comparisons
   18522   **      involving NaN. For example, x != x evaluates to true if x is NaN
   18523   **      ...
   18524   */
   18525 #ifdef __FAST_MATH__
   18526 # error SQLite will not work correctly with the -ffast-math option of GCC.
   18527 #endif
   18528   volatile double y = x;
   18529   volatile double z = y;
   18530   rc = (y!=z);
   18531 #else  /* if defined(SQLITE_HAVE_ISNAN) */
   18532   rc = isnan(x);
   18533 #endif /* SQLITE_HAVE_ISNAN */
   18534   testcase( rc );
   18535   return rc;
   18536 }
   18537 
   18538 /*
   18539 ** Compute a string length that is limited to what can be stored in
   18540 ** lower 30 bits of a 32-bit signed integer.
   18541 **
   18542 ** The value returned will never be negative.  Nor will it ever be greater
   18543 ** than the actual length of the string.  For very long strings (greater
   18544 ** than 1GiB) the value returned might be less than the true string length.
   18545 */
   18546 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
   18547   const char *z2 = z;
   18548   if( z==0 ) return 0;
   18549   while( *z2 ){ z2++; }
   18550   return 0x3fffffff & (int)(z2 - z);
   18551 }
   18552 
   18553 /*
   18554 ** Set the most recent error code and error string for the sqlite
   18555 ** handle "db". The error code is set to "err_code".
   18556 **
   18557 ** If it is not NULL, string zFormat specifies the format of the
   18558 ** error string in the style of the printf functions: The following
   18559 ** format characters are allowed:
   18560 **
   18561 **      %s      Insert a string
   18562 **      %z      A string that should be freed after use
   18563 **      %d      Insert an integer
   18564 **      %T      Insert a token
   18565 **      %S      Insert the first element of a SrcList
   18566 **
   18567 ** zFormat and any string tokens that follow it are assumed to be
   18568 ** encoded in UTF-8.
   18569 **
   18570 ** To clear the most recent error for sqlite handle "db", sqlite3Error
   18571 ** should be called with err_code set to SQLITE_OK and zFormat set
   18572 ** to NULL.
   18573 */
   18574 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
   18575   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
   18576     db->errCode = err_code;
   18577     if( zFormat ){
   18578       char *z;
   18579       va_list ap;
   18580       va_start(ap, zFormat);
   18581       z = sqlite3VMPrintf(db, zFormat, ap);
   18582       va_end(ap);
   18583       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
   18584     }else{
   18585       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
   18586     }
   18587   }
   18588 }
   18589 
   18590 /*
   18591 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
   18592 ** The following formatting characters are allowed:
   18593 **
   18594 **      %s      Insert a string
   18595 **      %z      A string that should be freed after use
   18596 **      %d      Insert an integer
   18597 **      %T      Insert a token
   18598 **      %S      Insert the first element of a SrcList
   18599 **
   18600 ** This function should be used to report any error that occurs whilst
   18601 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
   18602 ** last thing the sqlite3_prepare() function does is copy the error
   18603 ** stored by this function into the database handle using sqlite3Error().
   18604 ** Function sqlite3Error() should be used during statement execution
   18605 ** (sqlite3_step() etc.).
   18606 */
   18607 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
   18608   char *zMsg;
   18609   va_list ap;
   18610   sqlite3 *db = pParse->db;
   18611   va_start(ap, zFormat);
   18612   zMsg = sqlite3VMPrintf(db, zFormat, ap);
   18613   va_end(ap);
   18614   if( db->suppressErr ){
   18615     sqlite3DbFree(db, zMsg);
   18616   }else{
   18617     pParse->nErr++;
   18618     sqlite3DbFree(db, pParse->zErrMsg);
   18619     pParse->zErrMsg = zMsg;
   18620     pParse->rc = SQLITE_ERROR;
   18621   }
   18622 }
   18623 
   18624 /*
   18625 ** Convert an SQL-style quoted string into a normal string by removing
   18626 ** the quote characters.  The conversion is done in-place.  If the
   18627 ** input does not begin with a quote character, then this routine
   18628 ** is a no-op.
   18629 **
   18630 ** The input string must be zero-terminated.  A new zero-terminator
   18631 ** is added to the dequoted string.
   18632 **
   18633 ** The return value is -1 if no dequoting occurs or the length of the
   18634 ** dequoted string, exclusive of the zero terminator, if dequoting does
   18635 ** occur.
   18636 **
   18637 ** 2002-Feb-14: This routine is extended to remove MS-Access style
   18638 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
   18639 ** "a-b-c".
   18640 */
   18641 SQLITE_PRIVATE int sqlite3Dequote(char *z){
   18642   char quote;
   18643   int i, j;
   18644   if( z==0 ) return -1;
   18645   quote = z[0];
   18646   switch( quote ){
   18647     case '\'':  break;
   18648     case '"':   break;
   18649     case '`':   break;                /* For MySQL compatibility */
   18650     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
   18651     default:    return -1;
   18652   }
   18653   for(i=1, j=0; ALWAYS(z[i]); i++){
   18654     if( z[i]==quote ){
   18655       if( z[i+1]==quote ){
   18656         z[j++] = quote;
   18657         i++;
   18658       }else{
   18659         break;
   18660       }
   18661     }else{
   18662       z[j++] = z[i];
   18663     }
   18664   }
   18665   z[j] = 0;
   18666   return j;
   18667 }
   18668 
   18669 /* Convenient short-hand */
   18670 #define UpperToLower sqlite3UpperToLower
   18671 
   18672 /*
   18673 ** Some systems have stricmp().  Others have strcasecmp().  Because
   18674 ** there is no consistency, we will define our own.
   18675 */
   18676 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
   18677   register unsigned char *a, *b;
   18678   a = (unsigned char *)zLeft;
   18679   b = (unsigned char *)zRight;
   18680   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
   18681   return UpperToLower[*a] - UpperToLower[*b];
   18682 }
   18683 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
   18684   register unsigned char *a, *b;
   18685   a = (unsigned char *)zLeft;
   18686   b = (unsigned char *)zRight;
   18687   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
   18688   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
   18689 }
   18690 
   18691 /*
   18692 ** Return TRUE if z is a pure numeric string.  Return FALSE and leave
   18693 ** *realnum unchanged if the string contains any character which is not
   18694 ** part of a number.
   18695 **
   18696 ** If the string is pure numeric, set *realnum to TRUE if the string
   18697 ** contains the '.' character or an "E+000" style exponentiation suffix.
   18698 ** Otherwise set *realnum to FALSE.  Note that just becaue *realnum is
   18699 ** false does not mean that the number can be successfully converted into
   18700 ** an integer - it might be too big.
   18701 **
   18702 ** An empty string is considered non-numeric.
   18703 */
   18704 SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
   18705   int incr = (enc==SQLITE_UTF8?1:2);
   18706   if( enc==SQLITE_UTF16BE ) z++;
   18707   if( *z=='-' || *z=='+' ) z += incr;
   18708   if( !sqlite3Isdigit(*z) ){
   18709     return 0;
   18710   }
   18711   z += incr;
   18712   *realnum = 0;
   18713   while( sqlite3Isdigit(*z) ){ z += incr; }
   18714   if( *z=='.' ){
   18715     z += incr;
   18716     if( !sqlite3Isdigit(*z) ) return 0;
   18717     while( sqlite3Isdigit(*z) ){ z += incr; }
   18718     *realnum = 1;
   18719   }
   18720   if( *z=='e' || *z=='E' ){
   18721     z += incr;
   18722     if( *z=='+' || *z=='-' ) z += incr;
   18723     if( !sqlite3Isdigit(*z) ) return 0;
   18724     while( sqlite3Isdigit(*z) ){ z += incr; }
   18725     *realnum = 1;
   18726   }
   18727   return *z==0;
   18728 }
   18729 
   18730 /*
   18731 ** The string z[] is an ASCII representation of a real number.
   18732 ** Convert this string to a double.
   18733 **
   18734 ** This routine assumes that z[] really is a valid number.  If it
   18735 ** is not, the result is undefined.
   18736 **
   18737 ** This routine is used instead of the library atof() function because
   18738 ** the library atof() might want to use "," as the decimal point instead
   18739 ** of "." depending on how locale is set.  But that would cause problems
   18740 ** for SQL.  So this routine always uses "." regardless of locale.
   18741 */
   18742 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
   18743 #ifndef SQLITE_OMIT_FLOATING_POINT
   18744   const char *zBegin = z;
   18745   /* sign * significand * (10 ^ (esign * exponent)) */
   18746   int sign = 1;   /* sign of significand */
   18747   i64 s = 0;      /* significand */
   18748   int d = 0;      /* adjust exponent for shifting decimal point */
   18749   int esign = 1;  /* sign of exponent */
   18750   int e = 0;      /* exponent */
   18751   double result;
   18752   int nDigits = 0;
   18753 
   18754   /* skip leading spaces */
   18755   while( sqlite3Isspace(*z) ) z++;
   18756   /* get sign of significand */
   18757   if( *z=='-' ){
   18758     sign = -1;
   18759     z++;
   18760   }else if( *z=='+' ){
   18761     z++;
   18762   }
   18763   /* skip leading zeroes */
   18764   while( z[0]=='0' ) z++, nDigits++;
   18765 
   18766   /* copy max significant digits to significand */
   18767   while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
   18768     s = s*10 + (*z - '0');
   18769     z++, nDigits++;
   18770   }
   18771   /* skip non-significant significand digits
   18772   ** (increase exponent by d to shift decimal left) */
   18773   while( sqlite3Isdigit(*z) ) z++, nDigits++, d++;
   18774 
   18775   /* if decimal point is present */
   18776   if( *z=='.' ){
   18777     z++;
   18778     /* copy digits from after decimal to significand
   18779     ** (decrease exponent by d to shift decimal right) */
   18780     while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
   18781       s = s*10 + (*z - '0');
   18782       z++, nDigits++, d--;
   18783     }
   18784     /* skip non-significant digits */
   18785     while( sqlite3Isdigit(*z) ) z++, nDigits++;
   18786   }
   18787 
   18788   /* if exponent is present */
   18789   if( *z=='e' || *z=='E' ){
   18790     z++;
   18791     /* get sign of exponent */
   18792     if( *z=='-' ){
   18793       esign = -1;
   18794       z++;
   18795     }else if( *z=='+' ){
   18796       z++;
   18797     }
   18798     /* copy digits to exponent */
   18799     while( sqlite3Isdigit(*z) ){
   18800       e = e*10 + (*z - '0');
   18801       z++;
   18802     }
   18803   }
   18804 
   18805   /* adjust exponent by d, and update sign */
   18806   e = (e*esign) + d;
   18807   if( e<0 ) {
   18808     esign = -1;
   18809     e *= -1;
   18810   } else {
   18811     esign = 1;
   18812   }
   18813 
   18814   /* if 0 significand */
   18815   if( !s ) {
   18816     /* In the IEEE 754 standard, zero is signed.
   18817     ** Add the sign if we've seen at least one digit */
   18818     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
   18819   } else {
   18820     /* attempt to reduce exponent */
   18821     if( esign>0 ){
   18822       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
   18823     }else{
   18824       while( !(s%10) && e>0 ) e--,s/=10;
   18825     }
   18826 
   18827     /* adjust the sign of significand */
   18828     s = sign<0 ? -s : s;
   18829 
   18830     /* if exponent, scale significand as appropriate
   18831     ** and store in result. */
   18832     if( e ){
   18833       double scale = 1.0;
   18834       /* attempt to handle extremely small/large numbers better */
   18835       if( e>307 && e<342 ){
   18836         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
   18837         if( esign<0 ){
   18838           result = s / scale;
   18839           result /= 1.0e+308;
   18840         }else{
   18841           result = s * scale;
   18842           result *= 1.0e+308;
   18843         }
   18844       }else{
   18845         /* 1.0e+22 is the largest power of 10 than can be
   18846         ** represented exactly. */
   18847         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
   18848         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
   18849         if( esign<0 ){
   18850           result = s / scale;
   18851         }else{
   18852           result = s * scale;
   18853         }
   18854       }
   18855     } else {
   18856       result = (double)s;
   18857     }
   18858   }
   18859 
   18860   /* store the result */
   18861   *pResult = result;
   18862 
   18863   /* return number of characters used */
   18864   return (int)(z - zBegin);
   18865 #else
   18866   return sqlite3Atoi64(z, pResult);
   18867 #endif /* SQLITE_OMIT_FLOATING_POINT */
   18868 }
   18869 
   18870 /*
   18871 ** Compare the 19-character string zNum against the text representation
   18872 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
   18873 ** if zNum is less than, equal to, or greater than the string.
   18874 **
   18875 ** Unlike memcmp() this routine is guaranteed to return the difference
   18876 ** in the values of the last digit if the only difference is in the
   18877 ** last digit.  So, for example,
   18878 **
   18879 **      compare2pow63("9223372036854775800")
   18880 **
   18881 ** will return -8.
   18882 */
   18883 static int compare2pow63(const char *zNum){
   18884   int c;
   18885   c = memcmp(zNum,"922337203685477580",18)*10;
   18886   if( c==0 ){
   18887     c = zNum[18] - '8';
   18888   }
   18889   return c;
   18890 }
   18891 
   18892 
   18893 /*
   18894 ** Return TRUE if zNum is a 64-bit signed integer and write
   18895 ** the value of the integer into *pNum.  If zNum is not an integer
   18896 ** or is an integer that is too large to be expressed with 64 bits,
   18897 ** then return false.
   18898 **
   18899 ** When this routine was originally written it dealt with only
   18900 ** 32-bit numbers.  At that time, it was much faster than the
   18901 ** atoi() library routine in RedHat 7.2.
   18902 */
   18903 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
   18904   i64 v = 0;
   18905   int neg;
   18906   int i, c;
   18907   const char *zStart;
   18908   while( sqlite3Isspace(*zNum) ) zNum++;
   18909   if( *zNum=='-' ){
   18910     neg = 1;
   18911     zNum++;
   18912   }else if( *zNum=='+' ){
   18913     neg = 0;
   18914     zNum++;
   18915   }else{
   18916     neg = 0;
   18917   }
   18918   zStart = zNum;
   18919   while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
   18920   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
   18921     v = v*10 + c - '0';
   18922   }
   18923   *pNum = neg ? -v : v;
   18924   if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
   18925     /* zNum is empty or contains non-numeric text or is longer
   18926     ** than 19 digits (thus guaranting that it is too large) */
   18927     return 0;
   18928   }else if( i<19 ){
   18929     /* Less than 19 digits, so we know that it fits in 64 bits */
   18930     return 1;
   18931   }else{
   18932     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
   18933     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
   18934     ** is 2^63. */
   18935     return compare2pow63(zNum)<neg;
   18936   }
   18937 }
   18938 
   18939 /*
   18940 ** The string zNum represents an unsigned integer.  The zNum string
   18941 ** consists of one or more digit characters and is terminated by
   18942 ** a zero character.  Any stray characters in zNum result in undefined
   18943 ** behavior.
   18944 **
   18945 ** If the unsigned integer that zNum represents will fit in a
   18946 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
   18947 **
   18948 ** If the negFlag parameter is true, that means that zNum really represents
   18949 ** a negative number.  (The leading "-" is omitted from zNum.)  This
   18950 ** parameter is needed to determine a boundary case.  A string
   18951 ** of "9223373036854775808" returns false if negFlag is false or true
   18952 ** if negFlag is true.
   18953 **
   18954 ** Leading zeros are ignored.
   18955 */
   18956 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
   18957   int i;
   18958   int neg = 0;
   18959 
   18960   assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */
   18961 
   18962   if( negFlag ) neg = 1-neg;
   18963   while( *zNum=='0' ){
   18964     zNum++;   /* Skip leading zeros.  Ticket #2454 */
   18965   }
   18966   for(i=0; zNum[i]; i++){ assert( zNum[i]>='0' && zNum[i]<='9' ); }
   18967   if( i<19 ){
   18968     /* Guaranteed to fit if less than 19 digits */
   18969     return 1;
   18970   }else if( i>19 ){
   18971     /* Guaranteed to be too big if greater than 19 digits */
   18972     return 0;
   18973   }else{
   18974     /* Compare against 2^63. */
   18975     return compare2pow63(zNum)<neg;
   18976   }
   18977 }
   18978 
   18979 /*
   18980 ** If zNum represents an integer that will fit in 32-bits, then set
   18981 ** *pValue to that integer and return true.  Otherwise return false.
   18982 **
   18983 ** Any non-numeric characters that following zNum are ignored.
   18984 ** This is different from sqlite3Atoi64() which requires the
   18985 ** input number to be zero-terminated.
   18986 */
   18987 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
   18988   sqlite_int64 v = 0;
   18989   int i, c;
   18990   int neg = 0;
   18991   if( zNum[0]=='-' ){
   18992     neg = 1;
   18993     zNum++;
   18994   }else if( zNum[0]=='+' ){
   18995     zNum++;
   18996   }
   18997   while( zNum[0]=='0' ) zNum++;
   18998   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
   18999     v = v*10 + c;
   19000   }
   19001 
   19002   /* The longest decimal representation of a 32 bit integer is 10 digits:
   19003   **
   19004   **             1234567890
   19005   **     2^31 -> 2147483648
   19006   */
   19007   if( i>10 ){
   19008     return 0;
   19009   }
   19010   if( v-neg>2147483647 ){
   19011     return 0;
   19012   }
   19013   if( neg ){
   19014     v = -v;
   19015   }
   19016   *pValue = (int)v;
   19017   return 1;
   19018 }
   19019 
   19020 /*
   19021 ** The variable-length integer encoding is as follows:
   19022 **
   19023 ** KEY:
   19024 **         A = 0xxxxxxx    7 bits of data and one flag bit
   19025 **         B = 1xxxxxxx    7 bits of data and one flag bit
   19026 **         C = xxxxxxxx    8 bits of data
   19027 **
   19028 **  7 bits - A
   19029 ** 14 bits - BA
   19030 ** 21 bits - BBA
   19031 ** 28 bits - BBBA
   19032 ** 35 bits - BBBBA
   19033 ** 42 bits - BBBBBA
   19034 ** 49 bits - BBBBBBA
   19035 ** 56 bits - BBBBBBBA
   19036 ** 64 bits - BBBBBBBBC
   19037 */
   19038 
   19039 /*
   19040 ** Write a 64-bit variable-length integer to memory starting at p[0].
   19041 ** The length of data write will be between 1 and 9 bytes.  The number
   19042 ** of bytes written is returned.
   19043 **
   19044 ** A variable-length integer consists of the lower 7 bits of each byte
   19045 ** for all bytes that have the 8th bit set and one byte with the 8th
   19046 ** bit clear.  Except, if we get to the 9th byte, it stores the full
   19047 ** 8 bits and is the last byte.
   19048 */
   19049 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
   19050   int i, j, n;
   19051   u8 buf[10];
   19052   if( v & (((u64)0xff000000)<<32) ){
   19053     p[8] = (u8)v;
   19054     v >>= 8;
   19055     for(i=7; i>=0; i--){
   19056       p[i] = (u8)((v & 0x7f) | 0x80);
   19057       v >>= 7;
   19058     }
   19059     return 9;
   19060   }
   19061   n = 0;
   19062   do{
   19063     buf[n++] = (u8)((v & 0x7f) | 0x80);
   19064     v >>= 7;
   19065   }while( v!=0 );
   19066   buf[0] &= 0x7f;
   19067   assert( n<=9 );
   19068   for(i=0, j=n-1; j>=0; j--, i++){
   19069     p[i] = buf[j];
   19070   }
   19071   return n;
   19072 }
   19073 
   19074 /*
   19075 ** This routine is a faster version of sqlite3PutVarint() that only
   19076 ** works for 32-bit positive integers and which is optimized for
   19077 ** the common case of small integers.  A MACRO version, putVarint32,
   19078 ** is provided which inlines the single-byte case.  All code should use
   19079 ** the MACRO version as this function assumes the single-byte case has
   19080 ** already been handled.
   19081 */
   19082 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
   19083 #ifndef putVarint32
   19084   if( (v & ~0x7f)==0 ){
   19085     p[0] = v;
   19086     return 1;
   19087   }
   19088 #endif
   19089   if( (v & ~0x3fff)==0 ){
   19090     p[0] = (u8)((v>>7) | 0x80);
   19091     p[1] = (u8)(v & 0x7f);
   19092     return 2;
   19093   }
   19094   return sqlite3PutVarint(p, v);
   19095 }
   19096 
   19097 /*
   19098 ** Read a 64-bit variable-length integer from memory starting at p[0].
   19099 ** Return the number of bytes read.  The value is stored in *v.
   19100 */
   19101 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
   19102   u32 a,b,s;
   19103 
   19104   a = *p;
   19105   /* a: p0 (unmasked) */
   19106   if (!(a&0x80))
   19107   {
   19108     *v = a;
   19109     return 1;
   19110   }
   19111 
   19112   p++;
   19113   b = *p;
   19114   /* b: p1 (unmasked) */
   19115   if (!(b&0x80))
   19116   {
   19117     a &= 0x7f;
   19118     a = a<<7;
   19119     a |= b;
   19120     *v = a;
   19121     return 2;
   19122   }
   19123 
   19124   p++;
   19125   a = a<<14;
   19126   a |= *p;
   19127   /* a: p0<<14 | p2 (unmasked) */
   19128   if (!(a&0x80))
   19129   {
   19130     a &= (0x7f<<14)|(0x7f);
   19131     b &= 0x7f;
   19132     b = b<<7;
   19133     a |= b;
   19134     *v = a;
   19135     return 3;
   19136   }
   19137 
   19138   /* CSE1 from below */
   19139   a &= (0x7f<<14)|(0x7f);
   19140   p++;
   19141   b = b<<14;
   19142   b |= *p;
   19143   /* b: p1<<14 | p3 (unmasked) */
   19144   if (!(b&0x80))
   19145   {
   19146     b &= (0x7f<<14)|(0x7f);
   19147     /* moved CSE1 up */
   19148     /* a &= (0x7f<<14)|(0x7f); */
   19149     a = a<<7;
   19150     a |= b;
   19151     *v = a;
   19152     return 4;
   19153   }
   19154 
   19155   /* a: p0<<14 | p2 (masked) */
   19156   /* b: p1<<14 | p3 (unmasked) */
   19157   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   19158   /* moved CSE1 up */
   19159   /* a &= (0x7f<<14)|(0x7f); */
   19160   b &= (0x7f<<14)|(0x7f);
   19161   s = a;
   19162   /* s: p0<<14 | p2 (masked) */
   19163 
   19164   p++;
   19165   a = a<<14;
   19166   a |= *p;
   19167   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
   19168   if (!(a&0x80))
   19169   {
   19170     /* we can skip these cause they were (effectively) done above in calc'ing s */
   19171     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
   19172     /* b &= (0x7f<<14)|(0x7f); */
   19173     b = b<<7;
   19174     a |= b;
   19175     s = s>>18;
   19176     *v = ((u64)s)<<32 | a;
   19177     return 5;
   19178   }
   19179 
   19180   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   19181   s = s<<7;
   19182   s |= b;
   19183   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   19184 
   19185   p++;
   19186   b = b<<14;
   19187   b |= *p;
   19188   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
   19189   if (!(b&0x80))
   19190   {
   19191     /* we can skip this cause it was (effectively) done above in calc'ing s */
   19192     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
   19193     a &= (0x7f<<14)|(0x7f);
   19194     a = a<<7;
   19195     a |= b;
   19196     s = s>>18;
   19197     *v = ((u64)s)<<32 | a;
   19198     return 6;
   19199   }
   19200 
   19201   p++;
   19202   a = a<<14;
   19203   a |= *p;
   19204   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
   19205   if (!(a&0x80))
   19206   {
   19207     a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
   19208     b &= (0x7f<<14)|(0x7f);
   19209     b = b<<7;
   19210     a |= b;
   19211     s = s>>11;
   19212     *v = ((u64)s)<<32 | a;
   19213     return 7;
   19214   }
   19215 
   19216   /* CSE2 from below */
   19217   a &= (0x7f<<14)|(0x7f);
   19218   p++;
   19219   b = b<<14;
   19220   b |= *p;
   19221   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
   19222   if (!(b&0x80))
   19223   {
   19224     b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
   19225     /* moved CSE2 up */
   19226     /* a &= (0x7f<<14)|(0x7f); */
   19227     a = a<<7;
   19228     a |= b;
   19229     s = s>>4;
   19230     *v = ((u64)s)<<32 | a;
   19231     return 8;
   19232   }
   19233 
   19234   p++;
   19235   a = a<<15;
   19236   a |= *p;
   19237   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
   19238 
   19239   /* moved CSE2 up */
   19240   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
   19241   b &= (0x7f<<14)|(0x7f);
   19242   b = b<<8;
   19243   a |= b;
   19244 
   19245   s = s<<4;
   19246   b = p[-4];
   19247   b &= 0x7f;
   19248   b = b>>3;
   19249   s |= b;
   19250 
   19251   *v = ((u64)s)<<32 | a;
   19252 
   19253   return 9;
   19254 }
   19255 
   19256 /*
   19257 ** Read a 32-bit variable-length integer from memory starting at p[0].
   19258 ** Return the number of bytes read.  The value is stored in *v.
   19259 **
   19260 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
   19261 ** integer, then set *v to 0xffffffff.
   19262 **
   19263 ** A MACRO version, getVarint32, is provided which inlines the
   19264 ** single-byte case.  All code should use the MACRO version as
   19265 ** this function assumes the single-byte case has already been handled.
   19266 */
   19267 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
   19268   u32 a,b;
   19269 
   19270   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
   19271   ** by the getVarin32() macro */
   19272   a = *p;
   19273   /* a: p0 (unmasked) */
   19274 #ifndef getVarint32
   19275   if (!(a&0x80))
   19276   {
   19277     /* Values between 0 and 127 */
   19278     *v = a;
   19279     return 1;
   19280   }
   19281 #endif
   19282 
   19283   /* The 2-byte case */
   19284   p++;
   19285   b = *p;
   19286   /* b: p1 (unmasked) */
   19287   if (!(b&0x80))
   19288   {
   19289     /* Values between 128 and 16383 */
   19290     a &= 0x7f;
   19291     a = a<<7;
   19292     *v = a | b;
   19293     return 2;
   19294   }
   19295 
   19296   /* The 3-byte case */
   19297   p++;
   19298   a = a<<14;
   19299   a |= *p;
   19300   /* a: p0<<14 | p2 (unmasked) */
   19301   if (!(a&0x80))
   19302   {
   19303     /* Values between 16384 and 2097151 */
   19304     a &= (0x7f<<14)|(0x7f);
   19305     b &= 0x7f;
   19306     b = b<<7;
   19307     *v = a | b;
   19308     return 3;
   19309   }
   19310 
   19311   /* A 32-bit varint is used to store size information in btrees.
   19312   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
   19313   ** A 3-byte varint is sufficient, for example, to record the size
   19314   ** of a 1048569-byte BLOB or string.
   19315   **
   19316   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
   19317   ** rare larger cases can be handled by the slower 64-bit varint
   19318   ** routine.
   19319   */
   19320 #if 1
   19321   {
   19322     u64 v64;
   19323     u8 n;
   19324 
   19325     p -= 2;
   19326     n = sqlite3GetVarint(p, &v64);
   19327     assert( n>3 && n<=9 );
   19328     if( (v64 & SQLITE_MAX_U32)!=v64 ){
   19329       *v = 0xffffffff;
   19330     }else{
   19331       *v = (u32)v64;
   19332     }
   19333     return n;
   19334   }
   19335 
   19336 #else
   19337   /* For following code (kept for historical record only) shows an
   19338   ** unrolling for the 3- and 4-byte varint cases.  This code is
   19339   ** slightly faster, but it is also larger and much harder to test.
   19340   */
   19341   p++;
   19342   b = b<<14;
   19343   b |= *p;
   19344   /* b: p1<<14 | p3 (unmasked) */
   19345   if (!(b&0x80))
   19346   {
   19347     /* Values between 2097152 and 268435455 */
   19348     b &= (0x7f<<14)|(0x7f);
   19349     a &= (0x7f<<14)|(0x7f);
   19350     a = a<<7;
   19351     *v = a | b;
   19352     return 4;
   19353   }
   19354 
   19355   p++;
   19356   a = a<<14;
   19357   a |= *p;
   19358   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
   19359   if (!(a&0x80))
   19360   {
   19361     /* Walues  between 268435456 and 34359738367 */
   19362     a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
   19363     b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
   19364     b = b<<7;
   19365     *v = a | b;
   19366     return 5;
   19367   }
   19368 
   19369   /* We can only reach this point when reading a corrupt database
   19370   ** file.  In that case we are not in any hurry.  Use the (relatively
   19371   ** slow) general-purpose sqlite3GetVarint() routine to extract the
   19372   ** value. */
   19373   {
   19374     u64 v64;
   19375     u8 n;
   19376 
   19377     p -= 4;
   19378     n = sqlite3GetVarint(p, &v64);
   19379     assert( n>5 && n<=9 );
   19380     *v = (u32)v64;
   19381     return n;
   19382   }
   19383 #endif
   19384 }
   19385 
   19386 /*
   19387 ** Return the number of bytes that will be needed to store the given
   19388 ** 64-bit integer.
   19389 */
   19390 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
   19391   int i = 0;
   19392   do{
   19393     i++;
   19394     v >>= 7;
   19395   }while( v!=0 && ALWAYS(i<9) );
   19396   return i;
   19397 }
   19398 
   19399 
   19400 /*
   19401 ** Read or write a four-byte big-endian integer value.
   19402 */
   19403 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
   19404   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
   19405 }
   19406 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
   19407   p[0] = (u8)(v>>24);
   19408   p[1] = (u8)(v>>16);
   19409   p[2] = (u8)(v>>8);
   19410   p[3] = (u8)v;
   19411 }
   19412 
   19413 
   19414 
   19415 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
   19416 /*
   19417 ** Translate a single byte of Hex into an integer.
   19418 ** This routine only works if h really is a valid hexadecimal
   19419 ** character:  0..9a..fA..F
   19420 */
   19421 static u8 hexToInt(int h){
   19422   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
   19423 #ifdef SQLITE_ASCII
   19424   h += 9*(1&(h>>6));
   19425 #endif
   19426 #ifdef SQLITE_EBCDIC
   19427   h += 9*(1&~(h>>4));
   19428 #endif
   19429   return (u8)(h & 0xf);
   19430 }
   19431 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
   19432 
   19433 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
   19434 /*
   19435 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
   19436 ** value.  Return a pointer to its binary value.  Space to hold the
   19437 ** binary value has been obtained from malloc and must be freed by
   19438 ** the calling routine.
   19439 */
   19440 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
   19441   char *zBlob;
   19442   int i;
   19443 
   19444   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
   19445   n--;
   19446   if( zBlob ){
   19447     for(i=0; i<n; i+=2){
   19448       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
   19449     }
   19450     zBlob[i/2] = 0;
   19451   }
   19452   return zBlob;
   19453 }
   19454 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
   19455 
   19456 /*
   19457 ** Log an error that is an API call on a connection pointer that should
   19458 ** not have been used.  The "type" of connection pointer is given as the
   19459 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
   19460 */
   19461 static void logBadConnection(const char *zType){
   19462   sqlite3_log(SQLITE_MISUSE,
   19463      "API call with %s database connection pointer",
   19464      zType
   19465   );
   19466 }
   19467 
   19468 /*
   19469 ** Check to make sure we have a valid db pointer.  This test is not
   19470 ** foolproof but it does provide some measure of protection against
   19471 ** misuse of the interface such as passing in db pointers that are
   19472 ** NULL or which have been previously closed.  If this routine returns
   19473 ** 1 it means that the db pointer is valid and 0 if it should not be
   19474 ** dereferenced for any reason.  The calling function should invoke
   19475 ** SQLITE_MISUSE immediately.
   19476 **
   19477 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
   19478 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
   19479 ** open properly and is not fit for general use but which can be
   19480 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
   19481 */
   19482 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
   19483   u32 magic;
   19484   if( db==0 ){
   19485     logBadConnection("NULL");
   19486     return 0;
   19487   }
   19488   magic = db->magic;
   19489   if( magic!=SQLITE_MAGIC_OPEN ){
   19490     if( !sqlite3SafetyCheckSickOrOk(db) ){
   19491       logBadConnection("unopened");
   19492     }
   19493     return 0;
   19494   }else{
   19495     return 1;
   19496   }
   19497 }
   19498 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
   19499   u32 magic;
   19500   magic = db->magic;
   19501   if( magic!=SQLITE_MAGIC_SICK &&
   19502       magic!=SQLITE_MAGIC_OPEN &&
   19503       magic!=SQLITE_MAGIC_BUSY ){
   19504     logBadConnection("invalid");
   19505     return 0;
   19506   }else{
   19507     return 1;
   19508   }
   19509 }
   19510 
   19511 /************** End of util.c ************************************************/
   19512 /************** Begin file hash.c ********************************************/
   19513 /*
   19514 ** 2001 September 22
   19515 **
   19516 ** The author disclaims copyright to this source code.  In place of
   19517 ** a legal notice, here is a blessing:
   19518 **
   19519 **    May you do good and not evil.
   19520 **    May you find forgiveness for yourself and forgive others.
   19521 **    May you share freely, never taking more than you give.
   19522 **
   19523 *************************************************************************
   19524 ** This is the implementation of generic hash-tables
   19525 ** used in SQLite.
   19526 */
   19527 
   19528 /* Turn bulk memory into a hash table object by initializing the
   19529 ** fields of the Hash structure.
   19530 **
   19531 ** "pNew" is a pointer to the hash table that is to be initialized.
   19532 */
   19533 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
   19534   assert( pNew!=0 );
   19535   pNew->first = 0;
   19536   pNew->count = 0;
   19537   pNew->htsize = 0;
   19538   pNew->ht = 0;
   19539 }
   19540 
   19541 /* Remove all entries from a hash table.  Reclaim all memory.
   19542 ** Call this routine to delete a hash table or to reset a hash table
   19543 ** to the empty state.
   19544 */
   19545 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
   19546   HashElem *elem;         /* For looping over all elements of the table */
   19547 
   19548   assert( pH!=0 );
   19549   elem = pH->first;
   19550   pH->first = 0;
   19551   sqlite3_free(pH->ht);
   19552   pH->ht = 0;
   19553   pH->htsize = 0;
   19554   while( elem ){
   19555     HashElem *next_elem = elem->next;
   19556     sqlite3_free(elem);
   19557     elem = next_elem;
   19558   }
   19559   pH->count = 0;
   19560 }
   19561 
   19562 /*
   19563 ** The hashing function.
   19564 */
   19565 static unsigned int strHash(const char *z, int nKey){
   19566   int h = 0;
   19567   assert( nKey>=0 );
   19568   while( nKey > 0  ){
   19569     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
   19570     nKey--;
   19571   }
   19572   return h;
   19573 }
   19574 
   19575 
   19576 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
   19577 ** insert pNew into the pEntry hash bucket.
   19578 */
   19579 static void insertElement(
   19580   Hash *pH,              /* The complete hash table */
   19581   struct _ht *pEntry,    /* The entry into which pNew is inserted */
   19582   HashElem *pNew         /* The element to be inserted */
   19583 ){
   19584   HashElem *pHead;       /* First element already in pEntry */
   19585   if( pEntry ){
   19586     pHead = pEntry->count ? pEntry->chain : 0;
   19587     pEntry->count++;
   19588     pEntry->chain = pNew;
   19589   }else{
   19590     pHead = 0;
   19591   }
   19592   if( pHead ){
   19593     pNew->next = pHead;
   19594     pNew->prev = pHead->prev;
   19595     if( pHead->prev ){ pHead->prev->next = pNew; }
   19596     else             { pH->first = pNew; }
   19597     pHead->prev = pNew;
   19598   }else{
   19599     pNew->next = pH->first;
   19600     if( pH->first ){ pH->first->prev = pNew; }
   19601     pNew->prev = 0;
   19602     pH->first = pNew;
   19603   }
   19604 }
   19605 
   19606 
   19607 /* Resize the hash table so that it cantains "new_size" buckets.
   19608 **
   19609 ** The hash table might fail to resize if sqlite3_malloc() fails or
   19610 ** if the new size is the same as the prior size.
   19611 ** Return TRUE if the resize occurs and false if not.
   19612 */
   19613 static int rehash(Hash *pH, unsigned int new_size){
   19614   struct _ht *new_ht;            /* The new hash table */
   19615   HashElem *elem, *next_elem;    /* For looping over existing elements */
   19616 
   19617 #if SQLITE_MALLOC_SOFT_LIMIT>0
   19618   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
   19619     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
   19620   }
   19621   if( new_size==pH->htsize ) return 0;
   19622 #endif
   19623 
   19624   /* The inability to allocates space for a larger hash table is
   19625   ** a performance hit but it is not a fatal error.  So mark the
   19626   ** allocation as a benign.
   19627   */
   19628   sqlite3BeginBenignMalloc();
   19629   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
   19630   sqlite3EndBenignMalloc();
   19631 
   19632   if( new_ht==0 ) return 0;
   19633   sqlite3_free(pH->ht);
   19634   pH->ht = new_ht;
   19635   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
   19636   memset(new_ht, 0, new_size*sizeof(struct _ht));
   19637   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
   19638     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
   19639     next_elem = elem->next;
   19640     insertElement(pH, &new_ht[h], elem);
   19641   }
   19642   return 1;
   19643 }
   19644 
   19645 /* This function (for internal use only) locates an element in an
   19646 ** hash table that matches the given key.  The hash for this key has
   19647 ** already been computed and is passed as the 4th parameter.
   19648 */
   19649 static HashElem *findElementGivenHash(
   19650   const Hash *pH,     /* The pH to be searched */
   19651   const char *pKey,   /* The key we are searching for */
   19652   int nKey,           /* Bytes in key (not counting zero terminator) */
   19653   unsigned int h      /* The hash for this key. */
   19654 ){
   19655   HashElem *elem;                /* Used to loop thru the element list */
   19656   int count;                     /* Number of elements left to test */
   19657 
   19658   if( pH->ht ){
   19659     struct _ht *pEntry = &pH->ht[h];
   19660     elem = pEntry->chain;
   19661     count = pEntry->count;
   19662   }else{
   19663     elem = pH->first;
   19664     count = pH->count;
   19665   }
   19666   while( count-- && ALWAYS(elem) ){
   19667     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
   19668       return elem;
   19669     }
   19670     elem = elem->next;
   19671   }
   19672   return 0;
   19673 }
   19674 
   19675 /* Remove a single entry from the hash table given a pointer to that
   19676 ** element and a hash on the element's key.
   19677 */
   19678 static void removeElementGivenHash(
   19679   Hash *pH,         /* The pH containing "elem" */
   19680   HashElem* elem,   /* The element to be removed from the pH */
   19681   unsigned int h    /* Hash value for the element */
   19682 ){
   19683   struct _ht *pEntry;
   19684   if( elem->prev ){
   19685     elem->prev->next = elem->next;
   19686   }else{
   19687     pH->first = elem->next;
   19688   }
   19689   if( elem->next ){
   19690     elem->next->prev = elem->prev;
   19691   }
   19692   if( pH->ht ){
   19693     pEntry = &pH->ht[h];
   19694     if( pEntry->chain==elem ){
   19695       pEntry->chain = elem->next;
   19696     }
   19697     pEntry->count--;
   19698     assert( pEntry->count>=0 );
   19699   }
   19700   sqlite3_free( elem );
   19701   pH->count--;
   19702   if( pH->count<=0 ){
   19703     assert( pH->first==0 );
   19704     assert( pH->count==0 );
   19705     sqlite3HashClear(pH);
   19706   }
   19707 }
   19708 
   19709 /* Attempt to locate an element of the hash table pH with a key
   19710 ** that matches pKey,nKey.  Return the data for this element if it is
   19711 ** found, or NULL if there is no match.
   19712 */
   19713 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
   19714   HashElem *elem;    /* The element that matches key */
   19715   unsigned int h;    /* A hash on key */
   19716 
   19717   assert( pH!=0 );
   19718   assert( pKey!=0 );
   19719   assert( nKey>=0 );
   19720   if( pH->ht ){
   19721     h = strHash(pKey, nKey) % pH->htsize;
   19722   }else{
   19723     h = 0;
   19724   }
   19725   elem = findElementGivenHash(pH, pKey, nKey, h);
   19726   return elem ? elem->data : 0;
   19727 }
   19728 
   19729 /* Insert an element into the hash table pH.  The key is pKey,nKey
   19730 ** and the data is "data".
   19731 **
   19732 ** If no element exists with a matching key, then a new
   19733 ** element is created and NULL is returned.
   19734 **
   19735 ** If another element already exists with the same key, then the
   19736 ** new data replaces the old data and the old data is returned.
   19737 ** The key is not copied in this instance.  If a malloc fails, then
   19738 ** the new data is returned and the hash table is unchanged.
   19739 **
   19740 ** If the "data" parameter to this function is NULL, then the
   19741 ** element corresponding to "key" is removed from the hash table.
   19742 */
   19743 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
   19744   unsigned int h;       /* the hash of the key modulo hash table size */
   19745   HashElem *elem;       /* Used to loop thru the element list */
   19746   HashElem *new_elem;   /* New element added to the pH */
   19747 
   19748   assert( pH!=0 );
   19749   assert( pKey!=0 );
   19750   assert( nKey>=0 );
   19751   if( pH->htsize ){
   19752     h = strHash(pKey, nKey) % pH->htsize;
   19753   }else{
   19754     h = 0;
   19755   }
   19756   elem = findElementGivenHash(pH,pKey,nKey,h);
   19757   if( elem ){
   19758     void *old_data = elem->data;
   19759     if( data==0 ){
   19760       removeElementGivenHash(pH,elem,h);
   19761     }else{
   19762       elem->data = data;
   19763       elem->pKey = pKey;
   19764       assert(nKey==elem->nKey);
   19765     }
   19766     return old_data;
   19767   }
   19768   if( data==0 ) return 0;
   19769   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
   19770   if( new_elem==0 ) return data;
   19771   new_elem->pKey = pKey;
   19772   new_elem->nKey = nKey;
   19773   new_elem->data = data;
   19774   pH->count++;
   19775   if( pH->count>=10 && pH->count > 2*pH->htsize ){
   19776     if( rehash(pH, pH->count*2) ){
   19777       assert( pH->htsize>0 );
   19778       h = strHash(pKey, nKey) % pH->htsize;
   19779     }
   19780   }
   19781   if( pH->ht ){
   19782     insertElement(pH, &pH->ht[h], new_elem);
   19783   }else{
   19784     insertElement(pH, 0, new_elem);
   19785   }
   19786   return 0;
   19787 }
   19788 
   19789 /************** End of hash.c ************************************************/
   19790 /************** Begin file opcodes.c *****************************************/
   19791 /* Automatically generated.  Do not edit */
   19792 /* See the mkopcodec.awk script for details. */
   19793 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   19794 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
   19795  static const char *const azName[] = { "?",
   19796      /*   1 */ "Goto",
   19797      /*   2 */ "Gosub",
   19798      /*   3 */ "Return",
   19799      /*   4 */ "Yield",
   19800      /*   5 */ "HaltIfNull",
   19801      /*   6 */ "Halt",
   19802      /*   7 */ "Integer",
   19803      /*   8 */ "Int64",
   19804      /*   9 */ "String",
   19805      /*  10 */ "Null",
   19806      /*  11 */ "Blob",
   19807      /*  12 */ "Variable",
   19808      /*  13 */ "Move",
   19809      /*  14 */ "Copy",
   19810      /*  15 */ "SCopy",
   19811      /*  16 */ "ResultRow",
   19812      /*  17 */ "CollSeq",
   19813      /*  18 */ "Function",
   19814      /*  19 */ "Not",
   19815      /*  20 */ "AddImm",
   19816      /*  21 */ "MustBeInt",
   19817      /*  22 */ "RealAffinity",
   19818      /*  23 */ "Permutation",
   19819      /*  24 */ "Compare",
   19820      /*  25 */ "Jump",
   19821      /*  26 */ "If",
   19822      /*  27 */ "IfNot",
   19823      /*  28 */ "Column",
   19824      /*  29 */ "Affinity",
   19825      /*  30 */ "MakeRecord",
   19826      /*  31 */ "Count",
   19827      /*  32 */ "Savepoint",
   19828      /*  33 */ "AutoCommit",
   19829      /*  34 */ "Transaction",
   19830      /*  35 */ "ReadCookie",
   19831      /*  36 */ "SetCookie",
   19832      /*  37 */ "VerifyCookie",
   19833      /*  38 */ "OpenRead",
   19834      /*  39 */ "OpenWrite",
   19835      /*  40 */ "OpenEphemeral",
   19836      /*  41 */ "OpenPseudo",
   19837      /*  42 */ "Close",
   19838      /*  43 */ "SeekLt",
   19839      /*  44 */ "SeekLe",
   19840      /*  45 */ "SeekGe",
   19841      /*  46 */ "SeekGt",
   19842      /*  47 */ "Seek",
   19843      /*  48 */ "NotFound",
   19844      /*  49 */ "Found",
   19845      /*  50 */ "IsUnique",
   19846      /*  51 */ "NotExists",
   19847      /*  52 */ "Sequence",
   19848      /*  53 */ "NewRowid",
   19849      /*  54 */ "Insert",
   19850      /*  55 */ "InsertInt",
   19851      /*  56 */ "Delete",
   19852      /*  57 */ "ResetCount",
   19853      /*  58 */ "RowKey",
   19854      /*  59 */ "RowData",
   19855      /*  60 */ "Rowid",
   19856      /*  61 */ "NullRow",
   19857      /*  62 */ "Last",
   19858      /*  63 */ "Sort",
   19859      /*  64 */ "Rewind",
   19860      /*  65 */ "Prev",
   19861      /*  66 */ "Next",
   19862      /*  67 */ "IdxInsert",
   19863      /*  68 */ "Or",
   19864      /*  69 */ "And",
   19865      /*  70 */ "IdxDelete",
   19866      /*  71 */ "IdxRowid",
   19867      /*  72 */ "IdxLT",
   19868      /*  73 */ "IsNull",
   19869      /*  74 */ "NotNull",
   19870      /*  75 */ "Ne",
   19871      /*  76 */ "Eq",
   19872      /*  77 */ "Gt",
   19873      /*  78 */ "Le",
   19874      /*  79 */ "Lt",
   19875      /*  80 */ "Ge",
   19876      /*  81 */ "IdxGE",
   19877      /*  82 */ "BitAnd",
   19878      /*  83 */ "BitOr",
   19879      /*  84 */ "ShiftLeft",
   19880      /*  85 */ "ShiftRight",
   19881      /*  86 */ "Add",
   19882      /*  87 */ "Subtract",
   19883      /*  88 */ "Multiply",
   19884      /*  89 */ "Divide",
   19885      /*  90 */ "Remainder",
   19886      /*  91 */ "Concat",
   19887      /*  92 */ "Destroy",
   19888      /*  93 */ "BitNot",
   19889      /*  94 */ "String8",
   19890      /*  95 */ "Clear",
   19891      /*  96 */ "CreateIndex",
   19892      /*  97 */ "CreateTable",
   19893      /*  98 */ "ParseSchema",
   19894      /*  99 */ "LoadAnalysis",
   19895      /* 100 */ "DropTable",
   19896      /* 101 */ "DropIndex",
   19897      /* 102 */ "DropTrigger",
   19898      /* 103 */ "IntegrityCk",
   19899      /* 104 */ "RowSetAdd",
   19900      /* 105 */ "RowSetRead",
   19901      /* 106 */ "RowSetTest",
   19902      /* 107 */ "Program",
   19903      /* 108 */ "Param",
   19904      /* 109 */ "FkCounter",
   19905      /* 110 */ "FkIfZero",
   19906      /* 111 */ "MemMax",
   19907      /* 112 */ "IfPos",
   19908      /* 113 */ "IfNeg",
   19909      /* 114 */ "IfZero",
   19910      /* 115 */ "AggStep",
   19911      /* 116 */ "AggFinal",
   19912      /* 117 */ "Vacuum",
   19913      /* 118 */ "IncrVacuum",
   19914      /* 119 */ "Expire",
   19915      /* 120 */ "TableLock",
   19916      /* 121 */ "VBegin",
   19917      /* 122 */ "VCreate",
   19918      /* 123 */ "VDestroy",
   19919      /* 124 */ "VOpen",
   19920      /* 125 */ "VFilter",
   19921      /* 126 */ "VColumn",
   19922      /* 127 */ "VNext",
   19923      /* 128 */ "VRename",
   19924      /* 129 */ "VUpdate",
   19925      /* 130 */ "Real",
   19926      /* 131 */ "Pagecount",
   19927      /* 132 */ "Trace",
   19928      /* 133 */ "Noop",
   19929      /* 134 */ "Explain",
   19930      /* 135 */ "NotUsed_135",
   19931      /* 136 */ "NotUsed_136",
   19932      /* 137 */ "NotUsed_137",
   19933      /* 138 */ "NotUsed_138",
   19934      /* 139 */ "NotUsed_139",
   19935      /* 140 */ "NotUsed_140",
   19936      /* 141 */ "ToText",
   19937      /* 142 */ "ToBlob",
   19938      /* 143 */ "ToNumeric",
   19939      /* 144 */ "ToInt",
   19940      /* 145 */ "ToReal",
   19941   };
   19942   return azName[i];
   19943 }
   19944 #endif
   19945 
   19946 /************** End of opcodes.c *********************************************/
   19947 /************** Begin file os_os2.c ******************************************/
   19948 /*
   19949 ** 2006 Feb 14
   19950 **
   19951 ** The author disclaims copyright to this source code.  In place of
   19952 ** a legal notice, here is a blessing:
   19953 **
   19954 **    May you do good and not evil.
   19955 **    May you find forgiveness for yourself and forgive others.
   19956 **    May you share freely, never taking more than you give.
   19957 **
   19958 ******************************************************************************
   19959 **
   19960 ** This file contains code that is specific to OS/2.
   19961 */
   19962 
   19963 
   19964 #if SQLITE_OS_OS2
   19965 
   19966 /*
   19967 ** A Note About Memory Allocation:
   19968 **
   19969 ** This driver uses malloc()/free() directly rather than going through
   19970 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
   19971 ** are designed for use on embedded systems where memory is scarce and
   19972 ** malloc failures happen frequently.  OS/2 does not typically run on
   19973 ** embedded systems, and when it does the developers normally have bigger
   19974 ** problems to worry about than running out of memory.  So there is not
   19975 ** a compelling need to use the wrappers.
   19976 **
   19977 ** But there is a good reason to not use the wrappers.  If we use the
   19978 ** wrappers then we will get simulated malloc() failures within this
   19979 ** driver.  And that causes all kinds of problems for our tests.  We
   19980 ** could enhance SQLite to deal with simulated malloc failures within
   19981 ** the OS driver, but the code to deal with those failure would not
   19982 ** be exercised on Linux (which does not need to malloc() in the driver)
   19983 ** and so we would have difficulty writing coverage tests for that
   19984 ** code.  Better to leave the code out, we think.
   19985 **
   19986 ** The point of this discussion is as follows:  When creating a new
   19987 ** OS layer for an embedded system, if you use this file as an example,
   19988 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
   19989 ** desktops but not so well in embedded systems.
   19990 */
   19991 
   19992 /*
   19993 ** Macros used to determine whether or not to use threads.
   19994 */
   19995 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
   19996 # define SQLITE_OS2_THREADS 1
   19997 #endif
   19998 
   19999 /*
   20000 ** Include code that is common to all os_*.c files
   20001 */
   20002 /************** Include os_common.h in the middle of os_os2.c ****************/
   20003 /************** Begin file os_common.h ***************************************/
   20004 /*
   20005 ** 2004 May 22
   20006 **
   20007 ** The author disclaims copyright to this source code.  In place of
   20008 ** a legal notice, here is a blessing:
   20009 **
   20010 **    May you do good and not evil.
   20011 **    May you find forgiveness for yourself and forgive others.
   20012 **    May you share freely, never taking more than you give.
   20013 **
   20014 ******************************************************************************
   20015 **
   20016 ** This file contains macros and a little bit of code that is common to
   20017 ** all of the platform-specific files (os_*.c) and is #included into those
   20018 ** files.
   20019 **
   20020 ** This file should be #included by the os_*.c files only.  It is not a
   20021 ** general purpose header file.
   20022 */
   20023 #ifndef _OS_COMMON_H_
   20024 #define _OS_COMMON_H_
   20025 
   20026 /*
   20027 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   20028 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   20029 ** switch.  The following code should catch this problem at compile-time.
   20030 */
   20031 #ifdef MEMORY_DEBUG
   20032 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   20033 #endif
   20034 
   20035 #ifdef SQLITE_DEBUG
   20036 SQLITE_PRIVATE int sqlite3OSTrace = 0;
   20037 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
   20038 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
   20039 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
   20040 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
   20041 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
   20042 #define OSTRACE6(X,Y,Z,A,B,C) \
   20043     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
   20044 #define OSTRACE7(X,Y,Z,A,B,C,D) \
   20045     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
   20046 #else
   20047 #define OSTRACE1(X)
   20048 #define OSTRACE2(X,Y)
   20049 #define OSTRACE3(X,Y,Z)
   20050 #define OSTRACE4(X,Y,Z,A)
   20051 #define OSTRACE5(X,Y,Z,A,B)
   20052 #define OSTRACE6(X,Y,Z,A,B,C)
   20053 #define OSTRACE7(X,Y,Z,A,B,C,D)
   20054 #endif
   20055 
   20056 /*
   20057 ** Macros for performance tracing.  Normally turned off.  Only works
   20058 ** on i486 hardware.
   20059 */
   20060 #ifdef SQLITE_PERFORMANCE_TRACE
   20061 
   20062 /*
   20063 ** hwtime.h contains inline assembler code for implementing
   20064 ** high-performance timing routines.
   20065 */
   20066 /************** Include hwtime.h in the middle of os_common.h ****************/
   20067 /************** Begin file hwtime.h ******************************************/
   20068 /*
   20069 ** 2008 May 27
   20070 **
   20071 ** The author disclaims copyright to this source code.  In place of
   20072 ** a legal notice, here is a blessing:
   20073 **
   20074 **    May you do good and not evil.
   20075 **    May you find forgiveness for yourself and forgive others.
   20076 **    May you share freely, never taking more than you give.
   20077 **
   20078 ******************************************************************************
   20079 **
   20080 ** This file contains inline asm code for retrieving "high-performance"
   20081 ** counters for x86 class CPUs.
   20082 */
   20083 #ifndef _HWTIME_H_
   20084 #define _HWTIME_H_
   20085 
   20086 /*
   20087 ** The following routine only works on pentium-class (or newer) processors.
   20088 ** It uses the RDTSC opcode to read the cycle count value out of the
   20089 ** processor and returns that value.  This can be used for high-res
   20090 ** profiling.
   20091 */
   20092 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   20093       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   20094 
   20095   #if defined(__GNUC__)
   20096 
   20097   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   20098      unsigned int lo, hi;
   20099      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   20100      return (sqlite_uint64)hi << 32 | lo;
   20101   }
   20102 
   20103   #elif defined(_MSC_VER)
   20104 
   20105   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   20106      __asm {
   20107         rdtsc
   20108         ret       ; return value at EDX:EAX
   20109      }
   20110   }
   20111 
   20112   #endif
   20113 
   20114 #elif (defined(__GNUC__) && defined(__x86_64__))
   20115 
   20116   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   20117       unsigned long val;
   20118       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   20119       return val;
   20120   }
   20121 
   20122 #elif (defined(__GNUC__) && defined(__ppc__))
   20123 
   20124   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   20125       unsigned long long retval;
   20126       unsigned long junk;
   20127       __asm__ __volatile__ ("\n\
   20128           1:      mftbu   %1\n\
   20129                   mftb    %L0\n\
   20130                   mftbu   %0\n\
   20131                   cmpw    %0,%1\n\
   20132                   bne     1b"
   20133                   : "=r" (retval), "=r" (junk));
   20134       return retval;
   20135   }
   20136 
   20137 #else
   20138 
   20139   #error Need implementation of sqlite3Hwtime() for your platform.
   20140 
   20141   /*
   20142   ** To compile without implementing sqlite3Hwtime() for your platform,
   20143   ** you can remove the above #error and use the following
   20144   ** stub function.  You will lose timing support for many
   20145   ** of the debugging and testing utilities, but it should at
   20146   ** least compile and run.
   20147   */
   20148 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   20149 
   20150 #endif
   20151 
   20152 #endif /* !defined(_HWTIME_H_) */
   20153 
   20154 /************** End of hwtime.h **********************************************/
   20155 /************** Continuing where we left off in os_common.h ******************/
   20156 
   20157 static sqlite_uint64 g_start;
   20158 static sqlite_uint64 g_elapsed;
   20159 #define TIMER_START       g_start=sqlite3Hwtime()
   20160 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   20161 #define TIMER_ELAPSED     g_elapsed
   20162 #else
   20163 #define TIMER_START
   20164 #define TIMER_END
   20165 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   20166 #endif
   20167 
   20168 /*
   20169 ** If we compile with the SQLITE_TEST macro set, then the following block
   20170 ** of code will give us the ability to simulate a disk I/O error.  This
   20171 ** is used for testing the I/O recovery logic.
   20172 */
   20173 #ifdef SQLITE_TEST
   20174 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   20175 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   20176 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   20177 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   20178 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   20179 SQLITE_API int sqlite3_diskfull_pending = 0;
   20180 SQLITE_API int sqlite3_diskfull = 0;
   20181 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   20182 #define SimulateIOError(CODE)  \
   20183   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   20184        || sqlite3_io_error_pending-- == 1 )  \
   20185               { local_ioerr(); CODE; }
   20186 static void local_ioerr(){
   20187   IOTRACE(("IOERR\n"));
   20188   sqlite3_io_error_hit++;
   20189   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   20190 }
   20191 #define SimulateDiskfullError(CODE) \
   20192    if( sqlite3_diskfull_pending ){ \
   20193      if( sqlite3_diskfull_pending == 1 ){ \
   20194        local_ioerr(); \
   20195        sqlite3_diskfull = 1; \
   20196        sqlite3_io_error_hit = 1; \
   20197        CODE; \
   20198      }else{ \
   20199        sqlite3_diskfull_pending--; \
   20200      } \
   20201    }
   20202 #else
   20203 #define SimulateIOErrorBenign(X)
   20204 #define SimulateIOError(A)
   20205 #define SimulateDiskfullError(A)
   20206 #endif
   20207 
   20208 /*
   20209 ** When testing, keep a count of the number of open files.
   20210 */
   20211 #ifdef SQLITE_TEST
   20212 SQLITE_API int sqlite3_open_file_count = 0;
   20213 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   20214 #else
   20215 #define OpenCounter(X)
   20216 #endif
   20217 
   20218 #endif /* !defined(_OS_COMMON_H_) */
   20219 
   20220 /************** End of os_common.h *******************************************/
   20221 /************** Continuing where we left off in os_os2.c *********************/
   20222 
   20223 /*
   20224 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
   20225 ** protability layer.
   20226 */
   20227 typedef struct os2File os2File;
   20228 struct os2File {
   20229   const sqlite3_io_methods *pMethod;  /* Always the first entry */
   20230   HFILE h;                  /* Handle for accessing the file */
   20231   char* pathToDel;          /* Name of file to delete on close, NULL if not */
   20232   unsigned char locktype;   /* Type of lock currently held on this file */
   20233 };
   20234 
   20235 #define LOCK_TIMEOUT 10L /* the default locking timeout */
   20236 
   20237 /*****************************************************************************
   20238 ** The next group of routines implement the I/O methods specified
   20239 ** by the sqlite3_io_methods object.
   20240 ******************************************************************************/
   20241 
   20242 /*
   20243 ** Close a file.
   20244 */
   20245 static int os2Close( sqlite3_file *id ){
   20246   APIRET rc = NO_ERROR;
   20247   os2File *pFile;
   20248   if( id && (pFile = (os2File*)id) != 0 ){
   20249     OSTRACE2( "CLOSE %d\n", pFile->h );
   20250     rc = DosClose( pFile->h );
   20251     pFile->locktype = NO_LOCK;
   20252     if( pFile->pathToDel != NULL ){
   20253       rc = DosForceDelete( (PSZ)pFile->pathToDel );
   20254       free( pFile->pathToDel );
   20255       pFile->pathToDel = NULL;
   20256     }
   20257     id = 0;
   20258     OpenCounter( -1 );
   20259   }
   20260 
   20261   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
   20262 }
   20263 
   20264 /*
   20265 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   20266 ** bytes were read successfully and SQLITE_IOERR if anything goes
   20267 ** wrong.
   20268 */
   20269 static int os2Read(
   20270   sqlite3_file *id,               /* File to read from */
   20271   void *pBuf,                     /* Write content into this buffer */
   20272   int amt,                        /* Number of bytes to read */
   20273   sqlite3_int64 offset            /* Begin reading at this offset */
   20274 ){
   20275   ULONG fileLocation = 0L;
   20276   ULONG got;
   20277   os2File *pFile = (os2File*)id;
   20278   assert( id!=0 );
   20279   SimulateIOError( return SQLITE_IOERR_READ );
   20280   OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
   20281   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
   20282     return SQLITE_IOERR;
   20283   }
   20284   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
   20285     return SQLITE_IOERR_READ;
   20286   }
   20287   if( got == (ULONG)amt )
   20288     return SQLITE_OK;
   20289   else {
   20290     /* Unread portions of the input buffer must be zero-filled */
   20291     memset(&((char*)pBuf)[got], 0, amt-got);
   20292     return SQLITE_IOERR_SHORT_READ;
   20293   }
   20294 }
   20295 
   20296 /*
   20297 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   20298 ** or some other error code on failure.
   20299 */
   20300 static int os2Write(
   20301   sqlite3_file *id,               /* File to write into */
   20302   const void *pBuf,               /* The bytes to be written */
   20303   int amt,                        /* Number of bytes to write */
   20304   sqlite3_int64 offset            /* Offset into the file to begin writing at */
   20305 ){
   20306   ULONG fileLocation = 0L;
   20307   APIRET rc = NO_ERROR;
   20308   ULONG wrote;
   20309   os2File *pFile = (os2File*)id;
   20310   assert( id!=0 );
   20311   SimulateIOError( return SQLITE_IOERR_WRITE );
   20312   SimulateDiskfullError( return SQLITE_FULL );
   20313   OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
   20314   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
   20315     return SQLITE_IOERR;
   20316   }
   20317   assert( amt>0 );
   20318   while( amt > 0 &&
   20319          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
   20320          wrote > 0
   20321   ){
   20322     amt -= wrote;
   20323     pBuf = &((char*)pBuf)[wrote];
   20324   }
   20325 
   20326   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
   20327 }
   20328 
   20329 /*
   20330 ** Truncate an open file to a specified size
   20331 */
   20332 static int os2Truncate( sqlite3_file *id, i64 nByte ){
   20333   APIRET rc = NO_ERROR;
   20334   os2File *pFile = (os2File*)id;
   20335   OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
   20336   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
   20337   rc = DosSetFileSize( pFile->h, nByte );
   20338   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
   20339 }
   20340 
   20341 #ifdef SQLITE_TEST
   20342 /*
   20343 ** Count the number of fullsyncs and normal syncs.  This is used to test
   20344 ** that syncs and fullsyncs are occuring at the right times.
   20345 */
   20346 SQLITE_API int sqlite3_sync_count = 0;
   20347 SQLITE_API int sqlite3_fullsync_count = 0;
   20348 #endif
   20349 
   20350 /*
   20351 ** Make sure all writes to a particular file are committed to disk.
   20352 */
   20353 static int os2Sync( sqlite3_file *id, int flags ){
   20354   os2File *pFile = (os2File*)id;
   20355   OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
   20356 #ifdef SQLITE_TEST
   20357   if( flags & SQLITE_SYNC_FULL){
   20358     sqlite3_fullsync_count++;
   20359   }
   20360   sqlite3_sync_count++;
   20361 #endif
   20362   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   20363   ** no-op
   20364   */
   20365 #ifdef SQLITE_NO_SYNC
   20366   UNUSED_PARAMETER(pFile);
   20367   return SQLITE_OK;
   20368 #else
   20369   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
   20370 #endif
   20371 }
   20372 
   20373 /*
   20374 ** Determine the current size of a file in bytes
   20375 */
   20376 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
   20377   APIRET rc = NO_ERROR;
   20378   FILESTATUS3 fsts3FileInfo;
   20379   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
   20380   assert( id!=0 );
   20381   SimulateIOError( return SQLITE_IOERR_FSTAT );
   20382   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
   20383   if( rc == NO_ERROR ){
   20384     *pSize = fsts3FileInfo.cbFile;
   20385     return SQLITE_OK;
   20386   }else{
   20387     return SQLITE_IOERR_FSTAT;
   20388   }
   20389 }
   20390 
   20391 /*
   20392 ** Acquire a reader lock.
   20393 */
   20394 static int getReadLock( os2File *pFile ){
   20395   FILELOCK  LockArea,
   20396             UnlockArea;
   20397   APIRET res;
   20398   memset(&LockArea, 0, sizeof(LockArea));
   20399   memset(&UnlockArea, 0, sizeof(UnlockArea));
   20400   LockArea.lOffset = SHARED_FIRST;
   20401   LockArea.lRange = SHARED_SIZE;
   20402   UnlockArea.lOffset = 0L;
   20403   UnlockArea.lRange = 0L;
   20404   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
   20405   OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
   20406   return res;
   20407 }
   20408 
   20409 /*
   20410 ** Undo a readlock
   20411 */
   20412 static int unlockReadLock( os2File *id ){
   20413   FILELOCK  LockArea,
   20414             UnlockArea;
   20415   APIRET res;
   20416   memset(&LockArea, 0, sizeof(LockArea));
   20417   memset(&UnlockArea, 0, sizeof(UnlockArea));
   20418   LockArea.lOffset = 0L;
   20419   LockArea.lRange = 0L;
   20420   UnlockArea.lOffset = SHARED_FIRST;
   20421   UnlockArea.lRange = SHARED_SIZE;
   20422   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
   20423   OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
   20424   return res;
   20425 }
   20426 
   20427 /*
   20428 ** Lock the file with the lock specified by parameter locktype - one
   20429 ** of the following:
   20430 **
   20431 **     (1) SHARED_LOCK
   20432 **     (2) RESERVED_LOCK
   20433 **     (3) PENDING_LOCK
   20434 **     (4) EXCLUSIVE_LOCK
   20435 **
   20436 ** Sometimes when requesting one lock state, additional lock states
   20437 ** are inserted in between.  The locking might fail on one of the later
   20438 ** transitions leaving the lock state different from what it started but
   20439 ** still short of its goal.  The following chart shows the allowed
   20440 ** transitions and the inserted intermediate states:
   20441 **
   20442 **    UNLOCKED -> SHARED
   20443 **    SHARED -> RESERVED
   20444 **    SHARED -> (PENDING) -> EXCLUSIVE
   20445 **    RESERVED -> (PENDING) -> EXCLUSIVE
   20446 **    PENDING -> EXCLUSIVE
   20447 **
   20448 ** This routine will only increase a lock.  The os2Unlock() routine
   20449 ** erases all locks at once and returns us immediately to locking level 0.
   20450 ** It is not possible to lower the locking level one step at a time.  You
   20451 ** must go straight to locking level 0.
   20452 */
   20453 static int os2Lock( sqlite3_file *id, int locktype ){
   20454   int rc = SQLITE_OK;       /* Return code from subroutines */
   20455   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
   20456   int newLocktype;       /* Set pFile->locktype to this value before exiting */
   20457   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
   20458   FILELOCK  LockArea,
   20459             UnlockArea;
   20460   os2File *pFile = (os2File*)id;
   20461   memset(&LockArea, 0, sizeof(LockArea));
   20462   memset(&UnlockArea, 0, sizeof(UnlockArea));
   20463   assert( pFile!=0 );
   20464   OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
   20465 
   20466   /* If there is already a lock of this type or more restrictive on the
   20467   ** os2File, do nothing. Don't use the end_lock: exit path, as
   20468   ** sqlite3_mutex_enter() hasn't been called yet.
   20469   */
   20470   if( pFile->locktype>=locktype ){
   20471     OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
   20472     return SQLITE_OK;
   20473   }
   20474 
   20475   /* Make sure the locking sequence is correct
   20476   */
   20477   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
   20478   assert( locktype!=PENDING_LOCK );
   20479   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
   20480 
   20481   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
   20482   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
   20483   ** the PENDING_LOCK byte is temporary.
   20484   */
   20485   newLocktype = pFile->locktype;
   20486   if( pFile->locktype==NO_LOCK
   20487       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
   20488   ){
   20489     LockArea.lOffset = PENDING_BYTE;
   20490     LockArea.lRange = 1L;
   20491     UnlockArea.lOffset = 0L;
   20492     UnlockArea.lRange = 0L;
   20493 
   20494     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
   20495     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
   20496     if( res == NO_ERROR ){
   20497       gotPendingLock = 1;
   20498       OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
   20499     }
   20500   }
   20501 
   20502   /* Acquire a shared lock
   20503   */
   20504   if( locktype==SHARED_LOCK && res == NO_ERROR ){
   20505     assert( pFile->locktype==NO_LOCK );
   20506     res = getReadLock(pFile);
   20507     if( res == NO_ERROR ){
   20508       newLocktype = SHARED_LOCK;
   20509     }
   20510     OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
   20511   }
   20512 
   20513   /* Acquire a RESERVED lock
   20514   */
   20515   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
   20516     assert( pFile->locktype==SHARED_LOCK );
   20517     LockArea.lOffset = RESERVED_BYTE;
   20518     LockArea.lRange = 1L;
   20519     UnlockArea.lOffset = 0L;
   20520     UnlockArea.lRange = 0L;
   20521     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   20522     if( res == NO_ERROR ){
   20523       newLocktype = RESERVED_LOCK;
   20524     }
   20525     OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
   20526   }
   20527 
   20528   /* Acquire a PENDING lock
   20529   */
   20530   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
   20531     newLocktype = PENDING_LOCK;
   20532     gotPendingLock = 0;
   20533     OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
   20534   }
   20535 
   20536   /* Acquire an EXCLUSIVE lock
   20537   */
   20538   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
   20539     assert( pFile->locktype>=SHARED_LOCK );
   20540     res = unlockReadLock(pFile);
   20541     OSTRACE2( "unreadlock = %d\n", res );
   20542     LockArea.lOffset = SHARED_FIRST;
   20543     LockArea.lRange = SHARED_SIZE;
   20544     UnlockArea.lOffset = 0L;
   20545     UnlockArea.lRange = 0L;
   20546     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   20547     if( res == NO_ERROR ){
   20548       newLocktype = EXCLUSIVE_LOCK;
   20549     }else{
   20550       OSTRACE2( "OS/2 error-code = %d\n", res );
   20551       getReadLock(pFile);
   20552     }
   20553     OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
   20554   }
   20555 
   20556   /* If we are holding a PENDING lock that ought to be released, then
   20557   ** release it now.
   20558   */
   20559   if( gotPendingLock && locktype==SHARED_LOCK ){
   20560     int r;
   20561     LockArea.lOffset = 0L;
   20562     LockArea.lRange = 0L;
   20563     UnlockArea.lOffset = PENDING_BYTE;
   20564     UnlockArea.lRange = 1L;
   20565     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   20566     OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
   20567   }
   20568 
   20569   /* Update the state of the lock has held in the file descriptor then
   20570   ** return the appropriate result code.
   20571   */
   20572   if( res == NO_ERROR ){
   20573     rc = SQLITE_OK;
   20574   }else{
   20575     OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
   20576               locktype, newLocktype );
   20577     rc = SQLITE_BUSY;
   20578   }
   20579   pFile->locktype = newLocktype;
   20580   OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
   20581   return rc;
   20582 }
   20583 
   20584 /*
   20585 ** This routine checks if there is a RESERVED lock held on the specified
   20586 ** file by this or any other process. If such a lock is held, return
   20587 ** non-zero, otherwise zero.
   20588 */
   20589 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
   20590   int r = 0;
   20591   os2File *pFile = (os2File*)id;
   20592   assert( pFile!=0 );
   20593   if( pFile->locktype>=RESERVED_LOCK ){
   20594     r = 1;
   20595     OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
   20596   }else{
   20597     FILELOCK  LockArea,
   20598               UnlockArea;
   20599     APIRET rc = NO_ERROR;
   20600     memset(&LockArea, 0, sizeof(LockArea));
   20601     memset(&UnlockArea, 0, sizeof(UnlockArea));
   20602     LockArea.lOffset = RESERVED_BYTE;
   20603     LockArea.lRange = 1L;
   20604     UnlockArea.lOffset = 0L;
   20605     UnlockArea.lRange = 0L;
   20606     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   20607     OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
   20608     if( rc == NO_ERROR ){
   20609       APIRET rcu = NO_ERROR; /* return code for unlocking */
   20610       LockArea.lOffset = 0L;
   20611       LockArea.lRange = 0L;
   20612       UnlockArea.lOffset = RESERVED_BYTE;
   20613       UnlockArea.lRange = 1L;
   20614       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   20615       OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
   20616     }
   20617     r = !(rc == NO_ERROR);
   20618     OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
   20619   }
   20620   *pOut = r;
   20621   return SQLITE_OK;
   20622 }
   20623 
   20624 /*
   20625 ** Lower the locking level on file descriptor id to locktype.  locktype
   20626 ** must be either NO_LOCK or SHARED_LOCK.
   20627 **
   20628 ** If the locking level of the file descriptor is already at or below
   20629 ** the requested locking level, this routine is a no-op.
   20630 **
   20631 ** It is not possible for this routine to fail if the second argument
   20632 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
   20633 ** might return SQLITE_IOERR;
   20634 */
   20635 static int os2Unlock( sqlite3_file *id, int locktype ){
   20636   int type;
   20637   os2File *pFile = (os2File*)id;
   20638   APIRET rc = SQLITE_OK;
   20639   APIRET res = NO_ERROR;
   20640   FILELOCK  LockArea,
   20641             UnlockArea;
   20642   memset(&LockArea, 0, sizeof(LockArea));
   20643   memset(&UnlockArea, 0, sizeof(UnlockArea));
   20644   assert( pFile!=0 );
   20645   assert( locktype<=SHARED_LOCK );
   20646   OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
   20647   type = pFile->locktype;
   20648   if( type>=EXCLUSIVE_LOCK ){
   20649     LockArea.lOffset = 0L;
   20650     LockArea.lRange = 0L;
   20651     UnlockArea.lOffset = SHARED_FIRST;
   20652     UnlockArea.lRange = SHARED_SIZE;
   20653     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   20654     OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
   20655     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
   20656       /* This should never happen.  We should always be able to
   20657       ** reacquire the read lock */
   20658       OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
   20659       rc = SQLITE_IOERR_UNLOCK;
   20660     }
   20661   }
   20662   if( type>=RESERVED_LOCK ){
   20663     LockArea.lOffset = 0L;
   20664     LockArea.lRange = 0L;
   20665     UnlockArea.lOffset = RESERVED_BYTE;
   20666     UnlockArea.lRange = 1L;
   20667     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   20668     OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
   20669   }
   20670   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
   20671     res = unlockReadLock(pFile);
   20672     OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
   20673   }
   20674   if( type>=PENDING_LOCK ){
   20675     LockArea.lOffset = 0L;
   20676     LockArea.lRange = 0L;
   20677     UnlockArea.lOffset = PENDING_BYTE;
   20678     UnlockArea.lRange = 1L;
   20679     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   20680     OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
   20681   }
   20682   pFile->locktype = locktype;
   20683   OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
   20684   return rc;
   20685 }
   20686 
   20687 /*
   20688 ** Control and query of the open file handle.
   20689 */
   20690 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
   20691   switch( op ){
   20692     case SQLITE_FCNTL_LOCKSTATE: {
   20693       *(int*)pArg = ((os2File*)id)->locktype;
   20694       OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
   20695       return SQLITE_OK;
   20696     }
   20697   }
   20698   return SQLITE_ERROR;
   20699 }
   20700 
   20701 /*
   20702 ** Return the sector size in bytes of the underlying block device for
   20703 ** the specified file. This is almost always 512 bytes, but may be
   20704 ** larger for some devices.
   20705 **
   20706 ** SQLite code assumes this function cannot fail. It also assumes that
   20707 ** if two files are created in the same file-system directory (i.e.
   20708 ** a database and its journal file) that the sector size will be the
   20709 ** same for both.
   20710 */
   20711 static int os2SectorSize(sqlite3_file *id){
   20712   return SQLITE_DEFAULT_SECTOR_SIZE;
   20713 }
   20714 
   20715 /*
   20716 ** Return a vector of device characteristics.
   20717 */
   20718 static int os2DeviceCharacteristics(sqlite3_file *id){
   20719   return 0;
   20720 }
   20721 
   20722 
   20723 /*
   20724 ** Character set conversion objects used by conversion routines.
   20725 */
   20726 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
   20727 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
   20728 
   20729 /*
   20730 ** Helper function to initialize the conversion objects from and to UTF-8.
   20731 */
   20732 static void initUconvObjects( void ){
   20733   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
   20734     ucUtf8 = NULL;
   20735   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
   20736     uclCp = NULL;
   20737 }
   20738 
   20739 /*
   20740 ** Helper function to free the conversion objects from and to UTF-8.
   20741 */
   20742 static void freeUconvObjects( void ){
   20743   if ( ucUtf8 )
   20744     UniFreeUconvObject( ucUtf8 );
   20745   if ( uclCp )
   20746     UniFreeUconvObject( uclCp );
   20747   ucUtf8 = NULL;
   20748   uclCp = NULL;
   20749 }
   20750 
   20751 /*
   20752 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
   20753 ** The two-step process: first convert the incoming UTF-8 string
   20754 ** into UCS-2 and then from UCS-2 to the current codepage.
   20755 ** The returned char pointer has to be freed.
   20756 */
   20757 static char *convertUtf8PathToCp( const char *in ){
   20758   UniChar tempPath[CCHMAXPATH];
   20759   char *out = (char *)calloc( CCHMAXPATH, 1 );
   20760 
   20761   if( !out )
   20762     return NULL;
   20763 
   20764   if( !ucUtf8 || !uclCp )
   20765     initUconvObjects();
   20766 
   20767   /* determine string for the conversion of UTF-8 which is CP1208 */
   20768   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
   20769     return out; /* if conversion fails, return the empty string */
   20770 
   20771   /* conversion for current codepage which can be used for paths */
   20772   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
   20773 
   20774   return out;
   20775 }
   20776 
   20777 /*
   20778 ** Helper function to convert filenames from local codepage to UTF-8.
   20779 ** The two-step process: first convert the incoming codepage-specific
   20780 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
   20781 ** The returned char pointer has to be freed.
   20782 **
   20783 ** This function is non-static to be able to use this in shell.c and
   20784 ** similar applications that take command line arguments.
   20785 */
   20786 char *convertCpPathToUtf8( const char *in ){
   20787   UniChar tempPath[CCHMAXPATH];
   20788   char *out = (char *)calloc( CCHMAXPATH, 1 );
   20789 
   20790   if( !out )
   20791     return NULL;
   20792 
   20793   if( !ucUtf8 || !uclCp )
   20794     initUconvObjects();
   20795 
   20796   /* conversion for current codepage which can be used for paths */
   20797   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
   20798     return out; /* if conversion fails, return the empty string */
   20799 
   20800   /* determine string for the conversion of UTF-8 which is CP1208 */
   20801   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
   20802 
   20803   return out;
   20804 }
   20805 
   20806 /*
   20807 ** This vector defines all the methods that can operate on an
   20808 ** sqlite3_file for os2.
   20809 */
   20810 static const sqlite3_io_methods os2IoMethod = {
   20811   1,                        /* iVersion */
   20812   os2Close,
   20813   os2Read,
   20814   os2Write,
   20815   os2Truncate,
   20816   os2Sync,
   20817   os2FileSize,
   20818   os2Lock,
   20819   os2Unlock,
   20820   os2CheckReservedLock,
   20821   os2FileControl,
   20822   os2SectorSize,
   20823   os2DeviceCharacteristics
   20824 };
   20825 
   20826 /***************************************************************************
   20827 ** Here ends the I/O methods that form the sqlite3_io_methods object.
   20828 **
   20829 ** The next block of code implements the VFS methods.
   20830 ****************************************************************************/
   20831 
   20832 /*
   20833 ** Create a temporary file name in zBuf.  zBuf must be big enough to
   20834 ** hold at pVfs->mxPathname characters.
   20835 */
   20836 static int getTempname(int nBuf, char *zBuf ){
   20837   static const unsigned char zChars[] =
   20838     "abcdefghijklmnopqrstuvwxyz"
   20839     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   20840     "0123456789";
   20841   int i, j;
   20842   char zTempPathBuf[3];
   20843   PSZ zTempPath = (PSZ)&zTempPathBuf;
   20844   if( sqlite3_temp_directory ){
   20845     zTempPath = sqlite3_temp_directory;
   20846   }else{
   20847     if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
   20848       if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
   20849         if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
   20850            ULONG ulDriveNum = 0, ulDriveMap = 0;
   20851            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
   20852            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
   20853         }
   20854       }
   20855     }
   20856   }
   20857   /* Strip off a trailing slashes or backslashes, otherwise we would get *
   20858    * multiple (back)slashes which causes DosOpen() to fail.              *
   20859    * Trailing spaces are not allowed, either.                            */
   20860   j = sqlite3Strlen30(zTempPath);
   20861   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
   20862                     || zTempPath[j-1] == ' ' ) ){
   20863     j--;
   20864   }
   20865   zTempPath[j] = '\0';
   20866   if( !sqlite3_temp_directory ){
   20867     char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
   20868     sqlite3_snprintf( nBuf-30, zBuf,
   20869                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
   20870     free( zTempPathUTF );
   20871   }else{
   20872     sqlite3_snprintf( nBuf-30, zBuf,
   20873                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
   20874   }
   20875   j = sqlite3Strlen30( zBuf );
   20876   sqlite3_randomness( 20, &zBuf[j] );
   20877   for( i = 0; i < 20; i++, j++ ){
   20878     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   20879   }
   20880   zBuf[j] = 0;
   20881   OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
   20882   return SQLITE_OK;
   20883 }
   20884 
   20885 
   20886 /*
   20887 ** Turn a relative pathname into a full pathname.  Write the full
   20888 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
   20889 ** bytes in size.
   20890 */
   20891 static int os2FullPathname(
   20892   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
   20893   const char *zRelative,      /* Possibly relative input path */
   20894   int nFull,                  /* Size of output buffer in bytes */
   20895   char *zFull                 /* Output buffer */
   20896 ){
   20897   char *zRelativeCp = convertUtf8PathToCp( zRelative );
   20898   char zFullCp[CCHMAXPATH] = "\0";
   20899   char *zFullUTF;
   20900   APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
   20901                                 CCHMAXPATH );
   20902   free( zRelativeCp );
   20903   zFullUTF = convertCpPathToUtf8( zFullCp );
   20904   sqlite3_snprintf( nFull, zFull, zFullUTF );
   20905   free( zFullUTF );
   20906   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
   20907 }
   20908 
   20909 
   20910 /*
   20911 ** Open a file.
   20912 */
   20913 static int os2Open(
   20914   sqlite3_vfs *pVfs,            /* Not used */
   20915   const char *zName,            /* Name of the file */
   20916   sqlite3_file *id,             /* Write the SQLite file handle here */
   20917   int flags,                    /* Open mode flags */
   20918   int *pOutFlags                /* Status return flags */
   20919 ){
   20920   HFILE h;
   20921   ULONG ulFileAttribute = FILE_NORMAL;
   20922   ULONG ulOpenFlags = 0;
   20923   ULONG ulOpenMode = 0;
   20924   os2File *pFile = (os2File*)id;
   20925   APIRET rc = NO_ERROR;
   20926   ULONG ulAction;
   20927   char *zNameCp;
   20928   char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
   20929 
   20930   /* If the second argument to this function is NULL, generate a
   20931   ** temporary file name to use
   20932   */
   20933   if( !zName ){
   20934     int rc = getTempname(CCHMAXPATH+1, zTmpname);
   20935     if( rc!=SQLITE_OK ){
   20936       return rc;
   20937     }
   20938     zName = zTmpname;
   20939   }
   20940 
   20941 
   20942   memset( pFile, 0, sizeof(*pFile) );
   20943 
   20944   OSTRACE2( "OPEN want %d\n", flags );
   20945 
   20946   if( flags & SQLITE_OPEN_READWRITE ){
   20947     ulOpenMode |= OPEN_ACCESS_READWRITE;
   20948     OSTRACE1( "OPEN read/write\n" );
   20949   }else{
   20950     ulOpenMode |= OPEN_ACCESS_READONLY;
   20951     OSTRACE1( "OPEN read only\n" );
   20952   }
   20953 
   20954   if( flags & SQLITE_OPEN_CREATE ){
   20955     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
   20956     OSTRACE1( "OPEN open new/create\n" );
   20957   }else{
   20958     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
   20959     OSTRACE1( "OPEN open existing\n" );
   20960   }
   20961 
   20962   if( flags & SQLITE_OPEN_MAIN_DB ){
   20963     ulOpenMode |= OPEN_SHARE_DENYNONE;
   20964     OSTRACE1( "OPEN share read/write\n" );
   20965   }else{
   20966     ulOpenMode |= OPEN_SHARE_DENYWRITE;
   20967     OSTRACE1( "OPEN share read only\n" );
   20968   }
   20969 
   20970   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
   20971     char pathUtf8[CCHMAXPATH];
   20972 #ifdef NDEBUG /* when debugging we want to make sure it is deleted */
   20973     ulFileAttribute = FILE_HIDDEN;
   20974 #endif
   20975     os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
   20976     pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
   20977     OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
   20978   }else{
   20979     pFile->pathToDel = NULL;
   20980     OSTRACE1( "OPEN normal file attribute\n" );
   20981   }
   20982 
   20983   /* always open in random access mode for possibly better speed */
   20984   ulOpenMode |= OPEN_FLAGS_RANDOM;
   20985   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
   20986   ulOpenMode |= OPEN_FLAGS_NOINHERIT;
   20987 
   20988   zNameCp = convertUtf8PathToCp( zName );
   20989   rc = DosOpen( (PSZ)zNameCp,
   20990                 &h,
   20991                 &ulAction,
   20992                 0L,
   20993                 ulFileAttribute,
   20994                 ulOpenFlags,
   20995                 ulOpenMode,
   20996                 (PEAOP2)NULL );
   20997   free( zNameCp );
   20998   if( rc != NO_ERROR ){
   20999     OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
   21000               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
   21001     if( pFile->pathToDel )
   21002       free( pFile->pathToDel );
   21003     pFile->pathToDel = NULL;
   21004     if( flags & SQLITE_OPEN_READWRITE ){
   21005       OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
   21006       return os2Open( pVfs, zName, id,
   21007                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
   21008                       pOutFlags );
   21009     }else{
   21010       return SQLITE_CANTOPEN;
   21011     }
   21012   }
   21013 
   21014   if( pOutFlags ){
   21015     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
   21016   }
   21017 
   21018   pFile->pMethod = &os2IoMethod;
   21019   pFile->h = h;
   21020   OpenCounter(+1);
   21021   OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
   21022   return SQLITE_OK;
   21023 }
   21024 
   21025 /*
   21026 ** Delete the named file.
   21027 */
   21028 static int os2Delete(
   21029   sqlite3_vfs *pVfs,                     /* Not used on os2 */
   21030   const char *zFilename,                 /* Name of file to delete */
   21031   int syncDir                            /* Not used on os2 */
   21032 ){
   21033   APIRET rc = NO_ERROR;
   21034   char *zFilenameCp = convertUtf8PathToCp( zFilename );
   21035   SimulateIOError( return SQLITE_IOERR_DELETE );
   21036   rc = DosDelete( (PSZ)zFilenameCp );
   21037   free( zFilenameCp );
   21038   OSTRACE2( "DELETE \"%s\"\n", zFilename );
   21039   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
   21040 }
   21041 
   21042 /*
   21043 ** Check the existance and status of a file.
   21044 */
   21045 static int os2Access(
   21046   sqlite3_vfs *pVfs,        /* Not used on os2 */
   21047   const char *zFilename,    /* Name of file to check */
   21048   int flags,                /* Type of test to make on this file */
   21049   int *pOut                 /* Write results here */
   21050 ){
   21051   FILESTATUS3 fsts3ConfigInfo;
   21052   APIRET rc = NO_ERROR;
   21053   char *zFilenameCp = convertUtf8PathToCp( zFilename );
   21054 
   21055   memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
   21056   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
   21057                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
   21058   free( zFilenameCp );
   21059   OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
   21060             fsts3ConfigInfo.attrFile, flags, rc );
   21061   switch( flags ){
   21062     case SQLITE_ACCESS_READ:
   21063     case SQLITE_ACCESS_EXISTS:
   21064       rc = (rc == NO_ERROR);
   21065       OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
   21066       break;
   21067     case SQLITE_ACCESS_READWRITE:
   21068       rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
   21069       OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
   21070       break;
   21071     default:
   21072       assert( !"Invalid flags argument" );
   21073   }
   21074   *pOut = rc;
   21075   return SQLITE_OK;
   21076 }
   21077 
   21078 
   21079 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   21080 /*
   21081 ** Interfaces for opening a shared library, finding entry points
   21082 ** within the shared library, and closing the shared library.
   21083 */
   21084 /*
   21085 ** Interfaces for opening a shared library, finding entry points
   21086 ** within the shared library, and closing the shared library.
   21087 */
   21088 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
   21089   UCHAR loadErr[256];
   21090   HMODULE hmod;
   21091   APIRET rc;
   21092   char *zFilenameCp = convertUtf8PathToCp(zFilename);
   21093   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
   21094   free(zFilenameCp);
   21095   return rc != NO_ERROR ? 0 : (void*)hmod;
   21096 }
   21097 /*
   21098 ** A no-op since the error code is returned on the DosLoadModule call.
   21099 ** os2Dlopen returns zero if DosLoadModule is not successful.
   21100 */
   21101 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
   21102 /* no-op */
   21103 }
   21104 static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
   21105   PFN pfn;
   21106   APIRET rc;
   21107   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
   21108   if( rc != NO_ERROR ){
   21109     /* if the symbol itself was not found, search again for the same
   21110      * symbol with an extra underscore, that might be needed depending
   21111      * on the calling convention */
   21112     char _zSymbol[256] = "_";
   21113     strncat(_zSymbol, zSymbol, 255);
   21114     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
   21115   }
   21116   return rc != NO_ERROR ? 0 : (void*)pfn;
   21117 }
   21118 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
   21119   DosFreeModule((HMODULE)pHandle);
   21120 }
   21121 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   21122   #define os2DlOpen 0
   21123   #define os2DlError 0
   21124   #define os2DlSym 0
   21125   #define os2DlClose 0
   21126 #endif
   21127 
   21128 
   21129 /*
   21130 ** Write up to nBuf bytes of randomness into zBuf.
   21131 */
   21132 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
   21133   int n = 0;
   21134 #if defined(SQLITE_TEST)
   21135   n = nBuf;
   21136   memset(zBuf, 0, nBuf);
   21137 #else
   21138   int sizeofULong = sizeof(ULONG);
   21139   if( (int)sizeof(DATETIME) <= nBuf - n ){
   21140     DATETIME x;
   21141     DosGetDateTime(&x);
   21142     memcpy(&zBuf[n], &x, sizeof(x));
   21143     n += sizeof(x);
   21144   }
   21145 
   21146   if( sizeofULong <= nBuf - n ){
   21147     PPIB ppib;
   21148     DosGetInfoBlocks(NULL, &ppib);
   21149     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
   21150     n += sizeofULong;
   21151   }
   21152 
   21153   if( sizeofULong <= nBuf - n ){
   21154     PTIB ptib;
   21155     DosGetInfoBlocks(&ptib, NULL);
   21156     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
   21157     n += sizeofULong;
   21158   }
   21159 
   21160   /* if we still haven't filled the buffer yet the following will */
   21161   /* grab everything once instead of making several calls for a single item */
   21162   if( sizeofULong <= nBuf - n ){
   21163     ULONG ulSysInfo[QSV_MAX];
   21164     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
   21165 
   21166     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
   21167     n += sizeofULong;
   21168 
   21169     if( sizeofULong <= nBuf - n ){
   21170       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
   21171       n += sizeofULong;
   21172     }
   21173     if( sizeofULong <= nBuf - n ){
   21174       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
   21175       n += sizeofULong;
   21176     }
   21177     if( sizeofULong <= nBuf - n ){
   21178       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
   21179       n += sizeofULong;
   21180     }
   21181     if( sizeofULong <= nBuf - n ){
   21182       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
   21183       n += sizeofULong;
   21184     }
   21185   }
   21186 #endif
   21187 
   21188   return n;
   21189 }
   21190 
   21191 /*
   21192 ** Sleep for a little while.  Return the amount of time slept.
   21193 ** The argument is the number of microseconds we want to sleep.
   21194 ** The return value is the number of microseconds of sleep actually
   21195 ** requested from the underlying operating system, a number which
   21196 ** might be greater than or equal to the argument, but not less
   21197 ** than the argument.
   21198 */
   21199 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
   21200   DosSleep( (microsec/1000) );
   21201   return microsec;
   21202 }
   21203 
   21204 /*
   21205 ** The following variable, if set to a non-zero value, becomes the result
   21206 ** returned from sqlite3OsCurrentTime().  This is used for testing.
   21207 */
   21208 #ifdef SQLITE_TEST
   21209 SQLITE_API int sqlite3_current_time = 0;
   21210 #endif
   21211 
   21212 /*
   21213 ** Find the current time (in Universal Coordinated Time).  Write the
   21214 ** current time and date as a Julian Day number into *prNow and
   21215 ** return 0.  Return 1 if the time and date cannot be found.
   21216 */
   21217 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
   21218   double now;
   21219   SHORT minute; /* needs to be able to cope with negative timezone offset */
   21220   USHORT second, hour,
   21221          day, month, year;
   21222   DATETIME dt;
   21223   DosGetDateTime( &dt );
   21224   second = (USHORT)dt.seconds;
   21225   minute = (SHORT)dt.minutes + dt.timezone;
   21226   hour = (USHORT)dt.hours;
   21227   day = (USHORT)dt.day;
   21228   month = (USHORT)dt.month;
   21229   year = (USHORT)dt.year;
   21230 
   21231   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
   21232      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
   21233   /* Calculate the Julian days */
   21234   now = day - 32076 +
   21235     1461*(year + 4800 + (month - 14)/12)/4 +
   21236     367*(month - 2 - (month - 14)/12*12)/12 -
   21237     3*((year + 4900 + (month - 14)/12)/100)/4;
   21238 
   21239   /* Add the fractional hours, mins and seconds */
   21240   now += (hour + 12.0)/24.0;
   21241   now += minute/1440.0;
   21242   now += second/86400.0;
   21243   *prNow = now;
   21244 #ifdef SQLITE_TEST
   21245   if( sqlite3_current_time ){
   21246     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
   21247   }
   21248 #endif
   21249   return 0;
   21250 }
   21251 
   21252 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   21253   return 0;
   21254 }
   21255 
   21256 /*
   21257 ** Initialize and deinitialize the operating system interface.
   21258 */
   21259 SQLITE_API int sqlite3_os_init(void){
   21260   static sqlite3_vfs os2Vfs = {
   21261     1,                 /* iVersion */
   21262     sizeof(os2File),   /* szOsFile */
   21263     CCHMAXPATH,        /* mxPathname */
   21264     0,                 /* pNext */
   21265     "os2",             /* zName */
   21266     0,                 /* pAppData */
   21267 
   21268     os2Open,           /* xOpen */
   21269     os2Delete,         /* xDelete */
   21270     os2Access,         /* xAccess */
   21271     os2FullPathname,   /* xFullPathname */
   21272     os2DlOpen,         /* xDlOpen */
   21273     os2DlError,        /* xDlError */
   21274     os2DlSym,          /* xDlSym */
   21275     os2DlClose,        /* xDlClose */
   21276     os2Randomness,     /* xRandomness */
   21277     os2Sleep,          /* xSleep */
   21278     os2CurrentTime,    /* xCurrentTime */
   21279     os2GetLastError    /* xGetLastError */
   21280   };
   21281   sqlite3_vfs_register(&os2Vfs, 1);
   21282   initUconvObjects();
   21283   return SQLITE_OK;
   21284 }
   21285 SQLITE_API int sqlite3_os_end(void){
   21286   freeUconvObjects();
   21287   return SQLITE_OK;
   21288 }
   21289 
   21290 #endif /* SQLITE_OS_OS2 */
   21291 
   21292 /************** End of os_os2.c **********************************************/
   21293 /************** Begin file os_unix.c *****************************************/
   21294 /*
   21295 ** 2004 May 22
   21296 **
   21297 ** The author disclaims copyright to this source code.  In place of
   21298 ** a legal notice, here is a blessing:
   21299 **
   21300 **    May you do good and not evil.
   21301 **    May you find forgiveness for yourself and forgive others.
   21302 **    May you share freely, never taking more than you give.
   21303 **
   21304 ******************************************************************************
   21305 **
   21306 ** This file contains the VFS implementation for unix-like operating systems
   21307 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
   21308 **
   21309 ** There are actually several different VFS implementations in this file.
   21310 ** The differences are in the way that file locking is done.  The default
   21311 ** implementation uses Posix Advisory Locks.  Alternative implementations
   21312 ** use flock(), dot-files, various proprietary locking schemas, or simply
   21313 ** skip locking all together.
   21314 **
   21315 ** This source file is organized into divisions where the logic for various
   21316 ** subfunctions is contained within the appropriate division.  PLEASE
   21317 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
   21318 ** in the correct division and should be clearly labeled.
   21319 **
   21320 ** The layout of divisions is as follows:
   21321 **
   21322 **   *  General-purpose declarations and utility functions.
   21323 **   *  Unique file ID logic used by VxWorks.
   21324 **   *  Various locking primitive implementations (all except proxy locking):
   21325 **      + for Posix Advisory Locks
   21326 **      + for no-op locks
   21327 **      + for dot-file locks
   21328 **      + for flock() locking
   21329 **      + for named semaphore locks (VxWorks only)
   21330 **      + for AFP filesystem locks (MacOSX only)
   21331 **   *  sqlite3_file methods not associated with locking.
   21332 **   *  Definitions of sqlite3_io_methods objects for all locking
   21333 **      methods plus "finder" functions for each locking method.
   21334 **   *  sqlite3_vfs method implementations.
   21335 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
   21336 **   *  Definitions of sqlite3_vfs objects for all locking methods
   21337 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
   21338 */
   21339 #if SQLITE_OS_UNIX              /* This file is used on unix only */
   21340 
   21341 /*
   21342 ** There are various methods for file locking used for concurrency
   21343 ** control:
   21344 **
   21345 **   1. POSIX locking (the default),
   21346 **   2. No locking,
   21347 **   3. Dot-file locking,
   21348 **   4. flock() locking,
   21349 **   5. AFP locking (OSX only),
   21350 **   6. Named POSIX semaphores (VXWorks only),
   21351 **   7. proxy locking. (OSX only)
   21352 **
   21353 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
   21354 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
   21355 ** selection of the appropriate locking style based on the filesystem
   21356 ** where the database is located.
   21357 */
   21358 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
   21359 #  if defined(__APPLE__)
   21360 #    define SQLITE_ENABLE_LOCKING_STYLE 1
   21361 #  else
   21362 #    define SQLITE_ENABLE_LOCKING_STYLE 0
   21363 #  endif
   21364 #endif
   21365 
   21366 /*
   21367 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
   21368 ** vxworks, or 0 otherwise.
   21369 */
   21370 #ifndef OS_VXWORKS
   21371 #  if defined(__RTP__) || defined(_WRS_KERNEL)
   21372 #    define OS_VXWORKS 1
   21373 #  else
   21374 #    define OS_VXWORKS 0
   21375 #  endif
   21376 #endif
   21377 
   21378 /*
   21379 ** These #defines should enable >2GB file support on Posix if the
   21380 ** underlying operating system supports it.  If the OS lacks
   21381 ** large file support, these should be no-ops.
   21382 **
   21383 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
   21384 ** on the compiler command line.  This is necessary if you are compiling
   21385 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
   21386 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
   21387 ** without this option, LFS is enable.  But LFS does not exist in the kernel
   21388 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
   21389 ** portability you should omit LFS.
   21390 **
   21391 ** The previous paragraph was written in 2005.  (This paragraph is written
   21392 ** on 2008-11-28.) These days, all Linux kernels support large files, so
   21393 ** you should probably leave LFS enabled.  But some embedded platforms might
   21394 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
   21395 */
   21396 #ifndef SQLITE_DISABLE_LFS
   21397 # define _LARGE_FILE       1
   21398 # ifndef _FILE_OFFSET_BITS
   21399 #   define _FILE_OFFSET_BITS 64
   21400 # endif
   21401 # define _LARGEFILE_SOURCE 1
   21402 #endif
   21403 
   21404 /*
   21405 ** standard include files.
   21406 */
   21407 #include <sys/types.h>
   21408 #include <sys/stat.h>
   21409 #include <fcntl.h>
   21410 #include <unistd.h>
   21411 #include <sys/time.h>
   21412 #include <errno.h>
   21413 
   21414 #if SQLITE_ENABLE_LOCKING_STYLE
   21415 # include <sys/ioctl.h>
   21416 # if OS_VXWORKS
   21417 #  include <semaphore.h>
   21418 #  include <limits.h>
   21419 # else
   21420 #  include <sys/file.h>
   21421 #  include <sys/param.h>
   21422 #  include <sys/mount.h>
   21423 # endif
   21424 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
   21425 
   21426 /*
   21427 ** If we are to be thread-safe, include the pthreads header and define
   21428 ** the SQLITE_UNIX_THREADS macro.
   21429 */
   21430 #if SQLITE_THREADSAFE
   21431 # define SQLITE_UNIX_THREADS 1
   21432 #endif
   21433 
   21434 /*
   21435 ** Default permissions when creating a new file
   21436 */
   21437 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
   21438 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
   21439 #endif
   21440 
   21441 /*
   21442  ** Default permissions when creating auto proxy dir
   21443  */
   21444 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   21445 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
   21446 #endif
   21447 
   21448 /*
   21449 ** Maximum supported path-length.
   21450 */
   21451 #define MAX_PATHNAME 512
   21452 
   21453 /*
   21454 ** Only set the lastErrno if the error code is a real error and not
   21455 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
   21456 */
   21457 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
   21458 
   21459 
   21460 /*
   21461 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
   21462 ** cannot be closed immediately. In these cases, instances of the following
   21463 ** structure are used to store the file descriptor while waiting for an
   21464 ** opportunity to either close or reuse it.
   21465 */
   21466 typedef struct UnixUnusedFd UnixUnusedFd;
   21467 struct UnixUnusedFd {
   21468   int fd;                   /* File descriptor to close */
   21469   int flags;                /* Flags this file descriptor was opened with */
   21470   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
   21471 };
   21472 
   21473 /*
   21474 ** The unixFile structure is subclass of sqlite3_file specific to the unix
   21475 ** VFS implementations.
   21476 */
   21477 typedef struct unixFile unixFile;
   21478 struct unixFile {
   21479   sqlite3_io_methods const *pMethod;  /* Always the first entry */
   21480   struct unixOpenCnt *pOpen;       /* Info about all open fd's on this inode */
   21481   struct unixLockInfo *pLock;      /* Info about locks on this inode */
   21482   int h;                           /* The file descriptor */
   21483   int dirfd;                       /* File descriptor for the directory */
   21484   unsigned char locktype;          /* The type of lock held on this fd */
   21485   int lastErrno;                   /* The unix errno from the last I/O error */
   21486   void *lockingContext;            /* Locking style specific state */
   21487   UnixUnusedFd *pUnused;           /* Pre-allocated UnixUnusedFd */
   21488   int fileFlags;                   /* Miscellanous flags */
   21489 #if SQLITE_ENABLE_LOCKING_STYLE
   21490   int openFlags;                   /* The flags specified at open() */
   21491 #endif
   21492 #if SQLITE_THREADSAFE && defined(__linux__)
   21493   pthread_t tid;                   /* The thread that "owns" this unixFile */
   21494 #endif
   21495 #if OS_VXWORKS
   21496   int isDelete;                    /* Delete on close if true */
   21497   struct vxworksFileId *pId;       /* Unique file ID */
   21498 #endif
   21499 #ifndef NDEBUG
   21500   /* The next group of variables are used to track whether or not the
   21501   ** transaction counter in bytes 24-27 of database files are updated
   21502   ** whenever any part of the database changes.  An assertion fault will
   21503   ** occur if a file is updated without also updating the transaction
   21504   ** counter.  This test is made to avoid new problems similar to the
   21505   ** one described by ticket #3584.
   21506   */
   21507   unsigned char transCntrChng;   /* True if the transaction counter changed */
   21508   unsigned char dbUpdate;        /* True if any part of database file changed */
   21509   unsigned char inNormalWrite;   /* True if in a normal write operation */
   21510 #endif
   21511 #ifdef SQLITE_TEST
   21512   /* In test mode, increase the size of this structure a bit so that
   21513   ** it is larger than the struct CrashFile defined in test6.c.
   21514   */
   21515   char aPadding[32];
   21516 #endif
   21517 };
   21518 
   21519 /*
   21520 ** The following macros define bits in unixFile.fileFlags
   21521 */
   21522 #define SQLITE_WHOLE_FILE_LOCKING  0x0001   /* Use whole-file locking */
   21523 
   21524 /*
   21525 ** Include code that is common to all os_*.c files
   21526 */
   21527 /************** Include os_common.h in the middle of os_unix.c ***************/
   21528 /************** Begin file os_common.h ***************************************/
   21529 /*
   21530 ** 2004 May 22
   21531 **
   21532 ** The author disclaims copyright to this source code.  In place of
   21533 ** a legal notice, here is a blessing:
   21534 **
   21535 **    May you do good and not evil.
   21536 **    May you find forgiveness for yourself and forgive others.
   21537 **    May you share freely, never taking more than you give.
   21538 **
   21539 ******************************************************************************
   21540 **
   21541 ** This file contains macros and a little bit of code that is common to
   21542 ** all of the platform-specific files (os_*.c) and is #included into those
   21543 ** files.
   21544 **
   21545 ** This file should be #included by the os_*.c files only.  It is not a
   21546 ** general purpose header file.
   21547 */
   21548 #ifndef _OS_COMMON_H_
   21549 #define _OS_COMMON_H_
   21550 
   21551 /*
   21552 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   21553 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   21554 ** switch.  The following code should catch this problem at compile-time.
   21555 */
   21556 #ifdef MEMORY_DEBUG
   21557 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   21558 #endif
   21559 
   21560 #ifdef SQLITE_DEBUG
   21561 SQLITE_PRIVATE int sqlite3OSTrace = 0;
   21562 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
   21563 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
   21564 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
   21565 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
   21566 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
   21567 #define OSTRACE6(X,Y,Z,A,B,C) \
   21568     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
   21569 #define OSTRACE7(X,Y,Z,A,B,C,D) \
   21570     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
   21571 #else
   21572 #define OSTRACE1(X)
   21573 #define OSTRACE2(X,Y)
   21574 #define OSTRACE3(X,Y,Z)
   21575 #define OSTRACE4(X,Y,Z,A)
   21576 #define OSTRACE5(X,Y,Z,A,B)
   21577 #define OSTRACE6(X,Y,Z,A,B,C)
   21578 #define OSTRACE7(X,Y,Z,A,B,C,D)
   21579 #endif
   21580 
   21581 /*
   21582 ** Macros for performance tracing.  Normally turned off.  Only works
   21583 ** on i486 hardware.
   21584 */
   21585 #ifdef SQLITE_PERFORMANCE_TRACE
   21586 
   21587 /*
   21588 ** hwtime.h contains inline assembler code for implementing
   21589 ** high-performance timing routines.
   21590 */
   21591 /************** Include hwtime.h in the middle of os_common.h ****************/
   21592 /************** Begin file hwtime.h ******************************************/
   21593 /*
   21594 ** 2008 May 27
   21595 **
   21596 ** The author disclaims copyright to this source code.  In place of
   21597 ** a legal notice, here is a blessing:
   21598 **
   21599 **    May you do good and not evil.
   21600 **    May you find forgiveness for yourself and forgive others.
   21601 **    May you share freely, never taking more than you give.
   21602 **
   21603 ******************************************************************************
   21604 **
   21605 ** This file contains inline asm code for retrieving "high-performance"
   21606 ** counters for x86 class CPUs.
   21607 */
   21608 #ifndef _HWTIME_H_
   21609 #define _HWTIME_H_
   21610 
   21611 /*
   21612 ** The following routine only works on pentium-class (or newer) processors.
   21613 ** It uses the RDTSC opcode to read the cycle count value out of the
   21614 ** processor and returns that value.  This can be used for high-res
   21615 ** profiling.
   21616 */
   21617 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   21618       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   21619 
   21620   #if defined(__GNUC__)
   21621 
   21622   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   21623      unsigned int lo, hi;
   21624      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   21625      return (sqlite_uint64)hi << 32 | lo;
   21626   }
   21627 
   21628   #elif defined(_MSC_VER)
   21629 
   21630   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   21631      __asm {
   21632         rdtsc
   21633         ret       ; return value at EDX:EAX
   21634      }
   21635   }
   21636 
   21637   #endif
   21638 
   21639 #elif (defined(__GNUC__) && defined(__x86_64__))
   21640 
   21641   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   21642       unsigned long val;
   21643       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   21644       return val;
   21645   }
   21646 
   21647 #elif (defined(__GNUC__) && defined(__ppc__))
   21648 
   21649   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   21650       unsigned long long retval;
   21651       unsigned long junk;
   21652       __asm__ __volatile__ ("\n\
   21653           1:      mftbu   %1\n\
   21654                   mftb    %L0\n\
   21655                   mftbu   %0\n\
   21656                   cmpw    %0,%1\n\
   21657                   bne     1b"
   21658                   : "=r" (retval), "=r" (junk));
   21659       return retval;
   21660   }
   21661 
   21662 #else
   21663 
   21664   #error Need implementation of sqlite3Hwtime() for your platform.
   21665 
   21666   /*
   21667   ** To compile without implementing sqlite3Hwtime() for your platform,
   21668   ** you can remove the above #error and use the following
   21669   ** stub function.  You will lose timing support for many
   21670   ** of the debugging and testing utilities, but it should at
   21671   ** least compile and run.
   21672   */
   21673 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   21674 
   21675 #endif
   21676 
   21677 #endif /* !defined(_HWTIME_H_) */
   21678 
   21679 /************** End of hwtime.h **********************************************/
   21680 /************** Continuing where we left off in os_common.h ******************/
   21681 
   21682 static sqlite_uint64 g_start;
   21683 static sqlite_uint64 g_elapsed;
   21684 #define TIMER_START       g_start=sqlite3Hwtime()
   21685 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   21686 #define TIMER_ELAPSED     g_elapsed
   21687 #else
   21688 #define TIMER_START
   21689 #define TIMER_END
   21690 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   21691 #endif
   21692 
   21693 /*
   21694 ** If we compile with the SQLITE_TEST macro set, then the following block
   21695 ** of code will give us the ability to simulate a disk I/O error.  This
   21696 ** is used for testing the I/O recovery logic.
   21697 */
   21698 #ifdef SQLITE_TEST
   21699 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   21700 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   21701 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   21702 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   21703 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   21704 SQLITE_API int sqlite3_diskfull_pending = 0;
   21705 SQLITE_API int sqlite3_diskfull = 0;
   21706 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   21707 #define SimulateIOError(CODE)  \
   21708   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   21709        || sqlite3_io_error_pending-- == 1 )  \
   21710               { local_ioerr(); CODE; }
   21711 static void local_ioerr(){
   21712   IOTRACE(("IOERR\n"));
   21713   sqlite3_io_error_hit++;
   21714   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   21715 }
   21716 #define SimulateDiskfullError(CODE) \
   21717    if( sqlite3_diskfull_pending ){ \
   21718      if( sqlite3_diskfull_pending == 1 ){ \
   21719        local_ioerr(); \
   21720        sqlite3_diskfull = 1; \
   21721        sqlite3_io_error_hit = 1; \
   21722        CODE; \
   21723      }else{ \
   21724        sqlite3_diskfull_pending--; \
   21725      } \
   21726    }
   21727 #else
   21728 #define SimulateIOErrorBenign(X)
   21729 #define SimulateIOError(A)
   21730 #define SimulateDiskfullError(A)
   21731 #endif
   21732 
   21733 /*
   21734 ** When testing, keep a count of the number of open files.
   21735 */
   21736 #ifdef SQLITE_TEST
   21737 SQLITE_API int sqlite3_open_file_count = 0;
   21738 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   21739 #else
   21740 #define OpenCounter(X)
   21741 #endif
   21742 
   21743 #endif /* !defined(_OS_COMMON_H_) */
   21744 
   21745 /************** End of os_common.h *******************************************/
   21746 /************** Continuing where we left off in os_unix.c ********************/
   21747 
   21748 /*
   21749 ** Define various macros that are missing from some systems.
   21750 */
   21751 #ifndef O_LARGEFILE
   21752 # define O_LARGEFILE 0
   21753 #endif
   21754 #ifdef SQLITE_DISABLE_LFS
   21755 # undef O_LARGEFILE
   21756 # define O_LARGEFILE 0
   21757 #endif
   21758 #ifndef O_NOFOLLOW
   21759 # define O_NOFOLLOW 0
   21760 #endif
   21761 #ifndef O_BINARY
   21762 # define O_BINARY 0
   21763 #endif
   21764 
   21765 /*
   21766 ** The DJGPP compiler environment looks mostly like Unix, but it
   21767 ** lacks the fcntl() system call.  So redefine fcntl() to be something
   21768 ** that always succeeds.  This means that locking does not occur under
   21769 ** DJGPP.  But it is DOS - what did you expect?
   21770 */
   21771 #ifdef __DJGPP__
   21772 # define fcntl(A,B,C) 0
   21773 #endif
   21774 
   21775 /*
   21776 ** The threadid macro resolves to the thread-id or to 0.  Used for
   21777 ** testing and debugging only.
   21778 */
   21779 #if SQLITE_THREADSAFE
   21780 #define threadid pthread_self()
   21781 #else
   21782 #define threadid 0
   21783 #endif
   21784 
   21785 
   21786 /*
   21787 ** Helper functions to obtain and relinquish the global mutex. The
   21788 ** global mutex is used to protect the unixOpenCnt, unixLockInfo and
   21789 ** vxworksFileId objects used by this file, all of which may be
   21790 ** shared by multiple threads.
   21791 **
   21792 ** Function unixMutexHeld() is used to assert() that the global mutex
   21793 ** is held when required. This function is only used as part of assert()
   21794 ** statements. e.g.
   21795 **
   21796 **   unixEnterMutex()
   21797 **     assert( unixMutexHeld() );
   21798 **   unixEnterLeave()
   21799 */
   21800 static void unixEnterMutex(void){
   21801   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   21802 }
   21803 static void unixLeaveMutex(void){
   21804   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   21805 }
   21806 #ifdef SQLITE_DEBUG
   21807 static int unixMutexHeld(void) {
   21808   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   21809 }
   21810 #endif
   21811 
   21812 
   21813 #ifdef SQLITE_DEBUG
   21814 /*
   21815 ** Helper function for printing out trace information from debugging
   21816 ** binaries. This returns the string represetation of the supplied
   21817 ** integer lock-type.
   21818 */
   21819 static const char *locktypeName(int locktype){
   21820   switch( locktype ){
   21821     case NO_LOCK: return "NONE";
   21822     case SHARED_LOCK: return "SHARED";
   21823     case RESERVED_LOCK: return "RESERVED";
   21824     case PENDING_LOCK: return "PENDING";
   21825     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
   21826   }
   21827   return "ERROR";
   21828 }
   21829 #endif
   21830 
   21831 #ifdef SQLITE_LOCK_TRACE
   21832 /*
   21833 ** Print out information about all locking operations.
   21834 **
   21835 ** This routine is used for troubleshooting locks on multithreaded
   21836 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
   21837 ** command-line option on the compiler.  This code is normally
   21838 ** turned off.
   21839 */
   21840 static int lockTrace(int fd, int op, struct flock *p){
   21841   char *zOpName, *zType;
   21842   int s;
   21843   int savedErrno;
   21844   if( op==F_GETLK ){
   21845     zOpName = "GETLK";
   21846   }else if( op==F_SETLK ){
   21847     zOpName = "SETLK";
   21848   }else{
   21849     s = fcntl(fd, op, p);
   21850     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
   21851     return s;
   21852   }
   21853   if( p->l_type==F_RDLCK ){
   21854     zType = "RDLCK";
   21855   }else if( p->l_type==F_WRLCK ){
   21856     zType = "WRLCK";
   21857   }else if( p->l_type==F_UNLCK ){
   21858     zType = "UNLCK";
   21859   }else{
   21860     assert( 0 );
   21861   }
   21862   assert( p->l_whence==SEEK_SET );
   21863   s = fcntl(fd, op, p);
   21864   savedErrno = errno;
   21865   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
   21866      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
   21867      (int)p->l_pid, s);
   21868   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
   21869     struct flock l2;
   21870     l2 = *p;
   21871     fcntl(fd, F_GETLK, &l2);
   21872     if( l2.l_type==F_RDLCK ){
   21873       zType = "RDLCK";
   21874     }else if( l2.l_type==F_WRLCK ){
   21875       zType = "WRLCK";
   21876     }else if( l2.l_type==F_UNLCK ){
   21877       zType = "UNLCK";
   21878     }else{
   21879       assert( 0 );
   21880     }
   21881     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
   21882        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
   21883   }
   21884   errno = savedErrno;
   21885   return s;
   21886 }
   21887 #define fcntl lockTrace
   21888 #endif /* SQLITE_LOCK_TRACE */
   21889 
   21890 
   21891 
   21892 /*
   21893 ** This routine translates a standard POSIX errno code into something
   21894 ** useful to the clients of the sqlite3 functions.  Specifically, it is
   21895 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
   21896 ** and a variety of "please close the file descriptor NOW" errors into
   21897 ** SQLITE_IOERR
   21898 **
   21899 ** Errors during initialization of locks, or file system support for locks,
   21900 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
   21901 */
   21902 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
   21903   switch (posixError) {
   21904   case 0:
   21905     return SQLITE_OK;
   21906 
   21907   case EAGAIN:
   21908   case ETIMEDOUT:
   21909   case EBUSY:
   21910   case EINTR:
   21911   case ENOLCK:
   21912     /* random NFS retry error, unless during file system support
   21913      * introspection, in which it actually means what it says */
   21914     return SQLITE_BUSY;
   21915 
   21916   case EACCES:
   21917     /* EACCES is like EAGAIN during locking operations, but not any other time*/
   21918     if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
   21919 	(sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
   21920 	(sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
   21921 	(sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
   21922       return SQLITE_BUSY;
   21923     }
   21924     /* else fall through */
   21925   case EPERM:
   21926     return SQLITE_PERM;
   21927 
   21928   case EDEADLK:
   21929     return SQLITE_IOERR_BLOCKED;
   21930 
   21931 #if EOPNOTSUPP!=ENOTSUP
   21932   case EOPNOTSUPP:
   21933     /* something went terribly awry, unless during file system support
   21934      * introspection, in which it actually means what it says */
   21935 #endif
   21936 #ifdef ENOTSUP
   21937   case ENOTSUP:
   21938     /* invalid fd, unless during file system support introspection, in which
   21939      * it actually means what it says */
   21940 #endif
   21941   case EIO:
   21942   case EBADF:
   21943   case EINVAL:
   21944   case ENOTCONN:
   21945   case ENODEV:
   21946   case ENXIO:
   21947   case ENOENT:
   21948   case ESTALE:
   21949   case ENOSYS:
   21950     /* these should force the client to close the file and reconnect */
   21951 
   21952   default:
   21953     return sqliteIOErr;
   21954   }
   21955 }
   21956 
   21957 
   21958 
   21959 /******************************************************************************
   21960 ****************** Begin Unique File ID Utility Used By VxWorks ***************
   21961 **
   21962 ** On most versions of unix, we can get a unique ID for a file by concatenating
   21963 ** the device number and the inode number.  But this does not work on VxWorks.
   21964 ** On VxWorks, a unique file id must be based on the canonical filename.
   21965 **
   21966 ** A pointer to an instance of the following structure can be used as a
   21967 ** unique file ID in VxWorks.  Each instance of this structure contains
   21968 ** a copy of the canonical filename.  There is also a reference count.
   21969 ** The structure is reclaimed when the number of pointers to it drops to
   21970 ** zero.
   21971 **
   21972 ** There are never very many files open at one time and lookups are not
   21973 ** a performance-critical path, so it is sufficient to put these
   21974 ** structures on a linked list.
   21975 */
   21976 struct vxworksFileId {
   21977   struct vxworksFileId *pNext;  /* Next in a list of them all */
   21978   int nRef;                     /* Number of references to this one */
   21979   int nName;                    /* Length of the zCanonicalName[] string */
   21980   char *zCanonicalName;         /* Canonical filename */
   21981 };
   21982 
   21983 #if OS_VXWORKS
   21984 /*
   21985 ** All unique filenames are held on a linked list headed by this
   21986 ** variable:
   21987 */
   21988 static struct vxworksFileId *vxworksFileList = 0;
   21989 
   21990 /*
   21991 ** Simplify a filename into its canonical form
   21992 ** by making the following changes:
   21993 **
   21994 **  * removing any trailing and duplicate /
   21995 **  * convert /./ into just /
   21996 **  * convert /A/../ where A is any simple name into just /
   21997 **
   21998 ** Changes are made in-place.  Return the new name length.
   21999 **
   22000 ** The original filename is in z[0..n-1].  Return the number of
   22001 ** characters in the simplified name.
   22002 */
   22003 static int vxworksSimplifyName(char *z, int n){
   22004   int i, j;
   22005   while( n>1 && z[n-1]=='/' ){ n--; }
   22006   for(i=j=0; i<n; i++){
   22007     if( z[i]=='/' ){
   22008       if( z[i+1]=='/' ) continue;
   22009       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
   22010         i += 1;
   22011         continue;
   22012       }
   22013       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
   22014         while( j>0 && z[j-1]!='/' ){ j--; }
   22015         if( j>0 ){ j--; }
   22016         i += 2;
   22017         continue;
   22018       }
   22019     }
   22020     z[j++] = z[i];
   22021   }
   22022   z[j] = 0;
   22023   return j;
   22024 }
   22025 
   22026 /*
   22027 ** Find a unique file ID for the given absolute pathname.  Return
   22028 ** a pointer to the vxworksFileId object.  This pointer is the unique
   22029 ** file ID.
   22030 **
   22031 ** The nRef field of the vxworksFileId object is incremented before
   22032 ** the object is returned.  A new vxworksFileId object is created
   22033 ** and added to the global list if necessary.
   22034 **
   22035 ** If a memory allocation error occurs, return NULL.
   22036 */
   22037 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
   22038   struct vxworksFileId *pNew;         /* search key and new file ID */
   22039   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
   22040   int n;                              /* Length of zAbsoluteName string */
   22041 
   22042   assert( zAbsoluteName[0]=='/' );
   22043   n = (int)strlen(zAbsoluteName);
   22044   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
   22045   if( pNew==0 ) return 0;
   22046   pNew->zCanonicalName = (char*)&pNew[1];
   22047   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
   22048   n = vxworksSimplifyName(pNew->zCanonicalName, n);
   22049 
   22050   /* Search for an existing entry that matching the canonical name.
   22051   ** If found, increment the reference count and return a pointer to
   22052   ** the existing file ID.
   22053   */
   22054   unixEnterMutex();
   22055   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
   22056     if( pCandidate->nName==n
   22057      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
   22058     ){
   22059        sqlite3_free(pNew);
   22060        pCandidate->nRef++;
   22061        unixLeaveMutex();
   22062        return pCandidate;
   22063     }
   22064   }
   22065 
   22066   /* No match was found.  We will make a new file ID */
   22067   pNew->nRef = 1;
   22068   pNew->nName = n;
   22069   pNew->pNext = vxworksFileList;
   22070   vxworksFileList = pNew;
   22071   unixLeaveMutex();
   22072   return pNew;
   22073 }
   22074 
   22075 /*
   22076 ** Decrement the reference count on a vxworksFileId object.  Free
   22077 ** the object when the reference count reaches zero.
   22078 */
   22079 static void vxworksReleaseFileId(struct vxworksFileId *pId){
   22080   unixEnterMutex();
   22081   assert( pId->nRef>0 );
   22082   pId->nRef--;
   22083   if( pId->nRef==0 ){
   22084     struct vxworksFileId **pp;
   22085     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
   22086     assert( *pp==pId );
   22087     *pp = pId->pNext;
   22088     sqlite3_free(pId);
   22089   }
   22090   unixLeaveMutex();
   22091 }
   22092 #endif /* OS_VXWORKS */
   22093 /*************** End of Unique File ID Utility Used By VxWorks ****************
   22094 ******************************************************************************/
   22095 
   22096 
   22097 /******************************************************************************
   22098 *************************** Posix Advisory Locking ****************************
   22099 **
   22100 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
   22101 ** section 6.5.2.2 lines 483 through 490 specify that when a process
   22102 ** sets or clears a lock, that operation overrides any prior locks set
   22103 ** by the same process.  It does not explicitly say so, but this implies
   22104 ** that it overrides locks set by the same process using a different
   22105 ** file descriptor.  Consider this test case:
   22106 **
   22107 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
   22108 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
   22109 **
   22110 ** Suppose ./file1 and ./file2 are really the same file (because
   22111 ** one is a hard or symbolic link to the other) then if you set
   22112 ** an exclusive lock on fd1, then try to get an exclusive lock
   22113 ** on fd2, it works.  I would have expected the second lock to
   22114 ** fail since there was already a lock on the file due to fd1.
   22115 ** But not so.  Since both locks came from the same process, the
   22116 ** second overrides the first, even though they were on different
   22117 ** file descriptors opened on different file names.
   22118 **
   22119 ** This means that we cannot use POSIX locks to synchronize file access
   22120 ** among competing threads of the same process.  POSIX locks will work fine
   22121 ** to synchronize access for threads in separate processes, but not
   22122 ** threads within the same process.
   22123 **
   22124 ** To work around the problem, SQLite has to manage file locks internally
   22125 ** on its own.  Whenever a new database is opened, we have to find the
   22126 ** specific inode of the database file (the inode is determined by the
   22127 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
   22128 ** and check for locks already existing on that inode.  When locks are
   22129 ** created or removed, we have to look at our own internal record of the
   22130 ** locks to see if another thread has previously set a lock on that same
   22131 ** inode.
   22132 **
   22133 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
   22134 ** For VxWorks, we have to use the alternative unique ID system based on
   22135 ** canonical filename and implemented in the previous division.)
   22136 **
   22137 ** The sqlite3_file structure for POSIX is no longer just an integer file
   22138 ** descriptor.  It is now a structure that holds the integer file
   22139 ** descriptor and a pointer to a structure that describes the internal
   22140 ** locks on the corresponding inode.  There is one locking structure
   22141 ** per inode, so if the same inode is opened twice, both unixFile structures
   22142 ** point to the same locking structure.  The locking structure keeps
   22143 ** a reference count (so we will know when to delete it) and a "cnt"
   22144 ** field that tells us its internal lock status.  cnt==0 means the
   22145 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
   22146 ** cnt>0 means there are cnt shared locks on the file.
   22147 **
   22148 ** Any attempt to lock or unlock a file first checks the locking
   22149 ** structure.  The fcntl() system call is only invoked to set a
   22150 ** POSIX lock if the internal lock structure transitions between
   22151 ** a locked and an unlocked state.
   22152 **
   22153 ** But wait:  there are yet more problems with POSIX advisory locks.
   22154 **
   22155 ** If you close a file descriptor that points to a file that has locks,
   22156 ** all locks on that file that are owned by the current process are
   22157 ** released.  To work around this problem, each unixFile structure contains
   22158 ** a pointer to an unixOpenCnt structure.  There is one unixOpenCnt structure
   22159 ** per open inode, which means that multiple unixFile can point to a single
   22160 ** unixOpenCnt.  When an attempt is made to close an unixFile, if there are
   22161 ** other unixFile open on the same inode that are holding locks, the call
   22162 ** to close() the file descriptor is deferred until all of the locks clear.
   22163 ** The unixOpenCnt structure keeps a list of file descriptors that need to
   22164 ** be closed and that list is walked (and cleared) when the last lock
   22165 ** clears.
   22166 **
   22167 ** Yet another problem:  LinuxThreads do not play well with posix locks.
   22168 **
   22169 ** Many older versions of linux use the LinuxThreads library which is
   22170 ** not posix compliant.  Under LinuxThreads, a lock created by thread
   22171 ** A cannot be modified or overridden by a different thread B.
   22172 ** Only thread A can modify the lock.  Locking behavior is correct
   22173 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
   22174 ** on linux - with NPTL a lock created by thread A can override locks
   22175 ** in thread B.  But there is no way to know at compile-time which
   22176 ** threading library is being used.  So there is no way to know at
   22177 ** compile-time whether or not thread A can override locks on thread B.
   22178 ** We have to do a run-time check to discover the behavior of the
   22179 ** current process.
   22180 **
   22181 ** On systems where thread A is unable to modify locks created by
   22182 ** thread B, we have to keep track of which thread created each
   22183 ** lock.  Hence there is an extra field in the key to the unixLockInfo
   22184 ** structure to record this information.  And on those systems it
   22185 ** is illegal to begin a transaction in one thread and finish it
   22186 ** in another.  For this latter restriction, there is no work-around.
   22187 ** It is a limitation of LinuxThreads.
   22188 */
   22189 
   22190 /*
   22191 ** Set or check the unixFile.tid field.  This field is set when an unixFile
   22192 ** is first opened.  All subsequent uses of the unixFile verify that the
   22193 ** same thread is operating on the unixFile.  Some operating systems do
   22194 ** not allow locks to be overridden by other threads and that restriction
   22195 ** means that sqlite3* database handles cannot be moved from one thread
   22196 ** to another while locks are held.
   22197 **
   22198 ** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
   22199 ** another as long as we are running on a system that supports threads
   22200 ** overriding each others locks (which is now the most common behavior)
   22201 ** or if no locks are held.  But the unixFile.pLock field needs to be
   22202 ** recomputed because its key includes the thread-id.  See the
   22203 ** transferOwnership() function below for additional information
   22204 */
   22205 #if SQLITE_THREADSAFE && defined(__linux__)
   22206 # define SET_THREADID(X)   (X)->tid = pthread_self()
   22207 # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
   22208                             !pthread_equal((X)->tid, pthread_self()))
   22209 #else
   22210 # define SET_THREADID(X)
   22211 # define CHECK_THREADID(X) 0
   22212 #endif
   22213 
   22214 /*
   22215 ** An instance of the following structure serves as the key used
   22216 ** to locate a particular unixOpenCnt structure given its inode.  This
   22217 ** is the same as the unixLockKey except that the thread ID is omitted.
   22218 */
   22219 struct unixFileId {
   22220   dev_t dev;                  /* Device number */
   22221 #if OS_VXWORKS
   22222   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
   22223 #else
   22224   ino_t ino;                  /* Inode number */
   22225 #endif
   22226 };
   22227 
   22228 /*
   22229 ** An instance of the following structure serves as the key used
   22230 ** to locate a particular unixLockInfo structure given its inode.
   22231 **
   22232 ** If threads cannot override each others locks (LinuxThreads), then we
   22233 ** set the unixLockKey.tid field to the thread ID.  If threads can override
   22234 ** each others locks (Posix and NPTL) then tid is always set to zero.
   22235 ** tid is omitted if we compile without threading support or on an OS
   22236 ** other than linux.
   22237 */
   22238 struct unixLockKey {
   22239   struct unixFileId fid;  /* Unique identifier for the file */
   22240 #if SQLITE_THREADSAFE && defined(__linux__)
   22241   pthread_t tid;  /* Thread ID of lock owner. Zero if not using LinuxThreads */
   22242 #endif
   22243 };
   22244 
   22245 /*
   22246 ** An instance of the following structure is allocated for each open
   22247 ** inode.  Or, on LinuxThreads, there is one of these structures for
   22248 ** each inode opened by each thread.
   22249 **
   22250 ** A single inode can have multiple file descriptors, so each unixFile
   22251 ** structure contains a pointer to an instance of this object and this
   22252 ** object keeps a count of the number of unixFile pointing to it.
   22253 */
   22254 struct unixLockInfo {
   22255   struct unixLockKey lockKey;     /* The lookup key */
   22256   int cnt;                        /* Number of SHARED locks held */
   22257   int locktype;                   /* One of SHARED_LOCK, RESERVED_LOCK etc. */
   22258   int nRef;                       /* Number of pointers to this structure */
   22259   struct unixLockInfo *pNext;     /* List of all unixLockInfo objects */
   22260   struct unixLockInfo *pPrev;     /*    .... doubly linked */
   22261 };
   22262 
   22263 /*
   22264 ** An instance of the following structure is allocated for each open
   22265 ** inode.  This structure keeps track of the number of locks on that
   22266 ** inode.  If a close is attempted against an inode that is holding
   22267 ** locks, the close is deferred until all locks clear by adding the
   22268 ** file descriptor to be closed to the pending list.
   22269 **
   22270 ** TODO:  Consider changing this so that there is only a single file
   22271 ** descriptor for each open file, even when it is opened multiple times.
   22272 ** The close() system call would only occur when the last database
   22273 ** using the file closes.
   22274 */
   22275 struct unixOpenCnt {
   22276   struct unixFileId fileId;   /* The lookup key */
   22277   int nRef;                   /* Number of pointers to this structure */
   22278   int nLock;                  /* Number of outstanding locks */
   22279   UnixUnusedFd *pUnused;      /* Unused file descriptors to close */
   22280 #if OS_VXWORKS
   22281   sem_t *pSem;                     /* Named POSIX semaphore */
   22282   char aSemName[MAX_PATHNAME+2];   /* Name of that semaphore */
   22283 #endif
   22284   struct unixOpenCnt *pNext, *pPrev;   /* List of all unixOpenCnt objects */
   22285 };
   22286 
   22287 /*
   22288 ** Lists of all unixLockInfo and unixOpenCnt objects.  These used to be hash
   22289 ** tables.  But the number of objects is rarely more than a dozen and
   22290 ** never exceeds a few thousand.  And lookup is not on a critical
   22291 ** path so a simple linked list will suffice.
   22292 */
   22293 static struct unixLockInfo *lockList = 0;
   22294 static struct unixOpenCnt *openList = 0;
   22295 
   22296 /*
   22297 ** This variable remembers whether or not threads can override each others
   22298 ** locks.
   22299 **
   22300 **    0:  No.  Threads cannot override each others locks.  (LinuxThreads)
   22301 **    1:  Yes.  Threads can override each others locks.  (Posix & NLPT)
   22302 **   -1:  We don't know yet.
   22303 **
   22304 ** On some systems, we know at compile-time if threads can override each
   22305 ** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
   22306 ** will be set appropriately.  On other systems, we have to check at
   22307 ** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
   22308 ** undefined.
   22309 **
   22310 ** This variable normally has file scope only.  But during testing, we make
   22311 ** it a global so that the test code can change its value in order to verify
   22312 ** that the right stuff happens in either case.
   22313 */
   22314 #if SQLITE_THREADSAFE && defined(__linux__)
   22315 #  ifndef SQLITE_THREAD_OVERRIDE_LOCK
   22316 #    define SQLITE_THREAD_OVERRIDE_LOCK -1
   22317 #  endif
   22318 #  ifdef SQLITE_TEST
   22319 int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
   22320 #  else
   22321 static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
   22322 #  endif
   22323 #endif
   22324 
   22325 /*
   22326 ** This structure holds information passed into individual test
   22327 ** threads by the testThreadLockingBehavior() routine.
   22328 */
   22329 struct threadTestData {
   22330   int fd;                /* File to be locked */
   22331   struct flock lock;     /* The locking operation */
   22332   int result;            /* Result of the locking operation */
   22333 };
   22334 
   22335 #if SQLITE_THREADSAFE && defined(__linux__)
   22336 /*
   22337 ** This function is used as the main routine for a thread launched by
   22338 ** testThreadLockingBehavior(). It tests whether the shared-lock obtained
   22339 ** by the main thread in testThreadLockingBehavior() conflicts with a
   22340 ** hypothetical write-lock obtained by this thread on the same file.
   22341 **
   22342 ** The write-lock is not actually acquired, as this is not possible if
   22343 ** the file is open in read-only mode (see ticket #3472).
   22344 */
   22345 static void *threadLockingTest(void *pArg){
   22346   struct threadTestData *pData = (struct threadTestData*)pArg;
   22347   pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
   22348   return pArg;
   22349 }
   22350 #endif /* SQLITE_THREADSAFE && defined(__linux__) */
   22351 
   22352 
   22353 #if SQLITE_THREADSAFE && defined(__linux__)
   22354 /*
   22355 ** This procedure attempts to determine whether or not threads
   22356 ** can override each others locks then sets the
   22357 ** threadsOverrideEachOthersLocks variable appropriately.
   22358 */
   22359 static void testThreadLockingBehavior(int fd_orig){
   22360   int fd;
   22361   int rc;
   22362   struct threadTestData d;
   22363   struct flock l;
   22364   pthread_t t;
   22365 
   22366   fd = dup(fd_orig);
   22367   if( fd<0 ) return;
   22368   memset(&l, 0, sizeof(l));
   22369   l.l_type = F_RDLCK;
   22370   l.l_len = 1;
   22371   l.l_start = 0;
   22372   l.l_whence = SEEK_SET;
   22373   rc = fcntl(fd_orig, F_SETLK, &l);
   22374   if( rc!=0 ) return;
   22375   memset(&d, 0, sizeof(d));
   22376   d.fd = fd;
   22377   d.lock = l;
   22378   d.lock.l_type = F_WRLCK;
   22379   if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
   22380     pthread_join(t, 0);
   22381   }
   22382   close(fd);
   22383   if( d.result!=0 ) return;
   22384   threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
   22385 }
   22386 #endif /* SQLITE_THREADSAFE && defined(__linux__) */
   22387 
   22388 /*
   22389 ** Release a unixLockInfo structure previously allocated by findLockInfo().
   22390 **
   22391 ** The mutex entered using the unixEnterMutex() function must be held
   22392 ** when this function is called.
   22393 */
   22394 static void releaseLockInfo(struct unixLockInfo *pLock){
   22395   assert( unixMutexHeld() );
   22396   if( pLock ){
   22397     pLock->nRef--;
   22398     if( pLock->nRef==0 ){
   22399       if( pLock->pPrev ){
   22400         assert( pLock->pPrev->pNext==pLock );
   22401         pLock->pPrev->pNext = pLock->pNext;
   22402       }else{
   22403         assert( lockList==pLock );
   22404         lockList = pLock->pNext;
   22405       }
   22406       if( pLock->pNext ){
   22407         assert( pLock->pNext->pPrev==pLock );
   22408         pLock->pNext->pPrev = pLock->pPrev;
   22409       }
   22410       sqlite3_free(pLock);
   22411     }
   22412   }
   22413 }
   22414 
   22415 /*
   22416 ** Release a unixOpenCnt structure previously allocated by findLockInfo().
   22417 **
   22418 ** The mutex entered using the unixEnterMutex() function must be held
   22419 ** when this function is called.
   22420 */
   22421 static void releaseOpenCnt(struct unixOpenCnt *pOpen){
   22422   assert( unixMutexHeld() );
   22423   if( pOpen ){
   22424     pOpen->nRef--;
   22425     if( pOpen->nRef==0 ){
   22426       if( pOpen->pPrev ){
   22427         assert( pOpen->pPrev->pNext==pOpen );
   22428         pOpen->pPrev->pNext = pOpen->pNext;
   22429       }else{
   22430         assert( openList==pOpen );
   22431         openList = pOpen->pNext;
   22432       }
   22433       if( pOpen->pNext ){
   22434         assert( pOpen->pNext->pPrev==pOpen );
   22435         pOpen->pNext->pPrev = pOpen->pPrev;
   22436       }
   22437 #if SQLITE_THREADSAFE && defined(__linux__)
   22438       assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
   22439 #endif
   22440 
   22441       /* If pOpen->pUnused is not null, then memory and file-descriptors
   22442       ** are leaked.
   22443       **
   22444       ** This will only happen if, under Linuxthreads, the user has opened
   22445       ** a transaction in one thread, then attempts to close the database
   22446       ** handle from another thread (without first unlocking the db file).
   22447       ** This is a misuse.  */
   22448       sqlite3_free(pOpen);
   22449     }
   22450   }
   22451 }
   22452 
   22453 /*
   22454 ** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
   22455 ** describes that file descriptor.  Create new ones if necessary.  The
   22456 ** return values might be uninitialized if an error occurs.
   22457 **
   22458 ** The mutex entered using the unixEnterMutex() function must be held
   22459 ** when this function is called.
   22460 **
   22461 ** Return an appropriate error code.
   22462 */
   22463 static int findLockInfo(
   22464   unixFile *pFile,               /* Unix file with file desc used in the key */
   22465   struct unixLockInfo **ppLock,  /* Return the unixLockInfo structure here */
   22466   struct unixOpenCnt **ppOpen    /* Return the unixOpenCnt structure here */
   22467 ){
   22468   int rc;                        /* System call return code */
   22469   int fd;                        /* The file descriptor for pFile */
   22470   struct unixLockKey lockKey;    /* Lookup key for the unixLockInfo structure */
   22471   struct unixFileId fileId;      /* Lookup key for the unixOpenCnt struct */
   22472   struct stat statbuf;           /* Low-level file information */
   22473   struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
   22474   struct unixOpenCnt *pOpen;     /* Candidate unixOpenCnt object */
   22475 
   22476   assert( unixMutexHeld() );
   22477 
   22478   /* Get low-level information about the file that we can used to
   22479   ** create a unique name for the file.
   22480   */
   22481   fd = pFile->h;
   22482   rc = fstat(fd, &statbuf);
   22483   if( rc!=0 ){
   22484     pFile->lastErrno = errno;
   22485 #ifdef EOVERFLOW
   22486     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
   22487 #endif
   22488     return SQLITE_IOERR;
   22489   }
   22490 
   22491 #ifdef __APPLE__
   22492   /* On OS X on an msdos filesystem, the inode number is reported
   22493   ** incorrectly for zero-size files.  See ticket #3260.  To work
   22494   ** around this problem (we consider it a bug in OS X, not SQLite)
   22495   ** we always increase the file size to 1 by writing a single byte
   22496   ** prior to accessing the inode number.  The one byte written is
   22497   ** an ASCII 'S' character which also happens to be the first byte
   22498   ** in the header of every SQLite database.  In this way, if there
   22499   ** is a race condition such that another thread has already populated
   22500   ** the first page of the database, no damage is done.
   22501   */
   22502   if( statbuf.st_size==0 ){
   22503     rc = write(fd, "S", 1);
   22504     if( rc!=1 ){
   22505       return SQLITE_IOERR;
   22506     }
   22507     rc = fstat(fd, &statbuf);
   22508     if( rc!=0 ){
   22509       pFile->lastErrno = errno;
   22510       return SQLITE_IOERR;
   22511     }
   22512   }
   22513 #endif
   22514 
   22515   memset(&lockKey, 0, sizeof(lockKey));
   22516   lockKey.fid.dev = statbuf.st_dev;
   22517 #if OS_VXWORKS
   22518   lockKey.fid.pId = pFile->pId;
   22519 #else
   22520   lockKey.fid.ino = statbuf.st_ino;
   22521 #endif
   22522 #if SQLITE_THREADSAFE && defined(__linux__)
   22523   if( threadsOverrideEachOthersLocks<0 ){
   22524     testThreadLockingBehavior(fd);
   22525   }
   22526   lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
   22527 #endif
   22528   fileId = lockKey.fid;
   22529   if( ppLock!=0 ){
   22530     pLock = lockList;
   22531     while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
   22532       pLock = pLock->pNext;
   22533     }
   22534     if( pLock==0 ){
   22535       pLock = sqlite3_malloc( sizeof(*pLock) );
   22536       if( pLock==0 ){
   22537         rc = SQLITE_NOMEM;
   22538         goto exit_findlockinfo;
   22539       }
   22540       memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey));
   22541       pLock->nRef = 1;
   22542       pLock->cnt = 0;
   22543       pLock->locktype = 0;
   22544       pLock->pNext = lockList;
   22545       pLock->pPrev = 0;
   22546       if( lockList ) lockList->pPrev = pLock;
   22547       lockList = pLock;
   22548     }else{
   22549       pLock->nRef++;
   22550     }
   22551     *ppLock = pLock;
   22552   }
   22553   if( ppOpen!=0 ){
   22554     pOpen = openList;
   22555     while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
   22556       pOpen = pOpen->pNext;
   22557     }
   22558     if( pOpen==0 ){
   22559       pOpen = sqlite3_malloc( sizeof(*pOpen) );
   22560       if( pOpen==0 ){
   22561         releaseLockInfo(pLock);
   22562         rc = SQLITE_NOMEM;
   22563         goto exit_findlockinfo;
   22564       }
   22565       memset(pOpen, 0, sizeof(*pOpen));
   22566       pOpen->fileId = fileId;
   22567       pOpen->nRef = 1;
   22568       pOpen->pNext = openList;
   22569       if( openList ) openList->pPrev = pOpen;
   22570       openList = pOpen;
   22571     }else{
   22572       pOpen->nRef++;
   22573     }
   22574     *ppOpen = pOpen;
   22575   }
   22576 
   22577 exit_findlockinfo:
   22578   return rc;
   22579 }
   22580 
   22581 /*
   22582 ** If we are currently in a different thread than the thread that the
   22583 ** unixFile argument belongs to, then transfer ownership of the unixFile
   22584 ** over to the current thread.
   22585 **
   22586 ** A unixFile is only owned by a thread on systems that use LinuxThreads.
   22587 **
   22588 ** Ownership transfer is only allowed if the unixFile is currently unlocked.
   22589 ** If the unixFile is locked and an ownership is wrong, then return
   22590 ** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
   22591 */
   22592 #if SQLITE_THREADSAFE && defined(__linux__)
   22593 static int transferOwnership(unixFile *pFile){
   22594   int rc;
   22595   pthread_t hSelf;
   22596   if( threadsOverrideEachOthersLocks ){
   22597     /* Ownership transfers not needed on this system */
   22598     return SQLITE_OK;
   22599   }
   22600   hSelf = pthread_self();
   22601   if( pthread_equal(pFile->tid, hSelf) ){
   22602     /* We are still in the same thread */
   22603     OSTRACE1("No-transfer, same thread\n");
   22604     return SQLITE_OK;
   22605   }
   22606   if( pFile->locktype!=NO_LOCK ){
   22607     /* We cannot change ownership while we are holding a lock! */
   22608     return SQLITE_MISUSE_BKPT;
   22609   }
   22610   OSTRACE4("Transfer ownership of %d from %d to %d\n",
   22611             pFile->h, pFile->tid, hSelf);
   22612   pFile->tid = hSelf;
   22613   if (pFile->pLock != NULL) {
   22614     releaseLockInfo(pFile->pLock);
   22615     rc = findLockInfo(pFile, &pFile->pLock, 0);
   22616     OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
   22617            locktypeName(pFile->locktype),
   22618            locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
   22619     return rc;
   22620   } else {
   22621     return SQLITE_OK;
   22622   }
   22623 }
   22624 #else  /* if not SQLITE_THREADSAFE */
   22625   /* On single-threaded builds, ownership transfer is a no-op */
   22626 # define transferOwnership(X) SQLITE_OK
   22627 #endif /* SQLITE_THREADSAFE */
   22628 
   22629 
   22630 /*
   22631 ** This routine checks if there is a RESERVED lock held on the specified
   22632 ** file by this or any other process. If such a lock is held, set *pResOut
   22633 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   22634 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   22635 */
   22636 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
   22637   int rc = SQLITE_OK;
   22638   int reserved = 0;
   22639   unixFile *pFile = (unixFile*)id;
   22640 
   22641   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   22642 
   22643   assert( pFile );
   22644   unixEnterMutex(); /* Because pFile->pLock is shared across threads */
   22645 
   22646   /* Check if a thread in this process holds such a lock */
   22647   if( pFile->pLock->locktype>SHARED_LOCK ){
   22648     reserved = 1;
   22649   }
   22650 
   22651   /* Otherwise see if some other process holds it.
   22652   */
   22653 #ifndef __DJGPP__
   22654   if( !reserved ){
   22655     struct flock lock;
   22656     lock.l_whence = SEEK_SET;
   22657     lock.l_start = RESERVED_BYTE;
   22658     lock.l_len = 1;
   22659     lock.l_type = F_WRLCK;
   22660     if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
   22661       int tErrno = errno;
   22662       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
   22663       pFile->lastErrno = tErrno;
   22664     } else if( lock.l_type!=F_UNLCK ){
   22665       reserved = 1;
   22666     }
   22667   }
   22668 #endif
   22669 
   22670   unixLeaveMutex();
   22671   OSTRACE4("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved);
   22672 
   22673   *pResOut = reserved;
   22674   return rc;
   22675 }
   22676 
   22677 /*
   22678 ** Perform a file locking operation on a range of bytes in a file.
   22679 ** The "op" parameter should be one of F_RDLCK, F_WRLCK, or F_UNLCK.
   22680 ** Return 0 on success or -1 for failure.  On failure, write the error
   22681 ** code into *pErrcode.
   22682 **
   22683 ** If the SQLITE_WHOLE_FILE_LOCKING bit is clear, then only lock
   22684 ** the range of bytes on the locking page between SHARED_FIRST and
   22685 ** SHARED_SIZE.  If SQLITE_WHOLE_FILE_LOCKING is set, then lock all
   22686 ** bytes from 0 up to but not including PENDING_BYTE, and all bytes
   22687 ** that follow SHARED_FIRST.
   22688 **
   22689 ** In other words, of SQLITE_WHOLE_FILE_LOCKING if false (the historical
   22690 ** default case) then only lock a small range of bytes from SHARED_FIRST
   22691 ** through SHARED_FIRST+SHARED_SIZE-1.  But if SQLITE_WHOLE_FILE_LOCKING is
   22692 ** true then lock every byte in the file except for PENDING_BYTE and
   22693 ** RESERVED_BYTE.
   22694 **
   22695 ** SQLITE_WHOLE_FILE_LOCKING=true overlaps SQLITE_WHOLE_FILE_LOCKING=false
   22696 ** and so the locking schemes are compatible.  One type of lock will
   22697 ** effectively exclude the other type.  The reason for using the
   22698 ** SQLITE_WHOLE_FILE_LOCKING=true is that by indicating the full range
   22699 ** of bytes to be read or written, we give hints to NFS to help it
   22700 ** maintain cache coherency.  On the other hand, whole file locking
   22701 ** is slower, so we don't want to use it except for NFS.
   22702 */
   22703 static int rangeLock(unixFile *pFile, int op, int *pErrcode){
   22704   struct flock lock;
   22705   int rc;
   22706   lock.l_type = op;
   22707   lock.l_start = SHARED_FIRST;
   22708   lock.l_whence = SEEK_SET;
   22709   if( (pFile->fileFlags & SQLITE_WHOLE_FILE_LOCKING)==0 ){
   22710     lock.l_len = SHARED_SIZE;
   22711     rc = fcntl(pFile->h, F_SETLK, &lock);
   22712     *pErrcode = errno;
   22713   }else{
   22714     lock.l_len = 0;
   22715     rc = fcntl(pFile->h, F_SETLK, &lock);
   22716     *pErrcode = errno;
   22717     if( NEVER(op==F_UNLCK) || rc!=(-1) ){
   22718       lock.l_start = 0;
   22719       lock.l_len = PENDING_BYTE;
   22720       rc = fcntl(pFile->h, F_SETLK, &lock);
   22721       if( ALWAYS(op!=F_UNLCK) && rc==(-1) ){
   22722         *pErrcode = errno;
   22723         lock.l_type = F_UNLCK;
   22724         lock.l_start = SHARED_FIRST;
   22725         lock.l_len = 0;
   22726         fcntl(pFile->h, F_SETLK, &lock);
   22727       }
   22728     }
   22729   }
   22730   return rc;
   22731 }
   22732 
   22733 /*
   22734 ** Lock the file with the lock specified by parameter locktype - one
   22735 ** of the following:
   22736 **
   22737 **     (1) SHARED_LOCK
   22738 **     (2) RESERVED_LOCK
   22739 **     (3) PENDING_LOCK
   22740 **     (4) EXCLUSIVE_LOCK
   22741 **
   22742 ** Sometimes when requesting one lock state, additional lock states
   22743 ** are inserted in between.  The locking might fail on one of the later
   22744 ** transitions leaving the lock state different from what it started but
   22745 ** still short of its goal.  The following chart shows the allowed
   22746 ** transitions and the inserted intermediate states:
   22747 **
   22748 **    UNLOCKED -> SHARED
   22749 **    SHARED -> RESERVED
   22750 **    SHARED -> (PENDING) -> EXCLUSIVE
   22751 **    RESERVED -> (PENDING) -> EXCLUSIVE
   22752 **    PENDING -> EXCLUSIVE
   22753 **
   22754 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   22755 ** routine to lower a locking level.
   22756 */
   22757 static int unixLock(sqlite3_file *id, int locktype){
   22758   /* The following describes the implementation of the various locks and
   22759   ** lock transitions in terms of the POSIX advisory shared and exclusive
   22760   ** lock primitives (called read-locks and write-locks below, to avoid
   22761   ** confusion with SQLite lock names). The algorithms are complicated
   22762   ** slightly in order to be compatible with windows systems simultaneously
   22763   ** accessing the same database file, in case that is ever required.
   22764   **
   22765   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
   22766   ** byte', each single bytes at well known offsets, and the 'shared byte
   22767   ** range', a range of 510 bytes at a well known offset.
   22768   **
   22769   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
   22770   ** byte'.  If this is successful, a random byte from the 'shared byte
   22771   ** range' is read-locked and the lock on the 'pending byte' released.
   22772   **
   22773   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
   22774   ** A RESERVED lock is implemented by grabbing a write-lock on the
   22775   ** 'reserved byte'.
   22776   **
   22777   ** A process may only obtain a PENDING lock after it has obtained a
   22778   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
   22779   ** on the 'pending byte'. This ensures that no new SHARED locks can be
   22780   ** obtained, but existing SHARED locks are allowed to persist. A process
   22781   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
   22782   ** This property is used by the algorithm for rolling back a journal file
   22783   ** after a crash.
   22784   **
   22785   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
   22786   ** implemented by obtaining a write-lock on the entire 'shared byte
   22787   ** range'. Since all other locks require a read-lock on one of the bytes
   22788   ** within this range, this ensures that no other locks are held on the
   22789   ** database.
   22790   **
   22791   ** The reason a single byte cannot be used instead of the 'shared byte
   22792   ** range' is that some versions of windows do not support read-locks. By
   22793   ** locking a random byte from a range, concurrent SHARED locks may exist
   22794   ** even if the locking primitive used is always a write-lock.
   22795   */
   22796   int rc = SQLITE_OK;
   22797   unixFile *pFile = (unixFile*)id;
   22798   struct unixLockInfo *pLock = pFile->pLock;
   22799   struct flock lock;
   22800   int s = 0;
   22801   int tErrno;
   22802 
   22803   assert( pFile );
   22804   OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
   22805       locktypeName(locktype), locktypeName(pFile->locktype),
   22806       locktypeName(pLock->locktype), pLock->cnt , getpid());
   22807 
   22808   /* If there is already a lock of this type or more restrictive on the
   22809   ** unixFile, do nothing. Don't use the end_lock: exit path, as
   22810   ** unixEnterMutex() hasn't been called yet.
   22811   */
   22812   if( pFile->locktype>=locktype ){
   22813     OSTRACE3("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
   22814             locktypeName(locktype));
   22815     return SQLITE_OK;
   22816   }
   22817 
   22818   /* Make sure the locking sequence is correct.
   22819   **  (1) We never move from unlocked to anything higher than shared lock.
   22820   **  (2) SQLite never explicitly requests a pendig lock.
   22821   **  (3) A shared lock is always held when a reserve lock is requested.
   22822   */
   22823   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
   22824   assert( locktype!=PENDING_LOCK );
   22825   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
   22826 
   22827   /* This mutex is needed because pFile->pLock is shared across threads
   22828   */
   22829   unixEnterMutex();
   22830 
   22831   /* Make sure the current thread owns the pFile.
   22832   */
   22833   rc = transferOwnership(pFile);
   22834   if( rc!=SQLITE_OK ){
   22835     unixLeaveMutex();
   22836     return rc;
   22837   }
   22838   pLock = pFile->pLock;
   22839 
   22840   /* If some thread using this PID has a lock via a different unixFile*
   22841   ** handle that precludes the requested lock, return BUSY.
   22842   */
   22843   if( (pFile->locktype!=pLock->locktype &&
   22844           (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
   22845   ){
   22846     rc = SQLITE_BUSY;
   22847     goto end_lock;
   22848   }
   22849 
   22850   /* If a SHARED lock is requested, and some thread using this PID already
   22851   ** has a SHARED or RESERVED lock, then increment reference counts and
   22852   ** return SQLITE_OK.
   22853   */
   22854   if( locktype==SHARED_LOCK &&
   22855       (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
   22856     assert( locktype==SHARED_LOCK );
   22857     assert( pFile->locktype==0 );
   22858     assert( pLock->cnt>0 );
   22859     pFile->locktype = SHARED_LOCK;
   22860     pLock->cnt++;
   22861     pFile->pOpen->nLock++;
   22862     goto end_lock;
   22863   }
   22864 
   22865 
   22866   /* A PENDING lock is needed before acquiring a SHARED lock and before
   22867   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   22868   ** be released.
   22869   */
   22870   lock.l_len = 1L;
   22871   lock.l_whence = SEEK_SET;
   22872   if( locktype==SHARED_LOCK
   22873       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
   22874   ){
   22875     lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
   22876     lock.l_start = PENDING_BYTE;
   22877     s = fcntl(pFile->h, F_SETLK, &lock);
   22878     if( s==(-1) ){
   22879       tErrno = errno;
   22880       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   22881       if( IS_LOCK_ERROR(rc) ){
   22882         pFile->lastErrno = tErrno;
   22883       }
   22884       goto end_lock;
   22885     }
   22886   }
   22887 
   22888 
   22889   /* If control gets to this point, then actually go ahead and make
   22890   ** operating system calls for the specified lock.
   22891   */
   22892   if( locktype==SHARED_LOCK ){
   22893     assert( pLock->cnt==0 );
   22894     assert( pLock->locktype==0 );
   22895 
   22896     /* Now get the read-lock */
   22897     s = rangeLock(pFile, F_RDLCK, &tErrno);
   22898 
   22899     /* Drop the temporary PENDING lock */
   22900     lock.l_start = PENDING_BYTE;
   22901     lock.l_len = 1L;
   22902     lock.l_type = F_UNLCK;
   22903     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
   22904       if( s != -1 ){
   22905         /* This could happen with a network mount */
   22906         tErrno = errno;
   22907         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   22908         if( IS_LOCK_ERROR(rc) ){
   22909           pFile->lastErrno = tErrno;
   22910         }
   22911         goto end_lock;
   22912       }
   22913     }
   22914     if( s==(-1) ){
   22915       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   22916       if( IS_LOCK_ERROR(rc) ){
   22917         pFile->lastErrno = tErrno;
   22918       }
   22919     }else{
   22920       pFile->locktype = SHARED_LOCK;
   22921       pFile->pOpen->nLock++;
   22922       pLock->cnt = 1;
   22923     }
   22924   }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
   22925     /* We are trying for an exclusive lock but another thread in this
   22926     ** same process is still holding a shared lock. */
   22927     rc = SQLITE_BUSY;
   22928   }else{
   22929     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
   22930     ** assumed that there is a SHARED or greater lock on the file
   22931     ** already.
   22932     */
   22933     assert( 0!=pFile->locktype );
   22934     lock.l_type = F_WRLCK;
   22935     switch( locktype ){
   22936       case RESERVED_LOCK:
   22937         lock.l_start = RESERVED_BYTE;
   22938         s = fcntl(pFile->h, F_SETLK, &lock);
   22939         tErrno = errno;
   22940         break;
   22941       case EXCLUSIVE_LOCK:
   22942         s = rangeLock(pFile, F_WRLCK, &tErrno);
   22943         break;
   22944       default:
   22945         assert(0);
   22946     }
   22947     if( s==(-1) ){
   22948       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   22949       if( IS_LOCK_ERROR(rc) ){
   22950         pFile->lastErrno = tErrno;
   22951       }
   22952     }
   22953   }
   22954 
   22955 
   22956 #ifndef NDEBUG
   22957   /* Set up the transaction-counter change checking flags when
   22958   ** transitioning from a SHARED to a RESERVED lock.  The change
   22959   ** from SHARED to RESERVED marks the beginning of a normal
   22960   ** write operation (not a hot journal rollback).
   22961   */
   22962   if( rc==SQLITE_OK
   22963    && pFile->locktype<=SHARED_LOCK
   22964    && locktype==RESERVED_LOCK
   22965   ){
   22966     pFile->transCntrChng = 0;
   22967     pFile->dbUpdate = 0;
   22968     pFile->inNormalWrite = 1;
   22969   }
   22970 #endif
   22971 
   22972 
   22973   if( rc==SQLITE_OK ){
   22974     pFile->locktype = locktype;
   22975     pLock->locktype = locktype;
   22976   }else if( locktype==EXCLUSIVE_LOCK ){
   22977     pFile->locktype = PENDING_LOCK;
   22978     pLock->locktype = PENDING_LOCK;
   22979   }
   22980 
   22981 end_lock:
   22982   unixLeaveMutex();
   22983   OSTRACE4("LOCK    %d %s %s (unix)\n", pFile->h, locktypeName(locktype),
   22984       rc==SQLITE_OK ? "ok" : "failed");
   22985   return rc;
   22986 }
   22987 
   22988 /*
   22989 ** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
   22990 ** If all such file descriptors are closed without error, the list is
   22991 ** cleared and SQLITE_OK returned.
   22992 **
   22993 ** Otherwise, if an error occurs, then successfully closed file descriptor
   22994 ** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
   22995 ** not deleted and SQLITE_IOERR_CLOSE returned.
   22996 */
   22997 static int closePendingFds(unixFile *pFile){
   22998   int rc = SQLITE_OK;
   22999   struct unixOpenCnt *pOpen = pFile->pOpen;
   23000   UnixUnusedFd *pError = 0;
   23001   UnixUnusedFd *p;
   23002   UnixUnusedFd *pNext;
   23003   for(p=pOpen->pUnused; p; p=pNext){
   23004     pNext = p->pNext;
   23005     if( close(p->fd) ){
   23006       pFile->lastErrno = errno;
   23007       rc = SQLITE_IOERR_CLOSE;
   23008       p->pNext = pError;
   23009       pError = p;
   23010     }else{
   23011       sqlite3_free(p);
   23012     }
   23013   }
   23014   pOpen->pUnused = pError;
   23015   return rc;
   23016 }
   23017 
   23018 /*
   23019 ** Add the file descriptor used by file handle pFile to the corresponding
   23020 ** pUnused list.
   23021 */
   23022 static void setPendingFd(unixFile *pFile){
   23023   struct unixOpenCnt *pOpen = pFile->pOpen;
   23024   UnixUnusedFd *p = pFile->pUnused;
   23025   p->pNext = pOpen->pUnused;
   23026   pOpen->pUnused = p;
   23027   pFile->h = -1;
   23028   pFile->pUnused = 0;
   23029 }
   23030 
   23031 /*
   23032 ** Lower the locking level on file descriptor pFile to locktype.  locktype
   23033 ** must be either NO_LOCK or SHARED_LOCK.
   23034 **
   23035 ** If the locking level of the file descriptor is already at or below
   23036 ** the requested locking level, this routine is a no-op.
   23037 */
   23038 static int unixUnlock(sqlite3_file *id, int locktype){
   23039   unixFile *pFile = (unixFile*)id; /* The open file */
   23040   struct unixLockInfo *pLock;      /* Structure describing current lock state */
   23041   struct flock lock;               /* Information passed into fcntl() */
   23042   int rc = SQLITE_OK;              /* Return code from this interface */
   23043   int h;                           /* The underlying file descriptor */
   23044   int tErrno;                      /* Error code from system call errors */
   23045 
   23046   assert( pFile );
   23047   OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, locktype,
   23048       pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
   23049 
   23050   assert( locktype<=SHARED_LOCK );
   23051   if( pFile->locktype<=locktype ){
   23052     return SQLITE_OK;
   23053   }
   23054   if( CHECK_THREADID(pFile) ){
   23055     return SQLITE_MISUSE_BKPT;
   23056   }
   23057   unixEnterMutex();
   23058   h = pFile->h;
   23059   pLock = pFile->pLock;
   23060   assert( pLock->cnt!=0 );
   23061   if( pFile->locktype>SHARED_LOCK ){
   23062     assert( pLock->locktype==pFile->locktype );
   23063     SimulateIOErrorBenign(1);
   23064     SimulateIOError( h=(-1) )
   23065     SimulateIOErrorBenign(0);
   23066 
   23067 #ifndef NDEBUG
   23068     /* When reducing a lock such that other processes can start
   23069     ** reading the database file again, make sure that the
   23070     ** transaction counter was updated if any part of the database
   23071     ** file changed.  If the transaction counter is not updated,
   23072     ** other connections to the same file might not realize that
   23073     ** the file has changed and hence might not know to flush their
   23074     ** cache.  The use of a stale cache can lead to database corruption.
   23075     */
   23076     assert( pFile->inNormalWrite==0
   23077          || pFile->dbUpdate==0
   23078          || pFile->transCntrChng==1 );
   23079     pFile->inNormalWrite = 0;
   23080 #endif
   23081 
   23082 
   23083     if( locktype==SHARED_LOCK ){
   23084       if( rangeLock(pFile, F_RDLCK, &tErrno)==(-1) ){
   23085         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
   23086         if( IS_LOCK_ERROR(rc) ){
   23087           pFile->lastErrno = tErrno;
   23088         }
   23089         goto end_unlock;
   23090       }
   23091     }
   23092     lock.l_type = F_UNLCK;
   23093     lock.l_whence = SEEK_SET;
   23094     lock.l_start = PENDING_BYTE;
   23095     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
   23096     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
   23097       pLock->locktype = SHARED_LOCK;
   23098     }else{
   23099       tErrno = errno;
   23100       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   23101       if( IS_LOCK_ERROR(rc) ){
   23102         pFile->lastErrno = tErrno;
   23103       }
   23104       goto end_unlock;
   23105     }
   23106   }
   23107   if( locktype==NO_LOCK ){
   23108     struct unixOpenCnt *pOpen;
   23109 
   23110     /* Decrement the shared lock counter.  Release the lock using an
   23111     ** OS call only when all threads in this same process have released
   23112     ** the lock.
   23113     */
   23114     pLock->cnt--;
   23115     if( pLock->cnt==0 ){
   23116       lock.l_type = F_UNLCK;
   23117       lock.l_whence = SEEK_SET;
   23118       lock.l_start = lock.l_len = 0L;
   23119       SimulateIOErrorBenign(1);
   23120       SimulateIOError( h=(-1) )
   23121       SimulateIOErrorBenign(0);
   23122       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
   23123         pLock->locktype = NO_LOCK;
   23124       }else{
   23125         tErrno = errno;
   23126         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   23127         if( IS_LOCK_ERROR(rc) ){
   23128           pFile->lastErrno = tErrno;
   23129         }
   23130         pLock->locktype = NO_LOCK;
   23131         pFile->locktype = NO_LOCK;
   23132       }
   23133     }
   23134 
   23135     /* Decrement the count of locks against this same file.  When the
   23136     ** count reaches zero, close any other file descriptors whose close
   23137     ** was deferred because of outstanding locks.
   23138     */
   23139     pOpen = pFile->pOpen;
   23140     pOpen->nLock--;
   23141     assert( pOpen->nLock>=0 );
   23142     if( pOpen->nLock==0 ){
   23143       int rc2 = closePendingFds(pFile);
   23144       if( rc==SQLITE_OK ){
   23145         rc = rc2;
   23146       }
   23147     }
   23148   }
   23149 
   23150 end_unlock:
   23151   unixLeaveMutex();
   23152   if( rc==SQLITE_OK ) pFile->locktype = locktype;
   23153   return rc;
   23154 }
   23155 
   23156 /*
   23157 ** This function performs the parts of the "close file" operation
   23158 ** common to all locking schemes. It closes the directory and file
   23159 ** handles, if they are valid, and sets all fields of the unixFile
   23160 ** structure to 0.
   23161 **
   23162 ** It is *not* necessary to hold the mutex when this routine is called,
   23163 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
   23164 ** vxworksReleaseFileId() routine.
   23165 */
   23166 static int closeUnixFile(sqlite3_file *id){
   23167   unixFile *pFile = (unixFile*)id;
   23168   if( pFile ){
   23169     if( pFile->dirfd>=0 ){
   23170       int err = close(pFile->dirfd);
   23171       if( err ){
   23172         pFile->lastErrno = errno;
   23173         return SQLITE_IOERR_DIR_CLOSE;
   23174       }else{
   23175         pFile->dirfd=-1;
   23176       }
   23177     }
   23178     if( pFile->h>=0 ){
   23179       int err = close(pFile->h);
   23180       if( err ){
   23181         pFile->lastErrno = errno;
   23182         return SQLITE_IOERR_CLOSE;
   23183       }
   23184     }
   23185 #if OS_VXWORKS
   23186     if( pFile->pId ){
   23187       if( pFile->isDelete ){
   23188         unlink(pFile->pId->zCanonicalName);
   23189       }
   23190       vxworksReleaseFileId(pFile->pId);
   23191       pFile->pId = 0;
   23192     }
   23193 #endif
   23194     OSTRACE2("CLOSE   %-3d\n", pFile->h);
   23195     OpenCounter(-1);
   23196     sqlite3_free(pFile->pUnused);
   23197     memset(pFile, 0, sizeof(unixFile));
   23198   }
   23199   return SQLITE_OK;
   23200 }
   23201 
   23202 /*
   23203 ** Close a file.
   23204 */
   23205 static int unixClose(sqlite3_file *id){
   23206   int rc = SQLITE_OK;
   23207   if( id ){
   23208     unixFile *pFile = (unixFile *)id;
   23209     unixUnlock(id, NO_LOCK);
   23210     unixEnterMutex();
   23211     if( pFile->pOpen && pFile->pOpen->nLock ){
   23212       /* If there are outstanding locks, do not actually close the file just
   23213       ** yet because that would clear those locks.  Instead, add the file
   23214       ** descriptor to pOpen->pUnused list.  It will be automatically closed
   23215       ** when the last lock is cleared.
   23216       */
   23217       setPendingFd(pFile);
   23218     }
   23219     releaseLockInfo(pFile->pLock);
   23220     releaseOpenCnt(pFile->pOpen);
   23221     rc = closeUnixFile(id);
   23222     unixLeaveMutex();
   23223   }
   23224   return rc;
   23225 }
   23226 
   23227 /************** End of the posix advisory lock implementation *****************
   23228 ******************************************************************************/
   23229 
   23230 /******************************************************************************
   23231 ****************************** No-op Locking **********************************
   23232 **
   23233 ** Of the various locking implementations available, this is by far the
   23234 ** simplest:  locking is ignored.  No attempt is made to lock the database
   23235 ** file for reading or writing.
   23236 **
   23237 ** This locking mode is appropriate for use on read-only databases
   23238 ** (ex: databases that are burned into CD-ROM, for example.)  It can
   23239 ** also be used if the application employs some external mechanism to
   23240 ** prevent simultaneous access of the same database by two or more
   23241 ** database connections.  But there is a serious risk of database
   23242 ** corruption if this locking mode is used in situations where multiple
   23243 ** database connections are accessing the same database file at the same
   23244 ** time and one or more of those connections are writing.
   23245 */
   23246 
   23247 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
   23248   UNUSED_PARAMETER(NotUsed);
   23249   *pResOut = 0;
   23250   return SQLITE_OK;
   23251 }
   23252 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
   23253   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   23254   return SQLITE_OK;
   23255 }
   23256 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
   23257   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   23258   return SQLITE_OK;
   23259 }
   23260 
   23261 /*
   23262 ** Close the file.
   23263 */
   23264 static int nolockClose(sqlite3_file *id) {
   23265   return closeUnixFile(id);
   23266 }
   23267 
   23268 /******************* End of the no-op lock implementation *********************
   23269 ******************************************************************************/
   23270 
   23271 /******************************************************************************
   23272 ************************* Begin dot-file Locking ******************************
   23273 **
   23274 ** The dotfile locking implementation uses the existance of separate lock
   23275 ** files in order to control access to the database.  This works on just
   23276 ** about every filesystem imaginable.  But there are serious downsides:
   23277 **
   23278 **    (1)  There is zero concurrency.  A single reader blocks all other
   23279 **         connections from reading or writing the database.
   23280 **
   23281 **    (2)  An application crash or power loss can leave stale lock files
   23282 **         sitting around that need to be cleared manually.
   23283 **
   23284 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
   23285 ** other locking strategy is available.
   23286 **
   23287 ** Dotfile locking works by creating a file in the same directory as the
   23288 ** database and with the same name but with a ".lock" extension added.
   23289 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
   23290 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
   23291 */
   23292 
   23293 /*
   23294 ** The file suffix added to the data base filename in order to create the
   23295 ** lock file.
   23296 */
   23297 #define DOTLOCK_SUFFIX ".lock"
   23298 
   23299 /*
   23300 ** This routine checks if there is a RESERVED lock held on the specified
   23301 ** file by this or any other process. If such a lock is held, set *pResOut
   23302 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   23303 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   23304 **
   23305 ** In dotfile locking, either a lock exists or it does not.  So in this
   23306 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
   23307 ** is held on the file and false if the file is unlocked.
   23308 */
   23309 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
   23310   int rc = SQLITE_OK;
   23311   int reserved = 0;
   23312   unixFile *pFile = (unixFile*)id;
   23313 
   23314   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   23315 
   23316   assert( pFile );
   23317 
   23318   /* Check if a thread in this process holds such a lock */
   23319   if( pFile->locktype>SHARED_LOCK ){
   23320     /* Either this connection or some other connection in the same process
   23321     ** holds a lock on the file.  No need to check further. */
   23322     reserved = 1;
   23323   }else{
   23324     /* The lock is held if and only if the lockfile exists */
   23325     const char *zLockFile = (const char*)pFile->lockingContext;
   23326     reserved = access(zLockFile, 0)==0;
   23327   }
   23328   OSTRACE4("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved);
   23329   *pResOut = reserved;
   23330   return rc;
   23331 }
   23332 
   23333 /*
   23334 ** Lock the file with the lock specified by parameter locktype - one
   23335 ** of the following:
   23336 **
   23337 **     (1) SHARED_LOCK
   23338 **     (2) RESERVED_LOCK
   23339 **     (3) PENDING_LOCK
   23340 **     (4) EXCLUSIVE_LOCK
   23341 **
   23342 ** Sometimes when requesting one lock state, additional lock states
   23343 ** are inserted in between.  The locking might fail on one of the later
   23344 ** transitions leaving the lock state different from what it started but
   23345 ** still short of its goal.  The following chart shows the allowed
   23346 ** transitions and the inserted intermediate states:
   23347 **
   23348 **    UNLOCKED -> SHARED
   23349 **    SHARED -> RESERVED
   23350 **    SHARED -> (PENDING) -> EXCLUSIVE
   23351 **    RESERVED -> (PENDING) -> EXCLUSIVE
   23352 **    PENDING -> EXCLUSIVE
   23353 **
   23354 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   23355 ** routine to lower a locking level.
   23356 **
   23357 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
   23358 ** But we track the other locking levels internally.
   23359 */
   23360 static int dotlockLock(sqlite3_file *id, int locktype) {
   23361   unixFile *pFile = (unixFile*)id;
   23362   int fd;
   23363   char *zLockFile = (char *)pFile->lockingContext;
   23364   int rc = SQLITE_OK;
   23365 
   23366 
   23367   /* If we have any lock, then the lock file already exists.  All we have
   23368   ** to do is adjust our internal record of the lock level.
   23369   */
   23370   if( pFile->locktype > NO_LOCK ){
   23371     pFile->locktype = locktype;
   23372 #if !OS_VXWORKS
   23373     /* Always update the timestamp on the old file */
   23374     utimes(zLockFile, NULL);
   23375 #endif
   23376     return SQLITE_OK;
   23377   }
   23378 
   23379   /* grab an exclusive lock */
   23380   fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
   23381   if( fd<0 ){
   23382     /* failed to open/create the file, someone else may have stolen the lock */
   23383     int tErrno = errno;
   23384     if( EEXIST == tErrno ){
   23385       rc = SQLITE_BUSY;
   23386     } else {
   23387       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   23388       if( IS_LOCK_ERROR(rc) ){
   23389         pFile->lastErrno = tErrno;
   23390       }
   23391     }
   23392     return rc;
   23393   }
   23394   if( close(fd) ){
   23395     pFile->lastErrno = errno;
   23396     rc = SQLITE_IOERR_CLOSE;
   23397   }
   23398 
   23399   /* got it, set the type and return ok */
   23400   pFile->locktype = locktype;
   23401   return rc;
   23402 }
   23403 
   23404 /*
   23405 ** Lower the locking level on file descriptor pFile to locktype.  locktype
   23406 ** must be either NO_LOCK or SHARED_LOCK.
   23407 **
   23408 ** If the locking level of the file descriptor is already at or below
   23409 ** the requested locking level, this routine is a no-op.
   23410 **
   23411 ** When the locking level reaches NO_LOCK, delete the lock file.
   23412 */
   23413 static int dotlockUnlock(sqlite3_file *id, int locktype) {
   23414   unixFile *pFile = (unixFile*)id;
   23415   char *zLockFile = (char *)pFile->lockingContext;
   23416 
   23417   assert( pFile );
   23418   OSTRACE5("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, locktype,
   23419 	   pFile->locktype, getpid());
   23420   assert( locktype<=SHARED_LOCK );
   23421 
   23422   /* no-op if possible */
   23423   if( pFile->locktype==locktype ){
   23424     return SQLITE_OK;
   23425   }
   23426 
   23427   /* To downgrade to shared, simply update our internal notion of the
   23428   ** lock state.  No need to mess with the file on disk.
   23429   */
   23430   if( locktype==SHARED_LOCK ){
   23431     pFile->locktype = SHARED_LOCK;
   23432     return SQLITE_OK;
   23433   }
   23434 
   23435   /* To fully unlock the database, delete the lock file */
   23436   assert( locktype==NO_LOCK );
   23437   if( unlink(zLockFile) ){
   23438     int rc = 0;
   23439     int tErrno = errno;
   23440     if( ENOENT != tErrno ){
   23441       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   23442     }
   23443     if( IS_LOCK_ERROR(rc) ){
   23444       pFile->lastErrno = tErrno;
   23445     }
   23446     return rc;
   23447   }
   23448   pFile->locktype = NO_LOCK;
   23449   return SQLITE_OK;
   23450 }
   23451 
   23452 /*
   23453 ** Close a file.  Make sure the lock has been released before closing.
   23454 */
   23455 static int dotlockClose(sqlite3_file *id) {
   23456   int rc;
   23457   if( id ){
   23458     unixFile *pFile = (unixFile*)id;
   23459     dotlockUnlock(id, NO_LOCK);
   23460     sqlite3_free(pFile->lockingContext);
   23461   }
   23462   rc = closeUnixFile(id);
   23463   return rc;
   23464 }
   23465 /****************** End of the dot-file lock implementation *******************
   23466 ******************************************************************************/
   23467 
   23468 /******************************************************************************
   23469 ************************** Begin flock Locking ********************************
   23470 **
   23471 ** Use the flock() system call to do file locking.
   23472 **
   23473 ** flock() locking is like dot-file locking in that the various
   23474 ** fine-grain locking levels supported by SQLite are collapsed into
   23475 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
   23476 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
   23477 ** still works when you do this, but concurrency is reduced since
   23478 ** only a single process can be reading the database at a time.
   23479 **
   23480 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
   23481 ** compiling for VXWORKS.
   23482 */
   23483 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
   23484 
   23485 /*
   23486 ** This routine checks if there is a RESERVED lock held on the specified
   23487 ** file by this or any other process. If such a lock is held, set *pResOut
   23488 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   23489 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   23490 */
   23491 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
   23492   int rc = SQLITE_OK;
   23493   int reserved = 0;
   23494   unixFile *pFile = (unixFile*)id;
   23495 
   23496   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   23497 
   23498   assert( pFile );
   23499 
   23500   /* Check if a thread in this process holds such a lock */
   23501   if( pFile->locktype>SHARED_LOCK ){
   23502     reserved = 1;
   23503   }
   23504 
   23505   /* Otherwise see if some other process holds it. */
   23506   if( !reserved ){
   23507     /* attempt to get the lock */
   23508     int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
   23509     if( !lrc ){
   23510       /* got the lock, unlock it */
   23511       lrc = flock(pFile->h, LOCK_UN);
   23512       if ( lrc ) {
   23513         int tErrno = errno;
   23514         /* unlock failed with an error */
   23515         lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   23516         if( IS_LOCK_ERROR(lrc) ){
   23517           pFile->lastErrno = tErrno;
   23518           rc = lrc;
   23519         }
   23520       }
   23521     } else {
   23522       int tErrno = errno;
   23523       reserved = 1;
   23524       /* someone else might have it reserved */
   23525       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   23526       if( IS_LOCK_ERROR(lrc) ){
   23527         pFile->lastErrno = tErrno;
   23528         rc = lrc;
   23529       }
   23530     }
   23531   }
   23532   OSTRACE4("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved);
   23533 
   23534 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   23535   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
   23536     rc = SQLITE_OK;
   23537     reserved=1;
   23538   }
   23539 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   23540   *pResOut = reserved;
   23541   return rc;
   23542 }
   23543 
   23544 /*
   23545 ** Lock the file with the lock specified by parameter locktype - one
   23546 ** of the following:
   23547 **
   23548 **     (1) SHARED_LOCK
   23549 **     (2) RESERVED_LOCK
   23550 **     (3) PENDING_LOCK
   23551 **     (4) EXCLUSIVE_LOCK
   23552 **
   23553 ** Sometimes when requesting one lock state, additional lock states
   23554 ** are inserted in between.  The locking might fail on one of the later
   23555 ** transitions leaving the lock state different from what it started but
   23556 ** still short of its goal.  The following chart shows the allowed
   23557 ** transitions and the inserted intermediate states:
   23558 **
   23559 **    UNLOCKED -> SHARED
   23560 **    SHARED -> RESERVED
   23561 **    SHARED -> (PENDING) -> EXCLUSIVE
   23562 **    RESERVED -> (PENDING) -> EXCLUSIVE
   23563 **    PENDING -> EXCLUSIVE
   23564 **
   23565 ** flock() only really support EXCLUSIVE locks.  We track intermediate
   23566 ** lock states in the sqlite3_file structure, but all locks SHARED or
   23567 ** above are really EXCLUSIVE locks and exclude all other processes from
   23568 ** access the file.
   23569 **
   23570 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   23571 ** routine to lower a locking level.
   23572 */
   23573 static int flockLock(sqlite3_file *id, int locktype) {
   23574   int rc = SQLITE_OK;
   23575   unixFile *pFile = (unixFile*)id;
   23576 
   23577   assert( pFile );
   23578 
   23579   /* if we already have a lock, it is exclusive.
   23580   ** Just adjust level and punt on outta here. */
   23581   if (pFile->locktype > NO_LOCK) {
   23582     pFile->locktype = locktype;
   23583     return SQLITE_OK;
   23584   }
   23585 
   23586   /* grab an exclusive lock */
   23587 
   23588   if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
   23589     int tErrno = errno;
   23590     /* didn't get, must be busy */
   23591     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   23592     if( IS_LOCK_ERROR(rc) ){
   23593       pFile->lastErrno = tErrno;
   23594     }
   23595   } else {
   23596     /* got it, set the type and return ok */
   23597     pFile->locktype = locktype;
   23598   }
   23599   OSTRACE4("LOCK    %d %s %s (flock)\n", pFile->h, locktypeName(locktype),
   23600            rc==SQLITE_OK ? "ok" : "failed");
   23601 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   23602   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
   23603     rc = SQLITE_BUSY;
   23604   }
   23605 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   23606   return rc;
   23607 }
   23608 
   23609 
   23610 /*
   23611 ** Lower the locking level on file descriptor pFile to locktype.  locktype
   23612 ** must be either NO_LOCK or SHARED_LOCK.
   23613 **
   23614 ** If the locking level of the file descriptor is already at or below
   23615 ** the requested locking level, this routine is a no-op.
   23616 */
   23617 static int flockUnlock(sqlite3_file *id, int locktype) {
   23618   unixFile *pFile = (unixFile*)id;
   23619 
   23620   assert( pFile );
   23621   OSTRACE5("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, locktype,
   23622            pFile->locktype, getpid());
   23623   assert( locktype<=SHARED_LOCK );
   23624 
   23625   /* no-op if possible */
   23626   if( pFile->locktype==locktype ){
   23627     return SQLITE_OK;
   23628   }
   23629 
   23630   /* shared can just be set because we always have an exclusive */
   23631   if (locktype==SHARED_LOCK) {
   23632     pFile->locktype = locktype;
   23633     return SQLITE_OK;
   23634   }
   23635 
   23636   /* no, really, unlock. */
   23637   int rc = flock(pFile->h, LOCK_UN);
   23638   if (rc) {
   23639     int r, tErrno = errno;
   23640     r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   23641     if( IS_LOCK_ERROR(r) ){
   23642       pFile->lastErrno = tErrno;
   23643     }
   23644 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   23645     if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
   23646       r = SQLITE_BUSY;
   23647     }
   23648 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   23649 
   23650     return r;
   23651   } else {
   23652     pFile->locktype = NO_LOCK;
   23653     return SQLITE_OK;
   23654   }
   23655 }
   23656 
   23657 /*
   23658 ** Close a file.
   23659 */
   23660 static int flockClose(sqlite3_file *id) {
   23661   if( id ){
   23662     flockUnlock(id, NO_LOCK);
   23663   }
   23664   return closeUnixFile(id);
   23665 }
   23666 
   23667 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
   23668 
   23669 /******************* End of the flock lock implementation *********************
   23670 ******************************************************************************/
   23671 
   23672 /******************************************************************************
   23673 ************************ Begin Named Semaphore Locking ************************
   23674 **
   23675 ** Named semaphore locking is only supported on VxWorks.
   23676 **
   23677 ** Semaphore locking is like dot-lock and flock in that it really only
   23678 ** supports EXCLUSIVE locking.  Only a single process can read or write
   23679 ** the database file at a time.  This reduces potential concurrency, but
   23680 ** makes the lock implementation much easier.
   23681 */
   23682 #if OS_VXWORKS
   23683 
   23684 /*
   23685 ** This routine checks if there is a RESERVED lock held on the specified
   23686 ** file by this or any other process. If such a lock is held, set *pResOut
   23687 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   23688 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   23689 */
   23690 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
   23691   int rc = SQLITE_OK;
   23692   int reserved = 0;
   23693   unixFile *pFile = (unixFile*)id;
   23694 
   23695   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   23696 
   23697   assert( pFile );
   23698 
   23699   /* Check if a thread in this process holds such a lock */
   23700   if( pFile->locktype>SHARED_LOCK ){
   23701     reserved = 1;
   23702   }
   23703 
   23704   /* Otherwise see if some other process holds it. */
   23705   if( !reserved ){
   23706     sem_t *pSem = pFile->pOpen->pSem;
   23707     struct stat statBuf;
   23708 
   23709     if( sem_trywait(pSem)==-1 ){
   23710       int tErrno = errno;
   23711       if( EAGAIN != tErrno ){
   23712         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
   23713         pFile->lastErrno = tErrno;
   23714       } else {
   23715         /* someone else has the lock when we are in NO_LOCK */
   23716         reserved = (pFile->locktype < SHARED_LOCK);
   23717       }
   23718     }else{
   23719       /* we could have it if we want it */
   23720       sem_post(pSem);
   23721     }
   23722   }
   23723   OSTRACE4("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved);
   23724 
   23725   *pResOut = reserved;
   23726   return rc;
   23727 }
   23728 
   23729 /*
   23730 ** Lock the file with the lock specified by parameter locktype - one
   23731 ** of the following:
   23732 **
   23733 **     (1) SHARED_LOCK
   23734 **     (2) RESERVED_LOCK
   23735 **     (3) PENDING_LOCK
   23736 **     (4) EXCLUSIVE_LOCK
   23737 **
   23738 ** Sometimes when requesting one lock state, additional lock states
   23739 ** are inserted in between.  The locking might fail on one of the later
   23740 ** transitions leaving the lock state different from what it started but
   23741 ** still short of its goal.  The following chart shows the allowed
   23742 ** transitions and the inserted intermediate states:
   23743 **
   23744 **    UNLOCKED -> SHARED
   23745 **    SHARED -> RESERVED
   23746 **    SHARED -> (PENDING) -> EXCLUSIVE
   23747 **    RESERVED -> (PENDING) -> EXCLUSIVE
   23748 **    PENDING -> EXCLUSIVE
   23749 **
   23750 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
   23751 ** lock states in the sqlite3_file structure, but all locks SHARED or
   23752 ** above are really EXCLUSIVE locks and exclude all other processes from
   23753 ** access the file.
   23754 **
   23755 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   23756 ** routine to lower a locking level.
   23757 */
   23758 static int semLock(sqlite3_file *id, int locktype) {
   23759   unixFile *pFile = (unixFile*)id;
   23760   int fd;
   23761   sem_t *pSem = pFile->pOpen->pSem;
   23762   int rc = SQLITE_OK;
   23763 
   23764   /* if we already have a lock, it is exclusive.
   23765   ** Just adjust level and punt on outta here. */
   23766   if (pFile->locktype > NO_LOCK) {
   23767     pFile->locktype = locktype;
   23768     rc = SQLITE_OK;
   23769     goto sem_end_lock;
   23770   }
   23771 
   23772   /* lock semaphore now but bail out when already locked. */
   23773   if( sem_trywait(pSem)==-1 ){
   23774     rc = SQLITE_BUSY;
   23775     goto sem_end_lock;
   23776   }
   23777 
   23778   /* got it, set the type and return ok */
   23779   pFile->locktype = locktype;
   23780 
   23781  sem_end_lock:
   23782   return rc;
   23783 }
   23784 
   23785 /*
   23786 ** Lower the locking level on file descriptor pFile to locktype.  locktype
   23787 ** must be either NO_LOCK or SHARED_LOCK.
   23788 **
   23789 ** If the locking level of the file descriptor is already at or below
   23790 ** the requested locking level, this routine is a no-op.
   23791 */
   23792 static int semUnlock(sqlite3_file *id, int locktype) {
   23793   unixFile *pFile = (unixFile*)id;
   23794   sem_t *pSem = pFile->pOpen->pSem;
   23795 
   23796   assert( pFile );
   23797   assert( pSem );
   23798   OSTRACE5("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, locktype,
   23799 	   pFile->locktype, getpid());
   23800   assert( locktype<=SHARED_LOCK );
   23801 
   23802   /* no-op if possible */
   23803   if( pFile->locktype==locktype ){
   23804     return SQLITE_OK;
   23805   }
   23806 
   23807   /* shared can just be set because we always have an exclusive */
   23808   if (locktype==SHARED_LOCK) {
   23809     pFile->locktype = locktype;
   23810     return SQLITE_OK;
   23811   }
   23812 
   23813   /* no, really unlock. */
   23814   if ( sem_post(pSem)==-1 ) {
   23815     int rc, tErrno = errno;
   23816     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   23817     if( IS_LOCK_ERROR(rc) ){
   23818       pFile->lastErrno = tErrno;
   23819     }
   23820     return rc;
   23821   }
   23822   pFile->locktype = NO_LOCK;
   23823   return SQLITE_OK;
   23824 }
   23825 
   23826 /*
   23827  ** Close a file.
   23828  */
   23829 static int semClose(sqlite3_file *id) {
   23830   if( id ){
   23831     unixFile *pFile = (unixFile*)id;
   23832     semUnlock(id, NO_LOCK);
   23833     assert( pFile );
   23834     unixEnterMutex();
   23835     releaseLockInfo(pFile->pLock);
   23836     releaseOpenCnt(pFile->pOpen);
   23837     unixLeaveMutex();
   23838     closeUnixFile(id);
   23839   }
   23840   return SQLITE_OK;
   23841 }
   23842 
   23843 #endif /* OS_VXWORKS */
   23844 /*
   23845 ** Named semaphore locking is only available on VxWorks.
   23846 **
   23847 *************** End of the named semaphore lock implementation ****************
   23848 ******************************************************************************/
   23849 
   23850 
   23851 /******************************************************************************
   23852 *************************** Begin AFP Locking *********************************
   23853 **
   23854 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
   23855 ** on Apple Macintosh computers - both OS9 and OSX.
   23856 **
   23857 ** Third-party implementations of AFP are available.  But this code here
   23858 ** only works on OSX.
   23859 */
   23860 
   23861 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   23862 /*
   23863 ** The afpLockingContext structure contains all afp lock specific state
   23864 */
   23865 typedef struct afpLockingContext afpLockingContext;
   23866 struct afpLockingContext {
   23867   unsigned long long sharedByte;
   23868   const char *dbPath;             /* Name of the open file */
   23869 };
   23870 
   23871 struct ByteRangeLockPB2
   23872 {
   23873   unsigned long long offset;        /* offset to first byte to lock */
   23874   unsigned long long length;        /* nbr of bytes to lock */
   23875   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
   23876   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
   23877   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
   23878   int fd;                           /* file desc to assoc this lock with */
   23879 };
   23880 
   23881 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
   23882 
   23883 /*
   23884 ** This is a utility for setting or clearing a bit-range lock on an
   23885 ** AFP filesystem.
   23886 **
   23887 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
   23888 */
   23889 static int afpSetLock(
   23890   const char *path,              /* Name of the file to be locked or unlocked */
   23891   unixFile *pFile,               /* Open file descriptor on path */
   23892   unsigned long long offset,     /* First byte to be locked */
   23893   unsigned long long length,     /* Number of bytes to lock */
   23894   int setLockFlag                /* True to set lock.  False to clear lock */
   23895 ){
   23896   struct ByteRangeLockPB2 pb;
   23897   int err;
   23898 
   23899   pb.unLockFlag = setLockFlag ? 0 : 1;
   23900   pb.startEndFlag = 0;
   23901   pb.offset = offset;
   23902   pb.length = length;
   23903   pb.fd = pFile->h;
   23904 
   23905   OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
   23906     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
   23907     offset, length);
   23908   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
   23909   if ( err==-1 ) {
   23910     int rc;
   23911     int tErrno = errno;
   23912     OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
   23913              path, tErrno, strerror(tErrno));
   23914 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
   23915     rc = SQLITE_BUSY;
   23916 #else
   23917     rc = sqliteErrorFromPosixError(tErrno,
   23918                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
   23919 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
   23920     if( IS_LOCK_ERROR(rc) ){
   23921       pFile->lastErrno = tErrno;
   23922     }
   23923     return rc;
   23924   } else {
   23925     return SQLITE_OK;
   23926   }
   23927 }
   23928 
   23929 /*
   23930 ** This routine checks if there is a RESERVED lock held on the specified
   23931 ** file by this or any other process. If such a lock is held, set *pResOut
   23932 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   23933 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   23934 */
   23935 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
   23936   int rc = SQLITE_OK;
   23937   int reserved = 0;
   23938   unixFile *pFile = (unixFile*)id;
   23939 
   23940   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   23941 
   23942   assert( pFile );
   23943   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   23944 
   23945   /* Check if a thread in this process holds such a lock */
   23946   if( pFile->locktype>SHARED_LOCK ){
   23947     reserved = 1;
   23948   }
   23949 
   23950   /* Otherwise see if some other process holds it.
   23951    */
   23952   if( !reserved ){
   23953     /* lock the RESERVED byte */
   23954     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
   23955     if( SQLITE_OK==lrc ){
   23956       /* if we succeeded in taking the reserved lock, unlock it to restore
   23957       ** the original state */
   23958       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
   23959     } else {
   23960       /* if we failed to get the lock then someone else must have it */
   23961       reserved = 1;
   23962     }
   23963     if( IS_LOCK_ERROR(lrc) ){
   23964       rc=lrc;
   23965     }
   23966   }
   23967 
   23968   OSTRACE4("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved);
   23969 
   23970   *pResOut = reserved;
   23971   return rc;
   23972 }
   23973 
   23974 /*
   23975 ** Lock the file with the lock specified by parameter locktype - one
   23976 ** of the following:
   23977 **
   23978 **     (1) SHARED_LOCK
   23979 **     (2) RESERVED_LOCK
   23980 **     (3) PENDING_LOCK
   23981 **     (4) EXCLUSIVE_LOCK
   23982 **
   23983 ** Sometimes when requesting one lock state, additional lock states
   23984 ** are inserted in between.  The locking might fail on one of the later
   23985 ** transitions leaving the lock state different from what it started but
   23986 ** still short of its goal.  The following chart shows the allowed
   23987 ** transitions and the inserted intermediate states:
   23988 **
   23989 **    UNLOCKED -> SHARED
   23990 **    SHARED -> RESERVED
   23991 **    SHARED -> (PENDING) -> EXCLUSIVE
   23992 **    RESERVED -> (PENDING) -> EXCLUSIVE
   23993 **    PENDING -> EXCLUSIVE
   23994 **
   23995 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   23996 ** routine to lower a locking level.
   23997 */
   23998 static int afpLock(sqlite3_file *id, int locktype){
   23999   int rc = SQLITE_OK;
   24000   unixFile *pFile = (unixFile*)id;
   24001   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   24002 
   24003   assert( pFile );
   24004   OSTRACE5("LOCK    %d %s was %s pid=%d (afp)\n", pFile->h,
   24005          locktypeName(locktype), locktypeName(pFile->locktype), getpid());
   24006 
   24007   /* If there is already a lock of this type or more restrictive on the
   24008   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
   24009   ** unixEnterMutex() hasn't been called yet.
   24010   */
   24011   if( pFile->locktype>=locktype ){
   24012     OSTRACE3("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
   24013            locktypeName(locktype));
   24014     return SQLITE_OK;
   24015   }
   24016 
   24017   /* Make sure the locking sequence is correct
   24018   */
   24019   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
   24020   assert( locktype!=PENDING_LOCK );
   24021   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
   24022 
   24023   /* This mutex is needed because pFile->pLock is shared across threads
   24024   */
   24025   unixEnterMutex();
   24026 
   24027   /* Make sure the current thread owns the pFile.
   24028   */
   24029   rc = transferOwnership(pFile);
   24030   if( rc!=SQLITE_OK ){
   24031     unixLeaveMutex();
   24032     return rc;
   24033   }
   24034 
   24035   /* A PENDING lock is needed before acquiring a SHARED lock and before
   24036   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   24037   ** be released.
   24038   */
   24039   if( locktype==SHARED_LOCK
   24040       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
   24041   ){
   24042     int failed;
   24043     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
   24044     if (failed) {
   24045       rc = failed;
   24046       goto afp_end_lock;
   24047     }
   24048   }
   24049 
   24050   /* If control gets to this point, then actually go ahead and make
   24051   ** operating system calls for the specified lock.
   24052   */
   24053   if( locktype==SHARED_LOCK ){
   24054     int lk, lrc1, lrc2;
   24055     int lrc1Errno = 0;
   24056 
   24057     /* Now get the read-lock SHARED_LOCK */
   24058     /* note that the quality of the randomness doesn't matter that much */
   24059     lk = random();
   24060     context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
   24061     lrc1 = afpSetLock(context->dbPath, pFile,
   24062           SHARED_FIRST+context->sharedByte, 1, 1);
   24063     if( IS_LOCK_ERROR(lrc1) ){
   24064       lrc1Errno = pFile->lastErrno;
   24065     }
   24066     /* Drop the temporary PENDING lock */
   24067     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
   24068 
   24069     if( IS_LOCK_ERROR(lrc1) ) {
   24070       pFile->lastErrno = lrc1Errno;
   24071       rc = lrc1;
   24072       goto afp_end_lock;
   24073     } else if( IS_LOCK_ERROR(lrc2) ){
   24074       rc = lrc2;
   24075       goto afp_end_lock;
   24076     } else if( lrc1 != SQLITE_OK ) {
   24077       rc = lrc1;
   24078     } else {
   24079       pFile->locktype = SHARED_LOCK;
   24080       pFile->pOpen->nLock++;
   24081     }
   24082   }else{
   24083     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
   24084     ** assumed that there is a SHARED or greater lock on the file
   24085     ** already.
   24086     */
   24087     int failed = 0;
   24088     assert( 0!=pFile->locktype );
   24089     if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
   24090         /* Acquire a RESERVED lock */
   24091         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
   24092     }
   24093     if (!failed && locktype == EXCLUSIVE_LOCK) {
   24094       /* Acquire an EXCLUSIVE lock */
   24095 
   24096       /* Remove the shared lock before trying the range.  we'll need to
   24097       ** reestablish the shared lock if we can't get the  afpUnlock
   24098       */
   24099       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
   24100                          context->sharedByte, 1, 0)) ){
   24101         int failed2 = SQLITE_OK;
   24102         /* now attemmpt to get the exclusive lock range */
   24103         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
   24104                                SHARED_SIZE, 1);
   24105         if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
   24106                        SHARED_FIRST + context->sharedByte, 1, 1)) ){
   24107           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
   24108           ** a critical I/O error
   24109           */
   24110           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
   24111                SQLITE_IOERR_LOCK;
   24112           goto afp_end_lock;
   24113         }
   24114       }else{
   24115         rc = failed;
   24116       }
   24117     }
   24118     if( failed ){
   24119       rc = failed;
   24120     }
   24121   }
   24122 
   24123   if( rc==SQLITE_OK ){
   24124     pFile->locktype = locktype;
   24125   }else if( locktype==EXCLUSIVE_LOCK ){
   24126     pFile->locktype = PENDING_LOCK;
   24127   }
   24128 
   24129 afp_end_lock:
   24130   unixLeaveMutex();
   24131   OSTRACE4("LOCK    %d %s %s (afp)\n", pFile->h, locktypeName(locktype),
   24132          rc==SQLITE_OK ? "ok" : "failed");
   24133   return rc;
   24134 }
   24135 
   24136 /*
   24137 ** Lower the locking level on file descriptor pFile to locktype.  locktype
   24138 ** must be either NO_LOCK or SHARED_LOCK.
   24139 **
   24140 ** If the locking level of the file descriptor is already at or below
   24141 ** the requested locking level, this routine is a no-op.
   24142 */
   24143 static int afpUnlock(sqlite3_file *id, int locktype) {
   24144   int rc = SQLITE_OK;
   24145   unixFile *pFile = (unixFile*)id;
   24146   afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
   24147 
   24148   assert( pFile );
   24149   OSTRACE5("UNLOCK  %d %d was %d pid=%d (afp)\n", pFile->h, locktype,
   24150          pFile->locktype, getpid());
   24151 
   24152   assert( locktype<=SHARED_LOCK );
   24153   if( pFile->locktype<=locktype ){
   24154     return SQLITE_OK;
   24155   }
   24156   if( CHECK_THREADID(pFile) ){
   24157     return SQLITE_MISUSE_BKPT;
   24158   }
   24159   unixEnterMutex();
   24160   if( pFile->locktype>SHARED_LOCK ){
   24161 
   24162     if( pFile->locktype==EXCLUSIVE_LOCK ){
   24163       rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
   24164       if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
   24165         /* only re-establish the shared lock if necessary */
   24166         int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
   24167         rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
   24168       }
   24169     }
   24170     if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
   24171       rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
   24172     }
   24173     if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
   24174       rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
   24175     }
   24176   }else if( locktype==NO_LOCK ){
   24177     /* clear the shared lock */
   24178     int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
   24179     rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
   24180   }
   24181 
   24182   if( rc==SQLITE_OK ){
   24183     if( locktype==NO_LOCK ){
   24184       struct unixOpenCnt *pOpen = pFile->pOpen;
   24185       pOpen->nLock--;
   24186       assert( pOpen->nLock>=0 );
   24187       if( pOpen->nLock==0 ){
   24188         rc = closePendingFds(pFile);
   24189       }
   24190     }
   24191   }
   24192   unixLeaveMutex();
   24193   if( rc==SQLITE_OK ){
   24194     pFile->locktype = locktype;
   24195   }
   24196   return rc;
   24197 }
   24198 
   24199 /*
   24200 ** Close a file & cleanup AFP specific locking context
   24201 */
   24202 static int afpClose(sqlite3_file *id) {
   24203   if( id ){
   24204     unixFile *pFile = (unixFile*)id;
   24205     afpUnlock(id, NO_LOCK);
   24206     unixEnterMutex();
   24207     if( pFile->pOpen && pFile->pOpen->nLock ){
   24208       /* If there are outstanding locks, do not actually close the file just
   24209       ** yet because that would clear those locks.  Instead, add the file
   24210       ** descriptor to pOpen->aPending.  It will be automatically closed when
   24211       ** the last lock is cleared.
   24212       */
   24213       setPendingFd(pFile);
   24214     }
   24215     releaseOpenCnt(pFile->pOpen);
   24216     sqlite3_free(pFile->lockingContext);
   24217     closeUnixFile(id);
   24218     unixLeaveMutex();
   24219   }
   24220   return SQLITE_OK;
   24221 }
   24222 
   24223 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   24224 /*
   24225 ** The code above is the AFP lock implementation.  The code is specific
   24226 ** to MacOSX and does not work on other unix platforms.  No alternative
   24227 ** is available.  If you don't compile for a mac, then the "unix-afp"
   24228 ** VFS is not available.
   24229 **
   24230 ********************* End of the AFP lock implementation **********************
   24231 ******************************************************************************/
   24232 
   24233 
   24234 /******************************************************************************
   24235 **************** Non-locking sqlite3_file methods *****************************
   24236 **
   24237 ** The next division contains implementations for all methods of the
   24238 ** sqlite3_file object other than the locking methods.  The locking
   24239 ** methods were defined in divisions above (one locking method per
   24240 ** division).  Those methods that are common to all locking modes
   24241 ** are gather together into this division.
   24242 */
   24243 
   24244 /*
   24245 ** Seek to the offset passed as the second argument, then read cnt
   24246 ** bytes into pBuf. Return the number of bytes actually read.
   24247 **
   24248 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
   24249 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
   24250 ** one system to another.  Since SQLite does not define USE_PREAD
   24251 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
   24252 ** See tickets #2741 and #2681.
   24253 **
   24254 ** To avoid stomping the errno value on a failed read the lastErrno value
   24255 ** is set before returning.
   24256 */
   24257 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
   24258   int got;
   24259   i64 newOffset;
   24260   TIMER_START;
   24261 #if defined(USE_PREAD)
   24262   got = pread(id->h, pBuf, cnt, offset);
   24263   SimulateIOError( got = -1 );
   24264 #elif defined(USE_PREAD64)
   24265   got = pread64(id->h, pBuf, cnt, offset);
   24266   SimulateIOError( got = -1 );
   24267 #else
   24268   newOffset = lseek(id->h, offset, SEEK_SET);
   24269   SimulateIOError( newOffset-- );
   24270   if( newOffset!=offset ){
   24271     if( newOffset == -1 ){
   24272       ((unixFile*)id)->lastErrno = errno;
   24273     }else{
   24274       ((unixFile*)id)->lastErrno = 0;
   24275     }
   24276     return -1;
   24277   }
   24278   got = read(id->h, pBuf, cnt);
   24279 #endif
   24280   TIMER_END;
   24281   if( got<0 ){
   24282     ((unixFile*)id)->lastErrno = errno;
   24283   }
   24284   OSTRACE5("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
   24285   return got;
   24286 }
   24287 
   24288 /*
   24289 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   24290 ** bytes were read successfully and SQLITE_IOERR if anything goes
   24291 ** wrong.
   24292 */
   24293 static int unixRead(
   24294   sqlite3_file *id,
   24295   void *pBuf,
   24296   int amt,
   24297   sqlite3_int64 offset
   24298 ){
   24299   unixFile *pFile = (unixFile *)id;
   24300   int got;
   24301   assert( id );
   24302 
   24303   /* If this is a database file (not a journal, master-journal or temp
   24304   ** file), the bytes in the locking range should never be read or written. */
   24305   assert( pFile->pUnused==0
   24306        || offset>=PENDING_BYTE+512
   24307        || offset+amt<=PENDING_BYTE
   24308   );
   24309 
   24310   got = seekAndRead(pFile, offset, pBuf, amt);
   24311   if( got==amt ){
   24312     return SQLITE_OK;
   24313   }else if( got<0 ){
   24314     /* lastErrno set by seekAndRead */
   24315     return SQLITE_IOERR_READ;
   24316   }else{
   24317     pFile->lastErrno = 0; /* not a system error */
   24318     /* Unread parts of the buffer must be zero-filled */
   24319     memset(&((char*)pBuf)[got], 0, amt-got);
   24320     return SQLITE_IOERR_SHORT_READ;
   24321   }
   24322 }
   24323 
   24324 /*
   24325 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
   24326 ** Return the number of bytes actually read.  Update the offset.
   24327 **
   24328 ** To avoid stomping the errno value on a failed write the lastErrno value
   24329 ** is set before returning.
   24330 */
   24331 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
   24332   int got;
   24333   i64 newOffset;
   24334   TIMER_START;
   24335 #if defined(USE_PREAD)
   24336   got = pwrite(id->h, pBuf, cnt, offset);
   24337 #elif defined(USE_PREAD64)
   24338   got = pwrite64(id->h, pBuf, cnt, offset);
   24339 #else
   24340   newOffset = lseek(id->h, offset, SEEK_SET);
   24341   if( newOffset!=offset ){
   24342     if( newOffset == -1 ){
   24343       ((unixFile*)id)->lastErrno = errno;
   24344     }else{
   24345       ((unixFile*)id)->lastErrno = 0;
   24346     }
   24347     return -1;
   24348   }
   24349   got = write(id->h, pBuf, cnt);
   24350 #endif
   24351   TIMER_END;
   24352   if( got<0 ){
   24353     ((unixFile*)id)->lastErrno = errno;
   24354   }
   24355 
   24356   OSTRACE5("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
   24357   return got;
   24358 }
   24359 
   24360 
   24361 /*
   24362 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   24363 ** or some other error code on failure.
   24364 */
   24365 static int unixWrite(
   24366   sqlite3_file *id,
   24367   const void *pBuf,
   24368   int amt,
   24369   sqlite3_int64 offset
   24370 ){
   24371   unixFile *pFile = (unixFile*)id;
   24372   int wrote = 0;
   24373   assert( id );
   24374   assert( amt>0 );
   24375 
   24376   /* If this is a database file (not a journal, master-journal or temp
   24377   ** file), the bytes in the locking range should never be read or written. */
   24378   assert( pFile->pUnused==0
   24379        || offset>=PENDING_BYTE+512
   24380        || offset+amt<=PENDING_BYTE
   24381   );
   24382 
   24383 #ifndef NDEBUG
   24384   /* If we are doing a normal write to a database file (as opposed to
   24385   ** doing a hot-journal rollback or a write to some file other than a
   24386   ** normal database file) then record the fact that the database
   24387   ** has changed.  If the transaction counter is modified, record that
   24388   ** fact too.
   24389   */
   24390   if( pFile->inNormalWrite ){
   24391     pFile->dbUpdate = 1;  /* The database has been modified */
   24392     if( offset<=24 && offset+amt>=27 ){
   24393       int rc;
   24394       char oldCntr[4];
   24395       SimulateIOErrorBenign(1);
   24396       rc = seekAndRead(pFile, 24, oldCntr, 4);
   24397       SimulateIOErrorBenign(0);
   24398       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
   24399         pFile->transCntrChng = 1;  /* The transaction counter has changed */
   24400       }
   24401     }
   24402   }
   24403 #endif
   24404 
   24405   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
   24406     amt -= wrote;
   24407     offset += wrote;
   24408     pBuf = &((char*)pBuf)[wrote];
   24409   }
   24410   SimulateIOError(( wrote=(-1), amt=1 ));
   24411   SimulateDiskfullError(( wrote=0, amt=1 ));
   24412   if( amt>0 ){
   24413     if( wrote<0 ){
   24414       /* lastErrno set by seekAndWrite */
   24415       return SQLITE_IOERR_WRITE;
   24416     }else{
   24417       pFile->lastErrno = 0; /* not a system error */
   24418       return SQLITE_FULL;
   24419     }
   24420   }
   24421   return SQLITE_OK;
   24422 }
   24423 
   24424 #ifdef SQLITE_TEST
   24425 /*
   24426 ** Count the number of fullsyncs and normal syncs.  This is used to test
   24427 ** that syncs and fullsyncs are occurring at the right times.
   24428 */
   24429 SQLITE_API int sqlite3_sync_count = 0;
   24430 SQLITE_API int sqlite3_fullsync_count = 0;
   24431 #endif
   24432 
   24433 /*
   24434 ** We do not trust systems to provide a working fdatasync().  Some do.
   24435 ** Others do no.  To be safe, we will stick with the (slower) fsync().
   24436 ** If you know that your system does support fdatasync() correctly,
   24437 ** then simply compile with -Dfdatasync=fdatasync
   24438 */
   24439 #if !defined(fdatasync) && !defined(__linux__)
   24440 # define fdatasync fsync
   24441 #endif
   24442 
   24443 /*
   24444 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
   24445 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
   24446 ** only available on Mac OS X.  But that could change.
   24447 */
   24448 #ifdef F_FULLFSYNC
   24449 # define HAVE_FULLFSYNC 1
   24450 #else
   24451 # define HAVE_FULLFSYNC 0
   24452 #endif
   24453 
   24454 
   24455 /*
   24456 ** The fsync() system call does not work as advertised on many
   24457 ** unix systems.  The following procedure is an attempt to make
   24458 ** it work better.
   24459 **
   24460 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
   24461 ** for testing when we want to run through the test suite quickly.
   24462 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
   24463 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
   24464 ** or power failure will likely corrupt the database file.
   24465 **
   24466 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
   24467 ** The idea behind dataOnly is that it should only write the file content
   24468 ** to disk, not the inode.  We only set dataOnly if the file size is
   24469 ** unchanged since the file size is part of the inode.  However,
   24470 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
   24471 ** file size has changed.  The only real difference between fdatasync()
   24472 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
   24473 ** inode if the mtime or owner or other inode attributes have changed.
   24474 ** We only care about the file size, not the other file attributes, so
   24475 ** as far as SQLite is concerned, an fdatasync() is always adequate.
   24476 ** So, we always use fdatasync() if it is available, regardless of
   24477 ** the value of the dataOnly flag.
   24478 */
   24479 static int full_fsync(int fd, int fullSync, int dataOnly){
   24480   int rc;
   24481 
   24482   /* The following "ifdef/elif/else/" block has the same structure as
   24483   ** the one below. It is replicated here solely to avoid cluttering
   24484   ** up the real code with the UNUSED_PARAMETER() macros.
   24485   */
   24486 #ifdef SQLITE_NO_SYNC
   24487   UNUSED_PARAMETER(fd);
   24488   UNUSED_PARAMETER(fullSync);
   24489   UNUSED_PARAMETER(dataOnly);
   24490 #elif HAVE_FULLFSYNC
   24491   UNUSED_PARAMETER(dataOnly);
   24492 #else
   24493   UNUSED_PARAMETER(fullSync);
   24494   UNUSED_PARAMETER(dataOnly);
   24495 #endif
   24496 
   24497   /* Record the number of times that we do a normal fsync() and
   24498   ** FULLSYNC.  This is used during testing to verify that this procedure
   24499   ** gets called with the correct arguments.
   24500   */
   24501 #ifdef SQLITE_TEST
   24502   if( fullSync ) sqlite3_fullsync_count++;
   24503   sqlite3_sync_count++;
   24504 #endif
   24505 
   24506   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   24507   ** no-op
   24508   */
   24509 #ifdef SQLITE_NO_SYNC
   24510   rc = SQLITE_OK;
   24511 #elif HAVE_FULLFSYNC
   24512   if( fullSync ){
   24513     rc = fcntl(fd, F_FULLFSYNC, 0);
   24514   }else{
   24515     rc = 1;
   24516   }
   24517   /* If the FULLFSYNC failed, fall back to attempting an fsync().
   24518   ** It shouldn't be possible for fullfsync to fail on the local
   24519   ** file system (on OSX), so failure indicates that FULLFSYNC
   24520   ** isn't supported for this file system. So, attempt an fsync
   24521   ** and (for now) ignore the overhead of a superfluous fcntl call.
   24522   ** It'd be better to detect fullfsync support once and avoid
   24523   ** the fcntl call every time sync is called.
   24524   */
   24525   if( rc ) rc = fsync(fd);
   24526 
   24527 #else
   24528   rc = fdatasync(fd);
   24529 #if OS_VXWORKS
   24530   if( rc==-1 && errno==ENOTSUP ){
   24531     rc = fsync(fd);
   24532   }
   24533 #endif /* OS_VXWORKS */
   24534 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
   24535 
   24536   if( OS_VXWORKS && rc!= -1 ){
   24537     rc = 0;
   24538   }
   24539   return rc;
   24540 }
   24541 
   24542 /*
   24543 ** Make sure all writes to a particular file are committed to disk.
   24544 **
   24545 ** If dataOnly==0 then both the file itself and its metadata (file
   24546 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
   24547 ** file data is synced.
   24548 **
   24549 ** Under Unix, also make sure that the directory entry for the file
   24550 ** has been created by fsync-ing the directory that contains the file.
   24551 ** If we do not do this and we encounter a power failure, the directory
   24552 ** entry for the journal might not exist after we reboot.  The next
   24553 ** SQLite to access the file will not know that the journal exists (because
   24554 ** the directory entry for the journal was never created) and the transaction
   24555 ** will not roll back - possibly leading to database corruption.
   24556 */
   24557 static int unixSync(sqlite3_file *id, int flags){
   24558   int rc;
   24559   unixFile *pFile = (unixFile*)id;
   24560 
   24561   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
   24562   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
   24563 
   24564   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
   24565   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
   24566       || (flags&0x0F)==SQLITE_SYNC_FULL
   24567   );
   24568 
   24569   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
   24570   ** line is to test that doing so does not cause any problems.
   24571   */
   24572   SimulateDiskfullError( return SQLITE_FULL );
   24573 
   24574   assert( pFile );
   24575   OSTRACE2("SYNC    %-3d\n", pFile->h);
   24576   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
   24577   SimulateIOError( rc=1 );
   24578   if( rc ){
   24579     pFile->lastErrno = errno;
   24580     return SQLITE_IOERR_FSYNC;
   24581   }
   24582   if( pFile->dirfd>=0 ){
   24583     int err;
   24584     OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
   24585             HAVE_FULLFSYNC, isFullsync);
   24586 #ifndef SQLITE_DISABLE_DIRSYNC
   24587     /* The directory sync is only attempted if full_fsync is
   24588     ** turned off or unavailable.  If a full_fsync occurred above,
   24589     ** then the directory sync is superfluous.
   24590     */
   24591     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
   24592        /*
   24593        ** We have received multiple reports of fsync() returning
   24594        ** errors when applied to directories on certain file systems.
   24595        ** A failed directory sync is not a big deal.  So it seems
   24596        ** better to ignore the error.  Ticket #1657
   24597        */
   24598        /* pFile->lastErrno = errno; */
   24599        /* return SQLITE_IOERR; */
   24600     }
   24601 #endif
   24602     err = close(pFile->dirfd); /* Only need to sync once, so close the */
   24603     if( err==0 ){              /* directory when we are done */
   24604       pFile->dirfd = -1;
   24605     }else{
   24606       pFile->lastErrno = errno;
   24607       rc = SQLITE_IOERR_DIR_CLOSE;
   24608     }
   24609   }
   24610   return rc;
   24611 }
   24612 
   24613 /*
   24614 ** Truncate an open file to a specified size
   24615 */
   24616 static int unixTruncate(sqlite3_file *id, i64 nByte){
   24617   int rc;
   24618   assert( id );
   24619   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
   24620   rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
   24621   if( rc ){
   24622     ((unixFile*)id)->lastErrno = errno;
   24623     return SQLITE_IOERR_TRUNCATE;
   24624   }else{
   24625 #ifndef NDEBUG
   24626     /* If we are doing a normal write to a database file (as opposed to
   24627     ** doing a hot-journal rollback or a write to some file other than a
   24628     ** normal database file) and we truncate the file to zero length,
   24629     ** that effectively updates the change counter.  This might happen
   24630     ** when restoring a database using the backup API from a zero-length
   24631     ** source.
   24632     */
   24633     if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
   24634       ((unixFile*)id)->transCntrChng = 1;
   24635     }
   24636 #endif
   24637 
   24638     return SQLITE_OK;
   24639   }
   24640 }
   24641 
   24642 /*
   24643 ** Determine the current size of a file in bytes
   24644 */
   24645 static int unixFileSize(sqlite3_file *id, i64 *pSize){
   24646   int rc;
   24647   struct stat buf;
   24648   assert( id );
   24649   rc = fstat(((unixFile*)id)->h, &buf);
   24650   SimulateIOError( rc=1 );
   24651   if( rc!=0 ){
   24652     ((unixFile*)id)->lastErrno = errno;
   24653     return SQLITE_IOERR_FSTAT;
   24654   }
   24655   *pSize = buf.st_size;
   24656 
   24657   /* When opening a zero-size database, the findLockInfo() procedure
   24658   ** writes a single byte into that file in order to work around a bug
   24659   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
   24660   ** layers, we need to report this file size as zero even though it is
   24661   ** really 1.   Ticket #3260.
   24662   */
   24663   if( *pSize==1 ) *pSize = 0;
   24664 
   24665 
   24666   return SQLITE_OK;
   24667 }
   24668 
   24669 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   24670 /*
   24671 ** Handler for proxy-locking file-control verbs.  Defined below in the
   24672 ** proxying locking division.
   24673 */
   24674 static int proxyFileControl(sqlite3_file*,int,void*);
   24675 #endif
   24676 
   24677 
   24678 /*
   24679 ** Information and control of an open file handle.
   24680 */
   24681 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
   24682   switch( op ){
   24683     case SQLITE_FCNTL_LOCKSTATE: {
   24684       *(int*)pArg = ((unixFile*)id)->locktype;
   24685       return SQLITE_OK;
   24686     }
   24687     case SQLITE_LAST_ERRNO: {
   24688       *(int*)pArg = ((unixFile*)id)->lastErrno;
   24689       return SQLITE_OK;
   24690     }
   24691 #ifndef NDEBUG
   24692     /* The pager calls this method to signal that it has done
   24693     ** a rollback and that the database is therefore unchanged and
   24694     ** it hence it is OK for the transaction change counter to be
   24695     ** unchanged.
   24696     */
   24697     case SQLITE_FCNTL_DB_UNCHANGED: {
   24698       ((unixFile*)id)->dbUpdate = 0;
   24699       return SQLITE_OK;
   24700     }
   24701 #endif
   24702 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   24703     case SQLITE_SET_LOCKPROXYFILE:
   24704     case SQLITE_GET_LOCKPROXYFILE: {
   24705       return proxyFileControl(id,op,pArg);
   24706     }
   24707 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
   24708   }
   24709   return SQLITE_ERROR;
   24710 }
   24711 
   24712 /*
   24713 ** Return the sector size in bytes of the underlying block device for
   24714 ** the specified file. This is almost always 512 bytes, but may be
   24715 ** larger for some devices.
   24716 **
   24717 ** SQLite code assumes this function cannot fail. It also assumes that
   24718 ** if two files are created in the same file-system directory (i.e.
   24719 ** a database and its journal file) that the sector size will be the
   24720 ** same for both.
   24721 */
   24722 static int unixSectorSize(sqlite3_file *NotUsed){
   24723   UNUSED_PARAMETER(NotUsed);
   24724   return SQLITE_DEFAULT_SECTOR_SIZE;
   24725 }
   24726 
   24727 /*
   24728 ** Return the device characteristics for the file. This is always 0 for unix.
   24729 */
   24730 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
   24731   UNUSED_PARAMETER(NotUsed);
   24732   return 0;
   24733 }
   24734 
   24735 /*
   24736 ** Here ends the implementation of all sqlite3_file methods.
   24737 **
   24738 ********************** End sqlite3_file Methods *******************************
   24739 ******************************************************************************/
   24740 
   24741 /*
   24742 ** This division contains definitions of sqlite3_io_methods objects that
   24743 ** implement various file locking strategies.  It also contains definitions
   24744 ** of "finder" functions.  A finder-function is used to locate the appropriate
   24745 ** sqlite3_io_methods object for a particular database file.  The pAppData
   24746 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
   24747 ** the correct finder-function for that VFS.
   24748 **
   24749 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
   24750 ** object.  The only interesting finder-function is autolockIoFinder, which
   24751 ** looks at the filesystem type and tries to guess the best locking
   24752 ** strategy from that.
   24753 **
   24754 ** For finder-funtion F, two objects are created:
   24755 **
   24756 **    (1) The real finder-function named "FImpt()".
   24757 **
   24758 **    (2) A constant pointer to this function named just "F".
   24759 **
   24760 **
   24761 ** A pointer to the F pointer is used as the pAppData value for VFS
   24762 ** objects.  We have to do this instead of letting pAppData point
   24763 ** directly at the finder-function since C90 rules prevent a void*
   24764 ** from be cast into a function pointer.
   24765 **
   24766 **
   24767 ** Each instance of this macro generates two objects:
   24768 **
   24769 **   *  A constant sqlite3_io_methods object call METHOD that has locking
   24770 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
   24771 **
   24772 **   *  An I/O method finder function called FINDER that returns a pointer
   24773 **      to the METHOD object in the previous bullet.
   24774 */
   24775 #define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK)               \
   24776 static const sqlite3_io_methods METHOD = {                                   \
   24777    1,                          /* iVersion */                                \
   24778    CLOSE,                      /* xClose */                                  \
   24779    unixRead,                   /* xRead */                                   \
   24780    unixWrite,                  /* xWrite */                                  \
   24781    unixTruncate,               /* xTruncate */                               \
   24782    unixSync,                   /* xSync */                                   \
   24783    unixFileSize,               /* xFileSize */                               \
   24784    LOCK,                       /* xLock */                                   \
   24785    UNLOCK,                     /* xUnlock */                                 \
   24786    CKLOCK,                     /* xCheckReservedLock */                      \
   24787    unixFileControl,            /* xFileControl */                            \
   24788    unixSectorSize,             /* xSectorSize */                             \
   24789    unixDeviceCharacteristics   /* xDeviceCapabilities */                     \
   24790 };                                                                           \
   24791 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
   24792   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
   24793   return &METHOD;                                                            \
   24794 }                                                                            \
   24795 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
   24796     = FINDER##Impl;
   24797 
   24798 /*
   24799 ** Here are all of the sqlite3_io_methods objects for each of the
   24800 ** locking strategies.  Functions that return pointers to these methods
   24801 ** are also created.
   24802 */
   24803 IOMETHODS(
   24804   posixIoFinder,            /* Finder function name */
   24805   posixIoMethods,           /* sqlite3_io_methods object name */
   24806   unixClose,                /* xClose method */
   24807   unixLock,                 /* xLock method */
   24808   unixUnlock,               /* xUnlock method */
   24809   unixCheckReservedLock     /* xCheckReservedLock method */
   24810 )
   24811 IOMETHODS(
   24812   nolockIoFinder,           /* Finder function name */
   24813   nolockIoMethods,          /* sqlite3_io_methods object name */
   24814   nolockClose,              /* xClose method */
   24815   nolockLock,               /* xLock method */
   24816   nolockUnlock,             /* xUnlock method */
   24817   nolockCheckReservedLock   /* xCheckReservedLock method */
   24818 )
   24819 IOMETHODS(
   24820   dotlockIoFinder,          /* Finder function name */
   24821   dotlockIoMethods,         /* sqlite3_io_methods object name */
   24822   dotlockClose,             /* xClose method */
   24823   dotlockLock,              /* xLock method */
   24824   dotlockUnlock,            /* xUnlock method */
   24825   dotlockCheckReservedLock  /* xCheckReservedLock method */
   24826 )
   24827 
   24828 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
   24829 IOMETHODS(
   24830   flockIoFinder,            /* Finder function name */
   24831   flockIoMethods,           /* sqlite3_io_methods object name */
   24832   flockClose,               /* xClose method */
   24833   flockLock,                /* xLock method */
   24834   flockUnlock,              /* xUnlock method */
   24835   flockCheckReservedLock    /* xCheckReservedLock method */
   24836 )
   24837 #endif
   24838 
   24839 #if OS_VXWORKS
   24840 IOMETHODS(
   24841   semIoFinder,              /* Finder function name */
   24842   semIoMethods,             /* sqlite3_io_methods object name */
   24843   semClose,                 /* xClose method */
   24844   semLock,                  /* xLock method */
   24845   semUnlock,                /* xUnlock method */
   24846   semCheckReservedLock      /* xCheckReservedLock method */
   24847 )
   24848 #endif
   24849 
   24850 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   24851 IOMETHODS(
   24852   afpIoFinder,              /* Finder function name */
   24853   afpIoMethods,             /* sqlite3_io_methods object name */
   24854   afpClose,                 /* xClose method */
   24855   afpLock,                  /* xLock method */
   24856   afpUnlock,                /* xUnlock method */
   24857   afpCheckReservedLock      /* xCheckReservedLock method */
   24858 )
   24859 #endif
   24860 
   24861 /*
   24862 ** The "Whole File Locking" finder returns the same set of methods as
   24863 ** the posix locking finder.  But it also sets the SQLITE_WHOLE_FILE_LOCKING
   24864 ** flag to force the posix advisory locks to cover the whole file instead
   24865 ** of just a small span of bytes near the 1GiB boundary.  Whole File Locking
   24866 ** is useful on NFS-mounted files since it helps NFS to maintain cache
   24867 ** coherency.  But it is a detriment to other filesystems since it runs
   24868 ** slower.
   24869 */
   24870 static const sqlite3_io_methods *posixWflIoFinderImpl(const char*z, unixFile*p){
   24871   UNUSED_PARAMETER(z);
   24872   p->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
   24873   return &posixIoMethods;
   24874 }
   24875 static const sqlite3_io_methods
   24876   *(*const posixWflIoFinder)(const char*,unixFile *p) = posixWflIoFinderImpl;
   24877 
   24878 /*
   24879 ** The proxy locking method is a "super-method" in the sense that it
   24880 ** opens secondary file descriptors for the conch and lock files and
   24881 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
   24882 ** secondary files.  For this reason, the division that implements
   24883 ** proxy locking is located much further down in the file.  But we need
   24884 ** to go ahead and define the sqlite3_io_methods and finder function
   24885 ** for proxy locking here.  So we forward declare the I/O methods.
   24886 */
   24887 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   24888 static int proxyClose(sqlite3_file*);
   24889 static int proxyLock(sqlite3_file*, int);
   24890 static int proxyUnlock(sqlite3_file*, int);
   24891 static int proxyCheckReservedLock(sqlite3_file*, int*);
   24892 IOMETHODS(
   24893   proxyIoFinder,            /* Finder function name */
   24894   proxyIoMethods,           /* sqlite3_io_methods object name */
   24895   proxyClose,               /* xClose method */
   24896   proxyLock,                /* xLock method */
   24897   proxyUnlock,              /* xUnlock method */
   24898   proxyCheckReservedLock    /* xCheckReservedLock method */
   24899 )
   24900 #endif
   24901 
   24902 
   24903 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   24904 /*
   24905 ** This "finder" function attempts to determine the best locking strategy
   24906 ** for the database file "filePath".  It then returns the sqlite3_io_methods
   24907 ** object that implements that strategy.
   24908 **
   24909 ** This is for MacOSX only.
   24910 */
   24911 static const sqlite3_io_methods *autolockIoFinderImpl(
   24912   const char *filePath,    /* name of the database file */
   24913   unixFile *pNew           /* open file object for the database file */
   24914 ){
   24915   static const struct Mapping {
   24916     const char *zFilesystem;              /* Filesystem type name */
   24917     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
   24918   } aMap[] = {
   24919     { "hfs",    &posixIoMethods },
   24920     { "ufs",    &posixIoMethods },
   24921     { "afpfs",  &afpIoMethods },
   24922 #ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
   24923     { "smbfs",  &afpIoMethods },
   24924 #else
   24925     { "smbfs",  &flockIoMethods },
   24926 #endif
   24927     { "webdav", &nolockIoMethods },
   24928     { 0, 0 }
   24929   };
   24930   int i;
   24931   struct statfs fsInfo;
   24932   struct flock lockInfo;
   24933 
   24934   if( !filePath ){
   24935     /* If filePath==NULL that means we are dealing with a transient file
   24936     ** that does not need to be locked. */
   24937     return &nolockIoMethods;
   24938   }
   24939   if( statfs(filePath, &fsInfo) != -1 ){
   24940     if( fsInfo.f_flags & MNT_RDONLY ){
   24941       return &nolockIoMethods;
   24942     }
   24943     for(i=0; aMap[i].zFilesystem; i++){
   24944       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
   24945         return aMap[i].pMethods;
   24946       }
   24947     }
   24948   }
   24949 
   24950   /* Default case. Handles, amongst others, "nfs".
   24951   ** Test byte-range lock using fcntl(). If the call succeeds,
   24952   ** assume that the file-system supports POSIX style locks.
   24953   */
   24954   lockInfo.l_len = 1;
   24955   lockInfo.l_start = 0;
   24956   lockInfo.l_whence = SEEK_SET;
   24957   lockInfo.l_type = F_RDLCK;
   24958   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
   24959     pNew->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
   24960     return &posixIoMethods;
   24961   }else{
   24962     return &dotlockIoMethods;
   24963   }
   24964 }
   24965 static const sqlite3_io_methods
   24966   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
   24967 
   24968 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   24969 
   24970 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
   24971 /*
   24972 ** This "finder" function attempts to determine the best locking strategy
   24973 ** for the database file "filePath".  It then returns the sqlite3_io_methods
   24974 ** object that implements that strategy.
   24975 **
   24976 ** This is for VXWorks only.
   24977 */
   24978 static const sqlite3_io_methods *autolockIoFinderImpl(
   24979   const char *filePath,    /* name of the database file */
   24980   unixFile *pNew           /* the open file object */
   24981 ){
   24982   struct flock lockInfo;
   24983 
   24984   if( !filePath ){
   24985     /* If filePath==NULL that means we are dealing with a transient file
   24986     ** that does not need to be locked. */
   24987     return &nolockIoMethods;
   24988   }
   24989 
   24990   /* Test if fcntl() is supported and use POSIX style locks.
   24991   ** Otherwise fall back to the named semaphore method.
   24992   */
   24993   lockInfo.l_len = 1;
   24994   lockInfo.l_start = 0;
   24995   lockInfo.l_whence = SEEK_SET;
   24996   lockInfo.l_type = F_RDLCK;
   24997   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
   24998     return &posixIoMethods;
   24999   }else{
   25000     return &semIoMethods;
   25001   }
   25002 }
   25003 static const sqlite3_io_methods
   25004   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
   25005 
   25006 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
   25007 
   25008 /*
   25009 ** An abstract type for a pointer to a IO method finder function:
   25010 */
   25011 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
   25012 
   25013 
   25014 /****************************************************************************
   25015 **************************** sqlite3_vfs methods ****************************
   25016 **
   25017 ** This division contains the implementation of methods on the
   25018 ** sqlite3_vfs object.
   25019 */
   25020 
   25021 /*
   25022 ** Initialize the contents of the unixFile structure pointed to by pId.
   25023 */
   25024 static int fillInUnixFile(
   25025   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
   25026   int h,                  /* Open file descriptor of file being opened */
   25027   int dirfd,              /* Directory file descriptor */
   25028   sqlite3_file *pId,      /* Write to the unixFile structure here */
   25029   const char *zFilename,  /* Name of the file being opened */
   25030   int noLock,             /* Omit locking if true */
   25031   int isDelete            /* Delete on close if true */
   25032 ){
   25033   const sqlite3_io_methods *pLockingStyle;
   25034   unixFile *pNew = (unixFile *)pId;
   25035   int rc = SQLITE_OK;
   25036 
   25037   assert( pNew->pLock==NULL );
   25038   assert( pNew->pOpen==NULL );
   25039 
   25040   /* Parameter isDelete is only used on vxworks. Express this explicitly
   25041   ** here to prevent compiler warnings about unused parameters.
   25042   */
   25043   UNUSED_PARAMETER(isDelete);
   25044 
   25045   OSTRACE3("OPEN    %-3d %s\n", h, zFilename);
   25046   pNew->h = h;
   25047   pNew->dirfd = dirfd;
   25048   SET_THREADID(pNew);
   25049   pNew->fileFlags = 0;
   25050 
   25051 #if OS_VXWORKS
   25052   pNew->pId = vxworksFindFileId(zFilename);
   25053   if( pNew->pId==0 ){
   25054     noLock = 1;
   25055     rc = SQLITE_NOMEM;
   25056   }
   25057 #endif
   25058 
   25059   if( noLock ){
   25060     pLockingStyle = &nolockIoMethods;
   25061   }else{
   25062     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
   25063 #if SQLITE_ENABLE_LOCKING_STYLE
   25064     /* Cache zFilename in the locking context (AFP and dotlock override) for
   25065     ** proxyLock activation is possible (remote proxy is based on db name)
   25066     ** zFilename remains valid until file is closed, to support */
   25067     pNew->lockingContext = (void*)zFilename;
   25068 #endif
   25069   }
   25070 
   25071   if( pLockingStyle == &posixIoMethods ){
   25072     unixEnterMutex();
   25073     rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
   25074     if( rc!=SQLITE_OK ){
   25075       /* If an error occured in findLockInfo(), close the file descriptor
   25076       ** immediately, before releasing the mutex. findLockInfo() may fail
   25077       ** in two scenarios:
   25078       **
   25079       **   (a) A call to fstat() failed.
   25080       **   (b) A malloc failed.
   25081       **
   25082       ** Scenario (b) may only occur if the process is holding no other
   25083       ** file descriptors open on the same file. If there were other file
   25084       ** descriptors on this file, then no malloc would be required by
   25085       ** findLockInfo(). If this is the case, it is quite safe to close
   25086       ** handle h - as it is guaranteed that no posix locks will be released
   25087       ** by doing so.
   25088       **
   25089       ** If scenario (a) caused the error then things are not so safe. The
   25090       ** implicit assumption here is that if fstat() fails, things are in
   25091       ** such bad shape that dropping a lock or two doesn't matter much.
   25092       */
   25093       close(h);
   25094       h = -1;
   25095     }
   25096     unixLeaveMutex();
   25097   }
   25098 
   25099 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   25100   else if( pLockingStyle == &afpIoMethods ){
   25101     /* AFP locking uses the file path so it needs to be included in
   25102     ** the afpLockingContext.
   25103     */
   25104     afpLockingContext *pCtx;
   25105     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
   25106     if( pCtx==0 ){
   25107       rc = SQLITE_NOMEM;
   25108     }else{
   25109       /* NB: zFilename exists and remains valid until the file is closed
   25110       ** according to requirement F11141.  So we do not need to make a
   25111       ** copy of the filename. */
   25112       pCtx->dbPath = zFilename;
   25113       srandomdev();
   25114       unixEnterMutex();
   25115       rc = findLockInfo(pNew, NULL, &pNew->pOpen);
   25116       unixLeaveMutex();
   25117     }
   25118   }
   25119 #endif
   25120 
   25121   else if( pLockingStyle == &dotlockIoMethods ){
   25122     /* Dotfile locking uses the file path so it needs to be included in
   25123     ** the dotlockLockingContext
   25124     */
   25125     char *zLockFile;
   25126     int nFilename;
   25127     nFilename = (int)strlen(zFilename) + 6;
   25128     zLockFile = (char *)sqlite3_malloc(nFilename);
   25129     if( zLockFile==0 ){
   25130       rc = SQLITE_NOMEM;
   25131     }else{
   25132       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
   25133     }
   25134     pNew->lockingContext = zLockFile;
   25135   }
   25136 
   25137 #if OS_VXWORKS
   25138   else if( pLockingStyle == &semIoMethods ){
   25139     /* Named semaphore locking uses the file path so it needs to be
   25140     ** included in the semLockingContext
   25141     */
   25142     unixEnterMutex();
   25143     rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
   25144     if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
   25145       char *zSemName = pNew->pOpen->aSemName;
   25146       int n;
   25147       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
   25148                        pNew->pId->zCanonicalName);
   25149       for( n=1; zSemName[n]; n++ )
   25150         if( zSemName[n]=='/' ) zSemName[n] = '_';
   25151       pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
   25152       if( pNew->pOpen->pSem == SEM_FAILED ){
   25153         rc = SQLITE_NOMEM;
   25154         pNew->pOpen->aSemName[0] = '\0';
   25155       }
   25156     }
   25157     unixLeaveMutex();
   25158   }
   25159 #endif
   25160 
   25161   pNew->lastErrno = 0;
   25162 #if OS_VXWORKS
   25163   if( rc!=SQLITE_OK ){
   25164     unlink(zFilename);
   25165     isDelete = 0;
   25166   }
   25167   pNew->isDelete = isDelete;
   25168 #endif
   25169   if( rc!=SQLITE_OK ){
   25170     if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
   25171     if( h>=0 ) close(h);
   25172   }else{
   25173     pNew->pMethod = pLockingStyle;
   25174     OpenCounter(+1);
   25175   }
   25176   return rc;
   25177 }
   25178 
   25179 /*
   25180 ** Open a file descriptor to the directory containing file zFilename.
   25181 ** If successful, *pFd is set to the opened file descriptor and
   25182 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
   25183 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
   25184 ** value.
   25185 **
   25186 ** If SQLITE_OK is returned, the caller is responsible for closing
   25187 ** the file descriptor *pFd using close().
   25188 */
   25189 static int openDirectory(const char *zFilename, int *pFd){
   25190   int ii;
   25191   int fd = -1;
   25192   char zDirname[MAX_PATHNAME+1];
   25193 
   25194   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
   25195   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
   25196   if( ii>0 ){
   25197     zDirname[ii] = '\0';
   25198     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
   25199     if( fd>=0 ){
   25200 #ifdef FD_CLOEXEC
   25201       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
   25202 #endif
   25203       OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
   25204     }
   25205   }
   25206   *pFd = fd;
   25207   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
   25208 }
   25209 
   25210 /*
   25211 ** Create a temporary file name in zBuf.  zBuf must be allocated
   25212 ** by the calling process and must be big enough to hold at least
   25213 ** pVfs->mxPathname bytes.
   25214 */
   25215 static int getTempname(int nBuf, char *zBuf){
   25216   static const char *azDirs[] = {
   25217      0,
   25218      0,
   25219      "/var/tmp",
   25220      "/usr/tmp",
   25221      "/tmp",
   25222      ".",
   25223   };
   25224   static const unsigned char zChars[] =
   25225     "abcdefghijklmnopqrstuvwxyz"
   25226     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   25227     "0123456789";
   25228   unsigned int i, j;
   25229   struct stat buf;
   25230   const char *zDir = ".";
   25231 
   25232   /* It's odd to simulate an io-error here, but really this is just
   25233   ** using the io-error infrastructure to test that SQLite handles this
   25234   ** function failing.
   25235   */
   25236   SimulateIOError( return SQLITE_IOERR );
   25237 
   25238   azDirs[0] = sqlite3_temp_directory;
   25239   if (NULL == azDirs[1]) {
   25240     azDirs[1] = getenv("TMPDIR");
   25241   }
   25242 
   25243   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
   25244     if( azDirs[i]==0 ) continue;
   25245     if( stat(azDirs[i], &buf) ) continue;
   25246     if( !S_ISDIR(buf.st_mode) ) continue;
   25247     if( access(azDirs[i], 07) ) continue;
   25248     zDir = azDirs[i];
   25249     break;
   25250   }
   25251 
   25252   /* Check that the output buffer is large enough for the temporary file
   25253   ** name. If it is not, return SQLITE_ERROR.
   25254   */
   25255   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
   25256     return SQLITE_ERROR;
   25257   }
   25258 
   25259   do{
   25260     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
   25261     j = (int)strlen(zBuf);
   25262     sqlite3_randomness(15, &zBuf[j]);
   25263     for(i=0; i<15; i++, j++){
   25264       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   25265     }
   25266     zBuf[j] = 0;
   25267   }while( access(zBuf,0)==0 );
   25268   return SQLITE_OK;
   25269 }
   25270 
   25271 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   25272 /*
   25273 ** Routine to transform a unixFile into a proxy-locking unixFile.
   25274 ** Implementation in the proxy-lock division, but used by unixOpen()
   25275 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
   25276 */
   25277 static int proxyTransformUnixFile(unixFile*, const char*);
   25278 #endif
   25279 
   25280 /*
   25281 ** Search for an unused file descriptor that was opened on the database
   25282 ** file (not a journal or master-journal file) identified by pathname
   25283 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
   25284 ** argument to this function.
   25285 **
   25286 ** Such a file descriptor may exist if a database connection was closed
   25287 ** but the associated file descriptor could not be closed because some
   25288 ** other file descriptor open on the same file is holding a file-lock.
   25289 ** Refer to comments in the unixClose() function and the lengthy comment
   25290 ** describing "Posix Advisory Locking" at the start of this file for
   25291 ** further details. Also, ticket #4018.
   25292 **
   25293 ** If a suitable file descriptor is found, then it is returned. If no
   25294 ** such file descriptor is located, -1 is returned.
   25295 */
   25296 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
   25297   UnixUnusedFd *pUnused = 0;
   25298 
   25299   /* Do not search for an unused file descriptor on vxworks. Not because
   25300   ** vxworks would not benefit from the change (it might, we're not sure),
   25301   ** but because no way to test it is currently available. It is better
   25302   ** not to risk breaking vxworks support for the sake of such an obscure
   25303   ** feature.  */
   25304 #if !OS_VXWORKS
   25305   struct stat sStat;                   /* Results of stat() call */
   25306 
   25307   /* A stat() call may fail for various reasons. If this happens, it is
   25308   ** almost certain that an open() call on the same path will also fail.
   25309   ** For this reason, if an error occurs in the stat() call here, it is
   25310   ** ignored and -1 is returned. The caller will try to open a new file
   25311   ** descriptor on the same path, fail, and return an error to SQLite.
   25312   **
   25313   ** Even if a subsequent open() call does succeed, the consequences of
   25314   ** not searching for a resusable file descriptor are not dire.  */
   25315   if( 0==stat(zPath, &sStat) ){
   25316     struct unixOpenCnt *pOpen;
   25317 
   25318     unixEnterMutex();
   25319     pOpen = openList;
   25320     while( pOpen && (pOpen->fileId.dev!=sStat.st_dev
   25321                      || pOpen->fileId.ino!=sStat.st_ino) ){
   25322        pOpen = pOpen->pNext;
   25323     }
   25324     if( pOpen ){
   25325       UnixUnusedFd **pp;
   25326       for(pp=&pOpen->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
   25327       pUnused = *pp;
   25328       if( pUnused ){
   25329         *pp = pUnused->pNext;
   25330       }
   25331     }
   25332     unixLeaveMutex();
   25333   }
   25334 #endif    /* if !OS_VXWORKS */
   25335   return pUnused;
   25336 }
   25337 
   25338 /*
   25339 ** Open the file zPath.
   25340 **
   25341 ** Previously, the SQLite OS layer used three functions in place of this
   25342 ** one:
   25343 **
   25344 **     sqlite3OsOpenReadWrite();
   25345 **     sqlite3OsOpenReadOnly();
   25346 **     sqlite3OsOpenExclusive();
   25347 **
   25348 ** These calls correspond to the following combinations of flags:
   25349 **
   25350 **     ReadWrite() ->     (READWRITE | CREATE)
   25351 **     ReadOnly()  ->     (READONLY)
   25352 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
   25353 **
   25354 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
   25355 ** true, the file was configured to be automatically deleted when the
   25356 ** file handle closed. To achieve the same effect using this new
   25357 ** interface, add the DELETEONCLOSE flag to those specified above for
   25358 ** OpenExclusive().
   25359 */
   25360 static int unixOpen(
   25361   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
   25362   const char *zPath,           /* Pathname of file to be opened */
   25363   sqlite3_file *pFile,         /* The file descriptor to be filled in */
   25364   int flags,                   /* Input flags to control the opening */
   25365   int *pOutFlags               /* Output flags returned to SQLite core */
   25366 ){
   25367   unixFile *p = (unixFile *)pFile;
   25368   int fd = -1;                   /* File descriptor returned by open() */
   25369   int dirfd = -1;                /* Directory file descriptor */
   25370   int openFlags = 0;             /* Flags to pass to open() */
   25371   int eType = flags&0xFFFFFF00;  /* Type of file to open */
   25372   int noLock;                    /* True to omit locking primitives */
   25373   int rc = SQLITE_OK;            /* Function Return Code */
   25374 
   25375   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
   25376   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
   25377   int isCreate     = (flags & SQLITE_OPEN_CREATE);
   25378   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
   25379   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
   25380 
   25381   /* If creating a master or main-file journal, this function will open
   25382   ** a file-descriptor on the directory too. The first time unixSync()
   25383   ** is called the directory file descriptor will be fsync()ed and close()d.
   25384   */
   25385   int isOpenDirectory = (isCreate &&
   25386       (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
   25387   );
   25388 
   25389   /* If argument zPath is a NULL pointer, this function is required to open
   25390   ** a temporary file. Use this buffer to store the file name in.
   25391   */
   25392   char zTmpname[MAX_PATHNAME+1];
   25393   const char *zName = zPath;
   25394 
   25395   /* Check the following statements are true:
   25396   **
   25397   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
   25398   **   (b) if CREATE is set, then READWRITE must also be set, and
   25399   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
   25400   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
   25401   */
   25402   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
   25403   assert(isCreate==0 || isReadWrite);
   25404   assert(isExclusive==0 || isCreate);
   25405   assert(isDelete==0 || isCreate);
   25406 
   25407   /* The main DB, main journal, and master journal are never automatically
   25408   ** deleted. Nor are they ever temporary files.  */
   25409   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   25410   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
   25411   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
   25412 
   25413   /* Assert that the upper layer has set one of the "file-type" flags. */
   25414   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
   25415        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
   25416        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
   25417        || eType==SQLITE_OPEN_TRANSIENT_DB
   25418   );
   25419 
   25420   memset(p, 0, sizeof(unixFile));
   25421 
   25422   if( eType==SQLITE_OPEN_MAIN_DB ){
   25423     UnixUnusedFd *pUnused;
   25424     pUnused = findReusableFd(zName, flags);
   25425     if( pUnused ){
   25426       fd = pUnused->fd;
   25427     }else{
   25428       pUnused = sqlite3_malloc(sizeof(*pUnused));
   25429       if( !pUnused ){
   25430         return SQLITE_NOMEM;
   25431       }
   25432     }
   25433     p->pUnused = pUnused;
   25434   }else if( !zName ){
   25435     /* If zName is NULL, the upper layer is requesting a temp file. */
   25436     assert(isDelete && !isOpenDirectory);
   25437     rc = getTempname(MAX_PATHNAME+1, zTmpname);
   25438     if( rc!=SQLITE_OK ){
   25439       return rc;
   25440     }
   25441     zName = zTmpname;
   25442   }
   25443 
   25444   /* Determine the value of the flags parameter passed to POSIX function
   25445   ** open(). These must be calculated even if open() is not called, as
   25446   ** they may be stored as part of the file handle and used by the
   25447   ** 'conch file' locking functions later on.  */
   25448   if( isReadonly )  openFlags |= O_RDONLY;
   25449   if( isReadWrite ) openFlags |= O_RDWR;
   25450   if( isCreate )    openFlags |= O_CREAT;
   25451   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
   25452   openFlags |= (O_LARGEFILE|O_BINARY);
   25453 
   25454   if( fd<0 ){
   25455     mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
   25456     fd = open(zName, openFlags, openMode);
   25457     OSTRACE4("OPENX   %-3d %s 0%o\n", fd, zName, openFlags);
   25458     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
   25459       /* Failed to open the file for read/write access. Try read-only. */
   25460       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
   25461       openFlags &= ~(O_RDWR|O_CREAT);
   25462       flags |= SQLITE_OPEN_READONLY;
   25463       openFlags |= O_RDONLY;
   25464       fd = open(zName, openFlags, openMode);
   25465     }
   25466     if( fd<0 ){
   25467       rc = SQLITE_CANTOPEN_BKPT;
   25468       goto open_finished;
   25469     }
   25470   }
   25471   assert( fd>=0 );
   25472   if( pOutFlags ){
   25473     *pOutFlags = flags;
   25474   }
   25475 
   25476   if( p->pUnused ){
   25477     p->pUnused->fd = fd;
   25478     p->pUnused->flags = flags;
   25479   }
   25480 
   25481   if( isDelete ){
   25482 #if OS_VXWORKS
   25483     zPath = zName;
   25484 #else
   25485     unlink(zName);
   25486 #endif
   25487   }
   25488 #if SQLITE_ENABLE_LOCKING_STYLE
   25489   else{
   25490     p->openFlags = openFlags;
   25491   }
   25492 #endif
   25493 
   25494   if( isOpenDirectory ){
   25495     rc = openDirectory(zPath, &dirfd);
   25496     if( rc!=SQLITE_OK ){
   25497       /* It is safe to close fd at this point, because it is guaranteed not
   25498       ** to be open on a database file. If it were open on a database file,
   25499       ** it would not be safe to close as this would release any locks held
   25500       ** on the file by this process.  */
   25501       assert( eType!=SQLITE_OPEN_MAIN_DB );
   25502       close(fd);             /* silently leak if fail, already in error */
   25503       goto open_finished;
   25504     }
   25505   }
   25506 
   25507 #ifdef FD_CLOEXEC
   25508   fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
   25509 #endif
   25510 
   25511   noLock = eType!=SQLITE_OPEN_MAIN_DB;
   25512 
   25513 #if SQLITE_PREFER_PROXY_LOCKING
   25514   if( zPath!=NULL && !noLock && pVfs->xOpen ){
   25515     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
   25516     int useProxy = 0;
   25517 
   25518     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
   25519     ** never use proxy, NULL means use proxy for non-local files only.  */
   25520     if( envforce!=NULL ){
   25521       useProxy = atoi(envforce)>0;
   25522     }else{
   25523       struct statfs fsInfo;
   25524       if( statfs(zPath, &fsInfo) == -1 ){
   25525         /* In theory, the close(fd) call is sub-optimal. If the file opened
   25526         ** with fd is a database file, and there are other connections open
   25527         ** on that file that are currently holding advisory locks on it,
   25528         ** then the call to close() will cancel those locks. In practice,
   25529         ** we're assuming that statfs() doesn't fail very often. At least
   25530         ** not while other file descriptors opened by the same process on
   25531         ** the same file are working.  */
   25532         p->lastErrno = errno;
   25533         if( dirfd>=0 ){
   25534           close(dirfd); /* silently leak if fail, in error */
   25535         }
   25536         close(fd); /* silently leak if fail, in error */
   25537         rc = SQLITE_IOERR_ACCESS;
   25538         goto open_finished;
   25539       }
   25540       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
   25541     }
   25542     if( useProxy ){
   25543       rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
   25544       if( rc==SQLITE_OK ){
   25545         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
   25546       }
   25547       goto open_finished;
   25548     }
   25549   }
   25550 #endif
   25551 
   25552   rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
   25553 open_finished:
   25554   if( rc!=SQLITE_OK ){
   25555     sqlite3_free(p->pUnused);
   25556   }
   25557   return rc;
   25558 }
   25559 
   25560 
   25561 /*
   25562 ** Delete the file at zPath. If the dirSync argument is true, fsync()
   25563 ** the directory after deleting the file.
   25564 */
   25565 static int unixDelete(
   25566   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
   25567   const char *zPath,        /* Name of file to be deleted */
   25568   int dirSync               /* If true, fsync() directory after deleting file */
   25569 ){
   25570   int rc = SQLITE_OK;
   25571   UNUSED_PARAMETER(NotUsed);
   25572   SimulateIOError(return SQLITE_IOERR_DELETE);
   25573   unlink(zPath);
   25574 #ifndef SQLITE_DISABLE_DIRSYNC
   25575   if( dirSync ){
   25576     int fd;
   25577     rc = openDirectory(zPath, &fd);
   25578     if( rc==SQLITE_OK ){
   25579 #if OS_VXWORKS
   25580       if( fsync(fd)==-1 )
   25581 #else
   25582       if( fsync(fd) )
   25583 #endif
   25584       {
   25585         rc = SQLITE_IOERR_DIR_FSYNC;
   25586       }
   25587       if( close(fd)&&!rc ){
   25588         rc = SQLITE_IOERR_DIR_CLOSE;
   25589       }
   25590     }
   25591   }
   25592 #endif
   25593   return rc;
   25594 }
   25595 
   25596 /*
   25597 ** Test the existance of or access permissions of file zPath. The
   25598 ** test performed depends on the value of flags:
   25599 **
   25600 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
   25601 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
   25602 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
   25603 **
   25604 ** Otherwise return 0.
   25605 */
   25606 static int unixAccess(
   25607   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
   25608   const char *zPath,      /* Path of the file to examine */
   25609   int flags,              /* What do we want to learn about the zPath file? */
   25610   int *pResOut            /* Write result boolean here */
   25611 ){
   25612   int amode = 0;
   25613   UNUSED_PARAMETER(NotUsed);
   25614   SimulateIOError( return SQLITE_IOERR_ACCESS; );
   25615   switch( flags ){
   25616     case SQLITE_ACCESS_EXISTS:
   25617       amode = F_OK;
   25618       break;
   25619     case SQLITE_ACCESS_READWRITE:
   25620       amode = W_OK|R_OK;
   25621       break;
   25622     case SQLITE_ACCESS_READ:
   25623       amode = R_OK;
   25624       break;
   25625 
   25626     default:
   25627       assert(!"Invalid flags argument");
   25628   }
   25629   *pResOut = (access(zPath, amode)==0);
   25630   return SQLITE_OK;
   25631 }
   25632 
   25633 
   25634 /*
   25635 ** Turn a relative pathname into a full pathname. The relative path
   25636 ** is stored as a nul-terminated string in the buffer pointed to by
   25637 ** zPath.
   25638 **
   25639 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
   25640 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
   25641 ** this buffer before returning.
   25642 */
   25643 static int unixFullPathname(
   25644   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
   25645   const char *zPath,            /* Possibly relative input path */
   25646   int nOut,                     /* Size of output buffer in bytes */
   25647   char *zOut                    /* Output buffer */
   25648 ){
   25649 
   25650   /* It's odd to simulate an io-error here, but really this is just
   25651   ** using the io-error infrastructure to test that SQLite handles this
   25652   ** function failing. This function could fail if, for example, the
   25653   ** current working directory has been unlinked.
   25654   */
   25655   SimulateIOError( return SQLITE_ERROR );
   25656 
   25657   assert( pVfs->mxPathname==MAX_PATHNAME );
   25658   UNUSED_PARAMETER(pVfs);
   25659 
   25660   zOut[nOut-1] = '\0';
   25661   if( zPath[0]=='/' ){
   25662     sqlite3_snprintf(nOut, zOut, "%s", zPath);
   25663   }else{
   25664     int nCwd;
   25665     if( getcwd(zOut, nOut-1)==0 ){
   25666       return SQLITE_CANTOPEN_BKPT;
   25667     }
   25668     nCwd = (int)strlen(zOut);
   25669     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
   25670   }
   25671   return SQLITE_OK;
   25672 }
   25673 
   25674 
   25675 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   25676 /*
   25677 ** Interfaces for opening a shared library, finding entry points
   25678 ** within the shared library, and closing the shared library.
   25679 */
   25680 #include <dlfcn.h>
   25681 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
   25682   UNUSED_PARAMETER(NotUsed);
   25683   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
   25684 }
   25685 
   25686 /*
   25687 ** SQLite calls this function immediately after a call to unixDlSym() or
   25688 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
   25689 ** message is available, it is written to zBufOut. If no error message
   25690 ** is available, zBufOut is left unmodified and SQLite uses a default
   25691 ** error message.
   25692 */
   25693 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
   25694   char *zErr;
   25695   UNUSED_PARAMETER(NotUsed);
   25696   unixEnterMutex();
   25697   zErr = dlerror();
   25698   if( zErr ){
   25699     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
   25700   }
   25701   unixLeaveMutex();
   25702 }
   25703 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
   25704   /*
   25705   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
   25706   ** cast into a pointer to a function.  And yet the library dlsym() routine
   25707   ** returns a void* which is really a pointer to a function.  So how do we
   25708   ** use dlsym() with -pedantic-errors?
   25709   **
   25710   ** Variable x below is defined to be a pointer to a function taking
   25711   ** parameters void* and const char* and returning a pointer to a function.
   25712   ** We initialize x by assigning it a pointer to the dlsym() function.
   25713   ** (That assignment requires a cast.)  Then we call the function that
   25714   ** x points to.
   25715   **
   25716   ** This work-around is unlikely to work correctly on any system where
   25717   ** you really cannot cast a function pointer into void*.  But then, on the
   25718   ** other hand, dlsym() will not work on such a system either, so we have
   25719   ** not really lost anything.
   25720   */
   25721   void (*(*x)(void*,const char*))(void);
   25722   UNUSED_PARAMETER(NotUsed);
   25723   x = (void(*(*)(void*,const char*))(void))dlsym;
   25724   return (*x)(p, zSym);
   25725 }
   25726 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
   25727   UNUSED_PARAMETER(NotUsed);
   25728   dlclose(pHandle);
   25729 }
   25730 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   25731   #define unixDlOpen  0
   25732   #define unixDlError 0
   25733   #define unixDlSym   0
   25734   #define unixDlClose 0
   25735 #endif
   25736 
   25737 /*
   25738 ** Write nBuf bytes of random data to the supplied buffer zBuf.
   25739 */
   25740 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
   25741   UNUSED_PARAMETER(NotUsed);
   25742   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
   25743 
   25744   /* We have to initialize zBuf to prevent valgrind from reporting
   25745   ** errors.  The reports issued by valgrind are incorrect - we would
   25746   ** prefer that the randomness be increased by making use of the
   25747   ** uninitialized space in zBuf - but valgrind errors tend to worry
   25748   ** some users.  Rather than argue, it seems easier just to initialize
   25749   ** the whole array and silence valgrind, even if that means less randomness
   25750   ** in the random seed.
   25751   **
   25752   ** When testing, initializing zBuf[] to zero is all we do.  That means
   25753   ** that we always use the same random number sequence.  This makes the
   25754   ** tests repeatable.
   25755   */
   25756   memset(zBuf, 0, nBuf);
   25757 #if !defined(SQLITE_TEST)
   25758   {
   25759     int pid, fd;
   25760     fd = open("/dev/urandom", O_RDONLY);
   25761     if( fd<0 ){
   25762       time_t t;
   25763       time(&t);
   25764       memcpy(zBuf, &t, sizeof(t));
   25765       pid = getpid();
   25766       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
   25767       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
   25768       nBuf = sizeof(t) + sizeof(pid);
   25769     }else{
   25770       nBuf = read(fd, zBuf, nBuf);
   25771       close(fd);
   25772     }
   25773   }
   25774 #endif
   25775   return nBuf;
   25776 }
   25777 
   25778 
   25779 /*
   25780 ** Sleep for a little while.  Return the amount of time slept.
   25781 ** The argument is the number of microseconds we want to sleep.
   25782 ** The return value is the number of microseconds of sleep actually
   25783 ** requested from the underlying operating system, a number which
   25784 ** might be greater than or equal to the argument, but not less
   25785 ** than the argument.
   25786 */
   25787 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
   25788 #if OS_VXWORKS
   25789   struct timespec sp;
   25790 
   25791   sp.tv_sec = microseconds / 1000000;
   25792   sp.tv_nsec = (microseconds % 1000000) * 1000;
   25793   nanosleep(&sp, NULL);
   25794   UNUSED_PARAMETER(NotUsed);
   25795   return microseconds;
   25796 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
   25797   usleep(microseconds);
   25798   UNUSED_PARAMETER(NotUsed);
   25799   return microseconds;
   25800 #else
   25801   int seconds = (microseconds+999999)/1000000;
   25802   sleep(seconds);
   25803   UNUSED_PARAMETER(NotUsed);
   25804   return seconds*1000000;
   25805 #endif
   25806 }
   25807 
   25808 /*
   25809 ** The following variable, if set to a non-zero value, is interpreted as
   25810 ** the number of seconds since 1970 and is used to set the result of
   25811 ** sqlite3OsCurrentTime() during testing.
   25812 */
   25813 #ifdef SQLITE_TEST
   25814 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
   25815 #endif
   25816 
   25817 /*
   25818 ** Find the current time (in Universal Coordinated Time).  Write the
   25819 ** current time and date as a Julian Day number into *prNow and
   25820 ** return 0.  Return 1 if the time and date cannot be found.
   25821 */
   25822 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
   25823 #if defined(SQLITE_OMIT_FLOATING_POINT)
   25824   time_t t;
   25825   time(&t);
   25826   *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
   25827 #elif defined(NO_GETTOD)
   25828   time_t t;
   25829   time(&t);
   25830   *prNow = t/86400.0 + 2440587.5;
   25831 #elif OS_VXWORKS
   25832   struct timespec sNow;
   25833   clock_gettime(CLOCK_REALTIME, &sNow);
   25834   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
   25835 #else
   25836   struct timeval sNow;
   25837   gettimeofday(&sNow, 0);
   25838   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
   25839 #endif
   25840 
   25841 #ifdef SQLITE_TEST
   25842   if( sqlite3_current_time ){
   25843     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
   25844   }
   25845 #endif
   25846   UNUSED_PARAMETER(NotUsed);
   25847   return 0;
   25848 }
   25849 
   25850 /*
   25851 ** We added the xGetLastError() method with the intention of providing
   25852 ** better low-level error messages when operating-system problems come up
   25853 ** during SQLite operation.  But so far, none of that has been implemented
   25854 ** in the core.  So this routine is never called.  For now, it is merely
   25855 ** a place-holder.
   25856 */
   25857 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
   25858   UNUSED_PARAMETER(NotUsed);
   25859   UNUSED_PARAMETER(NotUsed2);
   25860   UNUSED_PARAMETER(NotUsed3);
   25861   return 0;
   25862 }
   25863 
   25864 /*
   25865 ************************ End of sqlite3_vfs methods ***************************
   25866 ******************************************************************************/
   25867 
   25868 /******************************************************************************
   25869 ************************** Begin Proxy Locking ********************************
   25870 **
   25871 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
   25872 ** other locking methods on secondary lock files.  Proxy locking is a
   25873 ** meta-layer over top of the primitive locking implemented above.  For
   25874 ** this reason, the division that implements of proxy locking is deferred
   25875 ** until late in the file (here) after all of the other I/O methods have
   25876 ** been defined - so that the primitive locking methods are available
   25877 ** as services to help with the implementation of proxy locking.
   25878 **
   25879 ****
   25880 **
   25881 ** The default locking schemes in SQLite use byte-range locks on the
   25882 ** database file to coordinate safe, concurrent access by multiple readers
   25883 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
   25884 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
   25885 ** as POSIX read & write locks over fixed set of locations (via fsctl),
   25886 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
   25887 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
   25888 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
   25889 ** address in the shared range is taken for a SHARED lock, the entire
   25890 ** shared range is taken for an EXCLUSIVE lock):
   25891 **
   25892 **      PENDING_BYTE        0x40000000
   25893 **      RESERVED_BYTE       0x40000001
   25894 **      SHARED_RANGE        0x40000002 -> 0x40000200
   25895 **
   25896 ** This works well on the local file system, but shows a nearly 100x
   25897 ** slowdown in read performance on AFP because the AFP client disables
   25898 ** the read cache when byte-range locks are present.  Enabling the read
   25899 ** cache exposes a cache coherency problem that is present on all OS X
   25900 ** supported network file systems.  NFS and AFP both observe the
   25901 ** close-to-open semantics for ensuring cache coherency
   25902 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
   25903 ** address the requirements for concurrent database access by multiple
   25904 ** readers and writers
   25905 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
   25906 **
   25907 ** To address the performance and cache coherency issues, proxy file locking
   25908 ** changes the way database access is controlled by limiting access to a
   25909 ** single host at a time and moving file locks off of the database file
   25910 ** and onto a proxy file on the local file system.
   25911 **
   25912 **
   25913 ** Using proxy locks
   25914 ** -----------------
   25915 **
   25916 ** C APIs
   25917 **
   25918 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
   25919 **                       <proxy_path> | ":auto:");
   25920 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
   25921 **
   25922 **
   25923 ** SQL pragmas
   25924 **
   25925 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
   25926 **  PRAGMA [database.]lock_proxy_file
   25927 **
   25928 ** Specifying ":auto:" means that if there is a conch file with a matching
   25929 ** host ID in it, the proxy path in the conch file will be used, otherwise
   25930 ** a proxy path based on the user's temp dir
   25931 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
   25932 ** actual proxy file name is generated from the name and path of the
   25933 ** database file.  For example:
   25934 **
   25935 **       For database path "/Users/me/foo.db"
   25936 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
   25937 **
   25938 ** Once a lock proxy is configured for a database connection, it can not
   25939 ** be removed, however it may be switched to a different proxy path via
   25940 ** the above APIs (assuming the conch file is not being held by another
   25941 ** connection or process).
   25942 **
   25943 **
   25944 ** How proxy locking works
   25945 ** -----------------------
   25946 **
   25947 ** Proxy file locking relies primarily on two new supporting files:
   25948 **
   25949 **   *  conch file to limit access to the database file to a single host
   25950 **      at a time
   25951 **
   25952 **   *  proxy file to act as a proxy for the advisory locks normally
   25953 **      taken on the database
   25954 **
   25955 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
   25956 ** by taking an sqlite-style shared lock on the conch file, reading the
   25957 ** contents and comparing the host's unique host ID (see below) and lock
   25958 ** proxy path against the values stored in the conch.  The conch file is
   25959 ** stored in the same directory as the database file and the file name
   25960 ** is patterned after the database file name as ".<databasename>-conch".
   25961 ** If the conch file does not exist, or it's contents do not match the
   25962 ** host ID and/or proxy path, then the lock is escalated to an exclusive
   25963 ** lock and the conch file contents is updated with the host ID and proxy
   25964 ** path and the lock is downgraded to a shared lock again.  If the conch
   25965 ** is held by another process (with a shared lock), the exclusive lock
   25966 ** will fail and SQLITE_BUSY is returned.
   25967 **
   25968 ** The proxy file - a single-byte file used for all advisory file locks
   25969 ** normally taken on the database file.   This allows for safe sharing
   25970 ** of the database file for multiple readers and writers on the same
   25971 ** host (the conch ensures that they all use the same local lock file).
   25972 **
   25973 ** There is a third file - the host ID file - used as a persistent record
   25974 ** of a unique identifier for the host, a 128-byte unique host id file
   25975 ** in the path defined by the HOSTIDPATH macro (default value is
   25976 ** /Library/Caches/.com.apple.sqliteConchHostId).
   25977 **
   25978 ** Requesting the lock proxy does not immediately take the conch, it is
   25979 ** only taken when the first request to lock database file is made.
   25980 ** This matches the semantics of the traditional locking behavior, where
   25981 ** opening a connection to a database file does not take a lock on it.
   25982 ** The shared lock and an open file descriptor are maintained until
   25983 ** the connection to the database is closed.
   25984 **
   25985 ** The proxy file and the lock file are never deleted so they only need
   25986 ** to be created the first time they are used.
   25987 **
   25988 ** Configuration options
   25989 ** ---------------------
   25990 **
   25991 **  SQLITE_PREFER_PROXY_LOCKING
   25992 **
   25993 **       Database files accessed on non-local file systems are
   25994 **       automatically configured for proxy locking, lock files are
   25995 **       named automatically using the same logic as
   25996 **       PRAGMA lock_proxy_file=":auto:"
   25997 **
   25998 **  SQLITE_PROXY_DEBUG
   25999 **
   26000 **       Enables the logging of error messages during host id file
   26001 **       retrieval and creation
   26002 **
   26003 **  HOSTIDPATH
   26004 **
   26005 **       Overrides the default host ID file path location
   26006 **
   26007 **  LOCKPROXYDIR
   26008 **
   26009 **       Overrides the default directory used for lock proxy files that
   26010 **       are named automatically via the ":auto:" setting
   26011 **
   26012 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   26013 **
   26014 **       Permissions to use when creating a directory for storing the
   26015 **       lock proxy files, only used when LOCKPROXYDIR is not set.
   26016 **
   26017 **
   26018 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
   26019 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
   26020 ** force proxy locking to be used for every database file opened, and 0
   26021 ** will force automatic proxy locking to be disabled for all database
   26022 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
   26023 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
   26024 */
   26025 
   26026 /*
   26027 ** Proxy locking is only available on MacOSX
   26028 */
   26029 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   26030 
   26031 #ifdef SQLITE_TEST
   26032 /* simulate multiple hosts by creating unique hostid file paths */
   26033 SQLITE_API int sqlite3_hostid_num = 0;
   26034 #endif
   26035 
   26036 /*
   26037 ** The proxyLockingContext has the path and file structures for the remote
   26038 ** and local proxy files in it
   26039 */
   26040 typedef struct proxyLockingContext proxyLockingContext;
   26041 struct proxyLockingContext {
   26042   unixFile *conchFile;         /* Open conch file */
   26043   char *conchFilePath;         /* Name of the conch file */
   26044   unixFile *lockProxy;         /* Open proxy lock file */
   26045   char *lockProxyPath;         /* Name of the proxy lock file */
   26046   char *dbPath;                /* Name of the open file */
   26047   int conchHeld;               /* True if the conch is currently held */
   26048   void *oldLockingContext;     /* Original lockingcontext to restore on close */
   26049   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
   26050 };
   26051 
   26052 /* HOSTIDLEN and CONCHLEN both include space for the string
   26053 ** terminating nul
   26054 */
   26055 #define HOSTIDLEN         128
   26056 #define CONCHLEN          (MAXPATHLEN+HOSTIDLEN+1)
   26057 #ifndef HOSTIDPATH
   26058 # define HOSTIDPATH       "/Library/Caches/.com.apple.sqliteConchHostId"
   26059 #endif
   26060 
   26061 /* basically a copy of unixRandomness with different
   26062 ** test behavior built in */
   26063 static int proxyGenerateHostID(char *pHostID){
   26064   int pid, fd, len;
   26065   unsigned char *key = (unsigned char *)pHostID;
   26066 
   26067   memset(key, 0, HOSTIDLEN);
   26068   len = 0;
   26069   fd = open("/dev/urandom", O_RDONLY);
   26070   if( fd>=0 ){
   26071     len = read(fd, key, HOSTIDLEN);
   26072     close(fd); /* silently leak the fd if it fails */
   26073   }
   26074   if( len < HOSTIDLEN ){
   26075     time_t t;
   26076     time(&t);
   26077     memcpy(key, &t, sizeof(t));
   26078     pid = getpid();
   26079     memcpy(&key[sizeof(t)], &pid, sizeof(pid));
   26080   }
   26081 
   26082 #ifdef MAKE_PRETTY_HOSTID
   26083   {
   26084     int i;
   26085     /* filter the bytes into printable ascii characters and NUL terminate */
   26086     key[(HOSTIDLEN-1)] = 0x00;
   26087     for( i=0; i<(HOSTIDLEN-1); i++ ){
   26088       unsigned char pa = key[i]&0x7F;
   26089       if( pa<0x20 ){
   26090         key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
   26091       }else if( pa==0x7F ){
   26092         key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
   26093       }
   26094     }
   26095   }
   26096 #endif
   26097   return SQLITE_OK;
   26098 }
   26099 
   26100 /* writes the host id path to path, path should be an pre-allocated buffer
   26101 ** with enough space for a path
   26102 */
   26103 static void proxyGetHostIDPath(char *path, size_t len){
   26104   strlcpy(path, HOSTIDPATH, len);
   26105 #ifdef SQLITE_TEST
   26106   if( sqlite3_hostid_num>0 ){
   26107     char suffix[2] = "1";
   26108     suffix[0] = suffix[0] + sqlite3_hostid_num;
   26109     strlcat(path, suffix, len);
   26110   }
   26111 #endif
   26112   OSTRACE3("GETHOSTIDPATH  %s pid=%d\n", path, getpid());
   26113 }
   26114 
   26115 /* get the host ID from a sqlite hostid file stored in the
   26116 ** user-specific tmp directory, create the ID if it's not there already
   26117 */
   26118 static int proxyGetHostID(char *pHostID, int *pError){
   26119   int fd;
   26120   char path[MAXPATHLEN];
   26121   size_t len;
   26122   int rc=SQLITE_OK;
   26123 
   26124   proxyGetHostIDPath(path, MAXPATHLEN);
   26125   /* try to create the host ID file, if it already exists read the contents */
   26126   fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
   26127   if( fd<0 ){
   26128     int err=errno;
   26129 
   26130     if( err!=EEXIST ){
   26131 #ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
   26132       fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
   26133               path, strerror(err));
   26134 #endif
   26135       return SQLITE_PERM;
   26136     }
   26137     /* couldn't create the file, read it instead */
   26138     fd = open(path, O_RDONLY|O_EXCL);
   26139     if( fd<0 ){
   26140 #ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
   26141       int err = errno;
   26142       fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
   26143               path, strerror(err));
   26144 #endif
   26145       return SQLITE_PERM;
   26146     }
   26147     len = pread(fd, pHostID, HOSTIDLEN, 0);
   26148     if( len<0 ){
   26149       *pError = errno;
   26150       rc = SQLITE_IOERR_READ;
   26151     }else if( len<HOSTIDLEN ){
   26152       *pError = 0;
   26153       rc = SQLITE_IOERR_SHORT_READ;
   26154     }
   26155     close(fd); /* silently leak the fd if it fails */
   26156     OSTRACE3("GETHOSTID  read %s pid=%d\n", pHostID, getpid());
   26157     return rc;
   26158   }else{
   26159     /* we're creating the host ID file (use a random string of bytes) */
   26160     proxyGenerateHostID(pHostID);
   26161     len = pwrite(fd, pHostID, HOSTIDLEN, 0);
   26162     if( len<0 ){
   26163       *pError = errno;
   26164       rc = SQLITE_IOERR_WRITE;
   26165     }else if( len<HOSTIDLEN ){
   26166       *pError = 0;
   26167       rc = SQLITE_IOERR_WRITE;
   26168     }
   26169     close(fd); /* silently leak the fd if it fails */
   26170     OSTRACE3("GETHOSTID  wrote %s pid=%d\n", pHostID, getpid());
   26171     return rc;
   26172   }
   26173 }
   26174 
   26175 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
   26176   int len;
   26177   int dbLen;
   26178   int i;
   26179 
   26180 #ifdef LOCKPROXYDIR
   26181   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
   26182 #else
   26183 # ifdef _CS_DARWIN_USER_TEMP_DIR
   26184   {
   26185     confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
   26186     len = strlcat(lPath, "sqliteplocks", maxLen);
   26187     if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
   26188       /* if mkdir fails, handle as lock file creation failure */
   26189 #  ifdef SQLITE_DEBUG
   26190       int err = errno;
   26191       if( err!=EEXIST ){
   26192         fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
   26193                 SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
   26194       }
   26195 #  endif
   26196     }else{
   26197       OSTRACE3("GETLOCKPATH  mkdir %s pid=%d\n", lPath, getpid());
   26198     }
   26199 
   26200   }
   26201 # else
   26202   len = strlcpy(lPath, "/tmp/", maxLen);
   26203 # endif
   26204 #endif
   26205 
   26206   if( lPath[len-1]!='/' ){
   26207     len = strlcat(lPath, "/", maxLen);
   26208   }
   26209 
   26210   /* transform the db path to a unique cache name */
   26211   dbLen = (int)strlen(dbPath);
   26212   for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
   26213     char c = dbPath[i];
   26214     lPath[i+len] = (c=='/')?'_':c;
   26215   }
   26216   lPath[i+len]='\0';
   26217   strlcat(lPath, ":auto:", maxLen);
   26218   return SQLITE_OK;
   26219 }
   26220 
   26221 /*
   26222 ** Create a new VFS file descriptor (stored in memory obtained from
   26223 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
   26224 **
   26225 ** The caller is responsible not only for closing the file descriptor
   26226 ** but also for freeing the memory associated with the file descriptor.
   26227 */
   26228 static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
   26229   unixFile *pNew;
   26230   int flags = SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
   26231   int rc = SQLITE_OK;
   26232   sqlite3_vfs dummyVfs;
   26233 
   26234   pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
   26235   if( !pNew ){
   26236     return SQLITE_NOMEM;
   26237   }
   26238   memset(pNew, 0, sizeof(unixFile));
   26239 
   26240   /* Call unixOpen() to open the proxy file. The flags passed to unixOpen()
   26241   ** suggest that the file being opened is a "main database". This is
   26242   ** necessary as other file types do not necessarily support locking. It
   26243   ** is better to use unixOpen() instead of opening the file directly with
   26244   ** open(), as unixOpen() sets up the various mechanisms required to
   26245   ** make sure a call to close() does not cause the system to discard
   26246   ** POSIX locks prematurely.
   26247   **
   26248   ** It is important that the xOpen member of the VFS object passed to
   26249   ** unixOpen() is NULL. This tells unixOpen() may try to open a proxy-file
   26250   ** for the proxy-file (creating a potential infinite loop).
   26251   */
   26252   pUnused = findReusableFd(path, openFlags);
   26253   if( pUnused ){
   26254     fd = pUnused->fd;
   26255   }else{
   26256     pUnused = sqlite3_malloc(sizeof(*pUnused));
   26257     if( !pUnused ){
   26258       return SQLITE_NOMEM;
   26259     }
   26260   }
   26261   if( fd<0 ){
   26262     fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
   26263     terrno = errno;
   26264     if( fd<0 && errno==ENOENT && islockfile ){
   26265       if( proxyCreateLockPath(path) == SQLITE_OK ){
   26266         fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
   26267       }
   26268     }
   26269   }
   26270   if( fd<0 ){
   26271     openFlags = O_RDONLY;
   26272     fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
   26273     terrno = errno;
   26274   }
   26275   if( fd<0 ){
   26276     if( islockfile ){
   26277       return SQLITE_BUSY;
   26278     }
   26279     switch (terrno) {
   26280       case EACCES:
   26281         return SQLITE_PERM;
   26282       case EIO:
   26283         return SQLITE_IOERR_LOCK; /* even though it is the conch */
   26284       default:
   26285         return SQLITE_CANTOPEN_BKPT;
   26286     }
   26287   }
   26288 
   26289   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
   26290   if( pNew==NULL ){
   26291     rc = SQLITE_NOMEM;
   26292     goto end_create_proxy;
   26293   }
   26294   memset(pNew, 0, sizeof(unixFile));
   26295   pNew->openFlags = openFlags;
   26296   dummyVfs.pAppData = (void*)&autolockIoFinder;
   26297   dummyVfs.xOpen = 0;
   26298   rc = unixOpen(&dummyVfs, path, (sqlite3_file *)pNew, flags, &flags);
   26299   if( rc==SQLITE_OK && (flags&SQLITE_OPEN_READONLY) ){
   26300     pNew->pMethod->xClose((sqlite3_file *)pNew);
   26301     rc = SQLITE_CANTOPEN;
   26302   }
   26303 
   26304   if( rc!=SQLITE_OK ){
   26305     sqlite3_free(pNew);
   26306     pNew = 0;
   26307   }
   26308 
   26309   *ppFile = pNew;
   26310   return rc;
   26311 }
   26312 
   26313 /* takes the conch by taking a shared lock and read the contents conch, if
   26314 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
   26315 ** lockPath means that the lockPath in the conch file will be used if the
   26316 ** host IDs match, or a new lock path will be generated automatically
   26317 ** and written to the conch file.
   26318 */
   26319 static int proxyTakeConch(unixFile *pFile){
   26320   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   26321 
   26322   if( pCtx->conchHeld>0 ){
   26323     return SQLITE_OK;
   26324   }else{
   26325     unixFile *conchFile = pCtx->conchFile;
   26326     char testValue[CONCHLEN];
   26327     char conchValue[CONCHLEN];
   26328     char lockPath[MAXPATHLEN];
   26329     char *tLockPath = NULL;
   26330     int rc = SQLITE_OK;
   26331     int readRc = SQLITE_OK;
   26332     int syncPerms = 0;
   26333 
   26334     OSTRACE4("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
   26335              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
   26336 
   26337     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
   26338     if( rc==SQLITE_OK ){
   26339       int pError = 0;
   26340       memset(testValue, 0, CONCHLEN); /* conch is fixed size */
   26341       rc = proxyGetHostID(testValue, &pError);
   26342       if( (rc&0xff)==SQLITE_IOERR ){
   26343         pFile->lastErrno = pError;
   26344       }
   26345       if( pCtx->lockProxyPath ){
   26346         strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
   26347       }
   26348     }
   26349     if( rc!=SQLITE_OK ){
   26350       goto end_takeconch;
   26351     }
   26352 
   26353     readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
   26354     if( readRc!=SQLITE_IOERR_SHORT_READ ){
   26355       if( readRc!=SQLITE_OK ){
   26356         if( (rc&0xff)==SQLITE_IOERR ){
   26357           pFile->lastErrno = conchFile->lastErrno;
   26358         }
   26359         rc = readRc;
   26360         goto end_takeconch;
   26361       }
   26362       /* if the conch has data compare the contents */
   26363       if( !pCtx->lockProxyPath ){
   26364         /* for auto-named local lock file, just check the host ID and we'll
   26365          ** use the local lock file path that's already in there */
   26366         if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
   26367           tLockPath = (char *)&conchValue[HOSTIDLEN];
   26368           goto end_takeconch;
   26369         }
   26370       }else{
   26371         /* we've got the conch if conchValue matches our path and host ID */
   26372         if( !memcmp(testValue, conchValue, CONCHLEN) ){
   26373           goto end_takeconch;
   26374         }
   26375       }
   26376     }else{
   26377       /* a short read means we're "creating" the conch (even though it could
   26378       ** have been user-intervention), if we acquire the exclusive lock,
   26379       ** we'll try to match the current on-disk permissions of the database
   26380       */
   26381       syncPerms = 1;
   26382     }
   26383 
   26384     /* either conch was emtpy or didn't match */
   26385     if( !pCtx->lockProxyPath ){
   26386       proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
   26387       tLockPath = lockPath;
   26388       strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
   26389     }
   26390 
   26391     /* update conch with host and path (this will fail if other process
   26392      ** has a shared lock already) */
   26393     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
   26394     if( rc==SQLITE_OK ){
   26395       rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
   26396       if( rc==SQLITE_OK && syncPerms ){
   26397         struct stat buf;
   26398         int err = fstat(pFile->h, &buf);
   26399         if( err==0 ){
   26400           /* try to match the database file permissions, ignore failure */
   26401 #ifndef SQLITE_PROXY_DEBUG
   26402           fchmod(conchFile->h, buf.st_mode);
   26403 #else
   26404           if( fchmod(conchFile->h, buf.st_mode)!=0 ){
   26405             int code = errno;
   26406             fprintf(stderr, "fchmod %o FAILED with %d %s\n",
   26407                              buf.st_mode, code, strerror(code));
   26408           } else {
   26409             fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
   26410           }
   26411         }else{
   26412           int code = errno;
   26413           fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
   26414                           err, code, strerror(code));
   26415 #endif
   26416         }
   26417       }
   26418     }
   26419     conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
   26420 
   26421 end_takeconch:
   26422     OSTRACE2("TRANSPROXY: CLOSE  %d\n", pFile->h);
   26423     if( rc==SQLITE_OK && pFile->openFlags ){
   26424       if( pFile->h>=0 ){
   26425 #ifdef STRICT_CLOSE_ERROR
   26426         if( close(pFile->h) ){
   26427           pFile->lastErrno = errno;
   26428           return SQLITE_IOERR_CLOSE;
   26429         }
   26430 #else
   26431         close(pFile->h); /* silently leak fd if fail */
   26432 #endif
   26433       }
   26434       pFile->h = -1;
   26435       int fd = open(pCtx->dbPath, pFile->openFlags,
   26436                     SQLITE_DEFAULT_FILE_PERMISSIONS);
   26437       OSTRACE2("TRANSPROXY: OPEN  %d\n", fd);
   26438       if( fd>=0 ){
   26439         pFile->h = fd;
   26440       }else{
   26441         rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
   26442                                during locking */
   26443       }
   26444     }
   26445     if( rc==SQLITE_OK && !pCtx->lockProxy ){
   26446       char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
   26447       /* ACS: Need to make a copy of path sometimes */
   26448       rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
   26449     }
   26450     if( rc==SQLITE_OK ){
   26451       pCtx->conchHeld = 1;
   26452 
   26453       if( tLockPath ){
   26454         pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
   26455         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
   26456           ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
   26457                      pCtx->lockProxyPath;
   26458         }
   26459       }
   26460 >>>>>>> BEGIN MERGE CONFLICT
   26461 
   26462       /* if the conch isn't writable and doesn't match, we can't take it */
   26463       if( (conchFile->openFlags&O_RDWR) == 0 ){
   26464         rc = SQLITE_BUSY;
   26465         goto end_takeconch;
   26466       }
   26467 
   26468       /* either the conch didn't match or we need to create a new one */
   26469       if( !pCtx->lockProxyPath ){
   26470         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
   26471         tempLockPath = lockPath;
   26472         /* create a copy of the lock path _only_ if the conch is taken */
   26473       }
   26474 
   26475       /* update conch with host and path (this will fail if other process
   26476       ** has a shared lock already), if the host id matches, use the big
   26477       ** stick.
   26478       */
   26479       futimes(conchFile->h, NULL);
   26480       if( hostIdMatch && !createConch ){
   26481         if( conchFile->pLock && conchFile->pLock->cnt>1 ){
   26482           /* We are trying for an exclusive lock but another thread in this
   26483            ** same process is still holding a shared lock. */
   26484           rc = SQLITE_BUSY;
   26485         } else {
   26486           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
   26487         }
   26488       }else{
   26489         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
   26490       }
   26491       if( rc==SQLITE_OK ){
   26492         char writeBuffer[PROXY_MAXCONCHLEN];
   26493         int writeSize = 0;
   26494 
   26495         writeBuffer[0] = (char)PROXY_CONCHVERSION;
   26496         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
   26497         if( pCtx->lockProxyPath!=NULL ){
   26498           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
   26499         }else{
   26500           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
   26501         }
   26502         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
   26503         ftruncate(conchFile->h, writeSize);
   26504         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
   26505         fsync(conchFile->h);
   26506         /* If we created a new conch file (not just updated the contents of a
   26507          ** valid conch file), try to match the permissions of the database
   26508          */
   26509         if( rc==SQLITE_OK && createConch ){
   26510           struct stat buf;
   26511           int err = fstat(pFile->h, &buf);
   26512           if( err==0 ){
   26513             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
   26514                                         S_IROTH|S_IWOTH);
   26515             /* try to match the database file R/W permissions, ignore failure */
   26516 #ifndef SQLITE_PROXY_DEBUG
   26517             fchmod(conchFile->h, cmode);
   26518 #else
   26519             if( fchmod(conchFile->h, cmode)!=0 ){
   26520               int code = errno;
   26521               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
   26522                       cmode, code, strerror(code));
   26523             } else {
   26524               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
   26525             }
   26526           }else{
   26527             int code = errno;
   26528             fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
   26529                     err, code, strerror(code));
   26530 #endif
   26531           }
   26532         }
   26533       }
   26534       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
   26535 
   26536     end_takeconch:
   26537       OSTRACE2("TRANSPROXY: CLOSE  %d\n", pFile->h);
   26538       if( rc==SQLITE_OK && pFile->openFlags ){
   26539         if( pFile->h>=0 ){
   26540 #ifdef STRICT_CLOSE_ERROR
   26541           if( close(pFile->h) ){
   26542             pFile->lastErrno = errno;
   26543             return SQLITE_IOERR_CLOSE;
   26544           }
   26545 #else
   26546           close(pFile->h); /* silently leak fd if fail */
   26547 #endif
   26548         }
   26549         pFile->h = -1;
   26550         int fd = open(pCtx->dbPath, pFile->openFlags,
   26551                       SQLITE_DEFAULT_FILE_PERMISSIONS);
   26552         OSTRACE2("TRANSPROXY: OPEN  %d\n", fd);
   26553         if( fd>=0 ){
   26554           pFile->h = fd;
   26555         }else{
   26556           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
   26557            during locking */
   26558         }
   26559       }
   26560       if( rc==SQLITE_OK && !pCtx->lockProxy ){
   26561         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
   26562         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
   26563         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
   26564           /* we couldn't create the proxy lock file with the old lock file path
   26565            ** so try again via auto-naming
   26566            */
   26567           forceNewLockPath = 1;
   26568           tryOldLockPath = 0;
   26569           continue; /* go back to the do {} while start point, try again */
   26570         }
   26571       }
   26572       if( rc==SQLITE_OK ){
   26573         /* Need to make a copy of path if we extracted the value
   26574          ** from the conch file or the path was allocated on the stack
   26575          */
   26576         if( tempLockPath ){
   26577           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
   26578           if( !pCtx->lockProxyPath ){
   26579             rc = SQLITE_NOMEM;
   26580           }
   26581         }
   26582       }
   26583       if( rc==SQLITE_OK ){
   26584         pCtx->conchHeld = 1;
   26585 
   26586         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
   26587           afpLockingContext *afpCtx;
   26588           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
   26589           afpCtx->dbPath = pCtx->lockProxyPath;
   26590         }
   26591       } else {
   26592         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   26593       }
   26594       OSTRACE3("TAKECONCH  %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
   26595       return rc;
   26596     } while (1); /* in case we need to retry the :auto: lock file - we should never get here except via the 'continue' call. */
   26597 ============================
   26598     } else {
   26599       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   26600     }
   26601     OSTRACE3("TAKECONCH  %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
   26602     return rc;
   26603 <<<<<<< END MERGE CONFLICT
   26604   }
   26605 }
   26606 
   26607 /*
   26608 ** If pFile holds a lock on a conch file, then release that lock.
   26609 */
   26610 static int proxyReleaseConch(unixFile *pFile){
   26611   int rc;                     /* Subroutine return code */
   26612   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
   26613   unixFile *conchFile;        /* Name of the conch file */
   26614 
   26615   pCtx = (proxyLockingContext *)pFile->lockingContext;
   26616   conchFile = pCtx->conchFile;
   26617   OSTRACE4("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
   26618            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
   26619            getpid());
   26620   pCtx->conchHeld = 0;
   26621   rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   26622   OSTRACE3("RELEASECONCH  %d %s\n", conchFile->h,
   26623            (rc==SQLITE_OK ? "ok" : "failed"));
   26624   return rc;
   26625 }
   26626 
   26627 /*
   26628 ** Given the name of a database file, compute the name of its conch file.
   26629 ** Store the conch filename in memory obtained from sqlite3_malloc().
   26630 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
   26631 ** or SQLITE_NOMEM if unable to obtain memory.
   26632 **
   26633 ** The caller is responsible for ensuring that the allocated memory
   26634 ** space is eventually freed.
   26635 **
   26636 ** *pConchPath is set to NULL if a memory allocation error occurs.
   26637 */
   26638 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
   26639   int i;                        /* Loop counter */
   26640   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
   26641   char *conchPath;              /* buffer in which to construct conch name */
   26642 
   26643   /* Allocate space for the conch filename and initialize the name to
   26644   ** the name of the original database file. */
   26645   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
   26646   if( conchPath==0 ){
   26647     return SQLITE_NOMEM;
   26648   }
   26649   memcpy(conchPath, dbPath, len+1);
   26650 
   26651   /* now insert a "." before the last / character */
   26652   for( i=(len-1); i>=0; i-- ){
   26653     if( conchPath[i]=='/' ){
   26654       i++;
   26655       break;
   26656     }
   26657   }
   26658   conchPath[i]='.';
   26659   while ( i<len ){
   26660     conchPath[i+1]=dbPath[i];
   26661     i++;
   26662   }
   26663 
   26664   /* append the "-conch" suffix to the file */
   26665   memcpy(&conchPath[i+1], "-conch", 7);
   26666   assert( (int)strlen(conchPath) == len+7 );
   26667 
   26668   return SQLITE_OK;
   26669 }
   26670 
   26671 
   26672 /* Takes a fully configured proxy locking-style unix file and switches
   26673 ** the local lock file path
   26674 */
   26675 static int switchLockProxyPath(unixFile *pFile, const char *path) {
   26676   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
   26677   char *oldPath = pCtx->lockProxyPath;
   26678   int rc = SQLITE_OK;
   26679 
   26680   if( pFile->locktype!=NO_LOCK ){
   26681     return SQLITE_BUSY;
   26682   }
   26683 
   26684   /* nothing to do if the path is NULL, :auto: or matches the existing path */
   26685   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
   26686     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
   26687     return SQLITE_OK;
   26688   }else{
   26689     unixFile *lockProxy = pCtx->lockProxy;
   26690     pCtx->lockProxy=NULL;
   26691     pCtx->conchHeld = 0;
   26692     if( lockProxy!=NULL ){
   26693       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
   26694       if( rc ) return rc;
   26695       sqlite3_free(lockProxy);
   26696     }
   26697     sqlite3_free(oldPath);
   26698     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
   26699   }
   26700 
   26701   return rc;
   26702 }
   26703 
   26704 /*
   26705 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
   26706 ** is a string buffer at least MAXPATHLEN+1 characters in size.
   26707 **
   26708 ** This routine find the filename associated with pFile and writes it
   26709 ** int dbPath.
   26710 */
   26711 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
   26712 #if defined(__APPLE__)
   26713   if( pFile->pMethod == &afpIoMethods ){
   26714     /* afp style keeps a reference to the db path in the filePath field
   26715     ** of the struct */
   26716     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
   26717     strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
   26718   }else
   26719 #endif
   26720   if( pFile->pMethod == &dotlockIoMethods ){
   26721     /* dot lock style uses the locking context to store the dot lock
   26722     ** file path */
   26723     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
   26724     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
   26725   }else{
   26726     /* all other styles use the locking context to store the db file path */
   26727     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
   26728     strcpy(dbPath, (char *)pFile->lockingContext);
   26729   }
   26730   return SQLITE_OK;
   26731 }
   26732 
   26733 /*
   26734 ** Takes an already filled in unix file and alters it so all file locking
   26735 ** will be performed on the local proxy lock file.  The following fields
   26736 ** are preserved in the locking context so that they can be restored and
   26737 ** the unix structure properly cleaned up at close time:
   26738 **  ->lockingContext
   26739 **  ->pMethod
   26740 */
   26741 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
   26742   proxyLockingContext *pCtx;
   26743   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
   26744   char *lockPath=NULL;
   26745   int rc = SQLITE_OK;
   26746 
   26747   if( pFile->locktype!=NO_LOCK ){
   26748     return SQLITE_BUSY;
   26749   }
   26750   proxyGetDbPathForUnixFile(pFile, dbPath);
   26751   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
   26752     lockPath=NULL;
   26753   }else{
   26754     lockPath=(char *)path;
   26755   }
   26756 
   26757   OSTRACE4("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
   26758            (lockPath ? lockPath : ":auto:"), getpid());
   26759 
   26760   pCtx = sqlite3_malloc( sizeof(*pCtx) );
   26761   if( pCtx==0 ){
   26762     return SQLITE_NOMEM;
   26763   }
   26764   memset(pCtx, 0, sizeof(*pCtx));
   26765 
   26766   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
   26767   if( rc==SQLITE_OK ){
   26768     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
   26769   }
   26770   if( rc==SQLITE_OK && lockPath ){
   26771     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
   26772   }
   26773 
   26774   if( rc==SQLITE_OK ){
   26775     /* all memory is allocated, proxys are created and assigned,
   26776     ** switch the locking context and pMethod then return.
   26777     */
   26778     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
   26779     pCtx->oldLockingContext = pFile->lockingContext;
   26780     pFile->lockingContext = pCtx;
   26781     pCtx->pOldMethod = pFile->pMethod;
   26782     pFile->pMethod = &proxyIoMethods;
   26783   }else{
   26784     if( pCtx->conchFile ){
   26785       rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
   26786       if( rc ) return rc;
   26787       sqlite3_free(pCtx->conchFile);
   26788     }
   26789     sqlite3_free(pCtx->conchFilePath);
   26790     sqlite3_free(pCtx);
   26791   }
   26792   OSTRACE3("TRANSPROXY  %d %s\n", pFile->h,
   26793            (rc==SQLITE_OK ? "ok" : "failed"));
   26794   return rc;
   26795 }
   26796 
   26797 
   26798 /*
   26799 ** This routine handles sqlite3_file_control() calls that are specific
   26800 ** to proxy locking.
   26801 */
   26802 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
   26803   switch( op ){
   26804     case SQLITE_GET_LOCKPROXYFILE: {
   26805       unixFile *pFile = (unixFile*)id;
   26806       if( pFile->pMethod == &proxyIoMethods ){
   26807         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
   26808         proxyTakeConch(pFile);
   26809         if( pCtx->lockProxyPath ){
   26810           *(const char **)pArg = pCtx->lockProxyPath;
   26811         }else{
   26812           *(const char **)pArg = ":auto: (not held)";
   26813         }
   26814       } else {
   26815         *(const char **)pArg = NULL;
   26816       }
   26817       return SQLITE_OK;
   26818     }
   26819     case SQLITE_SET_LOCKPROXYFILE: {
   26820       unixFile *pFile = (unixFile*)id;
   26821       int rc = SQLITE_OK;
   26822       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
   26823       if( pArg==NULL || (const char *)pArg==0 ){
   26824         if( isProxyStyle ){
   26825           /* turn off proxy locking - not supported */
   26826           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
   26827         }else{
   26828           /* turn off proxy locking - already off - NOOP */
   26829           rc = SQLITE_OK;
   26830         }
   26831       }else{
   26832         const char *proxyPath = (const char *)pArg;
   26833         if( isProxyStyle ){
   26834           proxyLockingContext *pCtx =
   26835             (proxyLockingContext*)pFile->lockingContext;
   26836           if( !strcmp(pArg, ":auto:")
   26837            || (pCtx->lockProxyPath &&
   26838                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
   26839           ){
   26840             rc = SQLITE_OK;
   26841           }else{
   26842             rc = switchLockProxyPath(pFile, proxyPath);
   26843           }
   26844         }else{
   26845           /* turn on proxy file locking */
   26846           rc = proxyTransformUnixFile(pFile, proxyPath);
   26847         }
   26848       }
   26849       return rc;
   26850     }
   26851     default: {
   26852       assert( 0 );  /* The call assures that only valid opcodes are sent */
   26853     }
   26854   }
   26855   /*NOTREACHED*/
   26856   return SQLITE_ERROR;
   26857 }
   26858 
   26859 /*
   26860 ** Within this division (the proxying locking implementation) the procedures
   26861 ** above this point are all utilities.  The lock-related methods of the
   26862 ** proxy-locking sqlite3_io_method object follow.
   26863 */
   26864 
   26865 
   26866 /*
   26867 ** This routine checks if there is a RESERVED lock held on the specified
   26868 ** file by this or any other process. If such a lock is held, set *pResOut
   26869 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   26870 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   26871 */
   26872 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
   26873   unixFile *pFile = (unixFile*)id;
   26874   int rc = proxyTakeConch(pFile);
   26875   if( rc==SQLITE_OK ){
   26876     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   26877     unixFile *proxy = pCtx->lockProxy;
   26878     return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
   26879   }
   26880   return rc;
   26881 }
   26882 
   26883 /*
   26884 ** Lock the file with the lock specified by parameter locktype - one
   26885 ** of the following:
   26886 **
   26887 **     (1) SHARED_LOCK
   26888 **     (2) RESERVED_LOCK
   26889 **     (3) PENDING_LOCK
   26890 **     (4) EXCLUSIVE_LOCK
   26891 **
   26892 ** Sometimes when requesting one lock state, additional lock states
   26893 ** are inserted in between.  The locking might fail on one of the later
   26894 ** transitions leaving the lock state different from what it started but
   26895 ** still short of its goal.  The following chart shows the allowed
   26896 ** transitions and the inserted intermediate states:
   26897 **
   26898 **    UNLOCKED -> SHARED
   26899 **    SHARED -> RESERVED
   26900 **    SHARED -> (PENDING) -> EXCLUSIVE
   26901 **    RESERVED -> (PENDING) -> EXCLUSIVE
   26902 **    PENDING -> EXCLUSIVE
   26903 **
   26904 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   26905 ** routine to lower a locking level.
   26906 */
   26907 static int proxyLock(sqlite3_file *id, int locktype) {
   26908   unixFile *pFile = (unixFile*)id;
   26909   int rc = proxyTakeConch(pFile);
   26910   if( rc==SQLITE_OK ){
   26911     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   26912     unixFile *proxy = pCtx->lockProxy;
   26913     rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
   26914     pFile->locktype = proxy->locktype;
   26915   }
   26916   return rc;
   26917 }
   26918 
   26919 
   26920 /*
   26921 ** Lower the locking level on file descriptor pFile to locktype.  locktype
   26922 ** must be either NO_LOCK or SHARED_LOCK.
   26923 **
   26924 ** If the locking level of the file descriptor is already at or below
   26925 ** the requested locking level, this routine is a no-op.
   26926 */
   26927 static int proxyUnlock(sqlite3_file *id, int locktype) {
   26928   unixFile *pFile = (unixFile*)id;
   26929   int rc = proxyTakeConch(pFile);
   26930   if( rc==SQLITE_OK ){
   26931     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   26932     unixFile *proxy = pCtx->lockProxy;
   26933     rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
   26934     pFile->locktype = proxy->locktype;
   26935   }
   26936   return rc;
   26937 }
   26938 
   26939 /*
   26940 ** Close a file that uses proxy locks.
   26941 */
   26942 static int proxyClose(sqlite3_file *id) {
   26943   if( id ){
   26944     unixFile *pFile = (unixFile*)id;
   26945     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   26946     unixFile *lockProxy = pCtx->lockProxy;
   26947     unixFile *conchFile = pCtx->conchFile;
   26948     int rc = SQLITE_OK;
   26949 
   26950     if( lockProxy ){
   26951       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
   26952       if( rc ) return rc;
   26953       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
   26954       if( rc ) return rc;
   26955       sqlite3_free(lockProxy);
   26956       pCtx->lockProxy = 0;
   26957     }
   26958     if( conchFile ){
   26959       if( pCtx->conchHeld ){
   26960         rc = proxyReleaseConch(pFile);
   26961         if( rc ) return rc;
   26962       }
   26963       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
   26964       if( rc ) return rc;
   26965       sqlite3_free(conchFile);
   26966     }
   26967     sqlite3_free(pCtx->lockProxyPath);
   26968     sqlite3_free(pCtx->conchFilePath);
   26969     sqlite3_free(pCtx->dbPath);
   26970     /* restore the original locking context and pMethod then close it */
   26971     pFile->lockingContext = pCtx->oldLockingContext;
   26972     pFile->pMethod = pCtx->pOldMethod;
   26973     sqlite3_free(pCtx);
   26974     return pFile->pMethod->xClose(id);
   26975   }
   26976   return SQLITE_OK;
   26977 }
   26978 
   26979 
   26980 
   26981 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   26982 /*
   26983 ** The proxy locking style is intended for use with AFP filesystems.
   26984 ** And since AFP is only supported on MacOSX, the proxy locking is also
   26985 ** restricted to MacOSX.
   26986 **
   26987 **
   26988 ******************* End of the proxy lock implementation **********************
   26989 ******************************************************************************/
   26990 
   26991 /*
   26992 ** Initialize the operating system interface.
   26993 **
   26994 ** This routine registers all VFS implementations for unix-like operating
   26995 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
   26996 ** should be the only routines in this file that are visible from other
   26997 ** files.
   26998 **
   26999 ** This routine is called once during SQLite initialization and by a
   27000 ** single thread.  The memory allocation and mutex subsystems have not
   27001 ** necessarily been initialized when this routine is called, and so they
   27002 ** should not be used.
   27003 */
   27004 SQLITE_API int sqlite3_os_init(void){
   27005   /*
   27006   ** The following macro defines an initializer for an sqlite3_vfs object.
   27007   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
   27008   ** to the "finder" function.  (pAppData is a pointer to a pointer because
   27009   ** silly C90 rules prohibit a void* from being cast to a function pointer
   27010   ** and so we have to go through the intermediate pointer to avoid problems
   27011   ** when compiling with -pedantic-errors on GCC.)
   27012   **
   27013   ** The FINDER parameter to this macro is the name of the pointer to the
   27014   ** finder-function.  The finder-function returns a pointer to the
   27015   ** sqlite_io_methods object that implements the desired locking
   27016   ** behaviors.  See the division above that contains the IOMETHODS
   27017   ** macro for addition information on finder-functions.
   27018   **
   27019   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
   27020   ** object.  But the "autolockIoFinder" available on MacOSX does a little
   27021   ** more than that; it looks at the filesystem type that hosts the
   27022   ** database file and tries to choose an locking method appropriate for
   27023   ** that filesystem time.
   27024   */
   27025   #define UNIXVFS(VFSNAME, FINDER) {                        \
   27026     1,                    /* iVersion */                    \
   27027     sizeof(unixFile),     /* szOsFile */                    \
   27028     MAX_PATHNAME,         /* mxPathname */                  \
   27029     0,                    /* pNext */                       \
   27030     VFSNAME,              /* zName */                       \
   27031     (void*)&FINDER,       /* pAppData */                    \
   27032     unixOpen,             /* xOpen */                       \
   27033     unixDelete,           /* xDelete */                     \
   27034     unixAccess,           /* xAccess */                     \
   27035     unixFullPathname,     /* xFullPathname */               \
   27036     unixDlOpen,           /* xDlOpen */                     \
   27037     unixDlError,          /* xDlError */                    \
   27038     unixDlSym,            /* xDlSym */                      \
   27039     unixDlClose,          /* xDlClose */                    \
   27040     unixRandomness,       /* xRandomness */                 \
   27041     unixSleep,            /* xSleep */                      \
   27042     unixCurrentTime,      /* xCurrentTime */                \
   27043     unixGetLastError      /* xGetLastError */               \
   27044   }
   27045 
   27046   /*
   27047   ** All default VFSes for unix are contained in the following array.
   27048   **
   27049   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
   27050   ** by the SQLite core when the VFS is registered.  So the following
   27051   ** array cannot be const.
   27052   */
   27053   static sqlite3_vfs aVfs[] = {
   27054 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
   27055     UNIXVFS("unix",          autolockIoFinder ),
   27056 #else
   27057     UNIXVFS("unix",          posixIoFinder ),
   27058 #endif
   27059     UNIXVFS("unix-none",     nolockIoFinder ),
   27060     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
   27061     UNIXVFS("unix-wfl",      posixWflIoFinder ),
   27062 #if OS_VXWORKS
   27063     UNIXVFS("unix-namedsem", semIoFinder ),
   27064 #endif
   27065 #if SQLITE_ENABLE_LOCKING_STYLE
   27066     UNIXVFS("unix-posix",    posixIoFinder ),
   27067 #if !OS_VXWORKS
   27068     UNIXVFS("unix-flock",    flockIoFinder ),
   27069 #endif
   27070 #endif
   27071 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   27072     UNIXVFS("unix-afp",      afpIoFinder ),
   27073     UNIXVFS("unix-proxy",    proxyIoFinder ),
   27074 #endif
   27075   };
   27076   unsigned int i;          /* Loop counter */
   27077 
   27078   /* Register all VFSes defined in the aVfs[] array */
   27079   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
   27080     sqlite3_vfs_register(&aVfs[i], i==0);
   27081   }
   27082   return SQLITE_OK;
   27083 }
   27084 
   27085 /*
   27086 ** Shutdown the operating system interface.
   27087 **
   27088 ** Some operating systems might need to do some cleanup in this routine,
   27089 ** to release dynamically allocated objects.  But not on unix.
   27090 ** This routine is a no-op for unix.
   27091 */
   27092 SQLITE_API int sqlite3_os_end(void){
   27093   return SQLITE_OK;
   27094 }
   27095 
   27096 #endif /* SQLITE_OS_UNIX */
   27097 
   27098 /************** End of os_unix.c *********************************************/
   27099 /************** Begin file os_win.c ******************************************/
   27100 /*
   27101 ** 2004 May 22
   27102 **
   27103 ** The author disclaims copyright to this source code.  In place of
   27104 ** a legal notice, here is a blessing:
   27105 **
   27106 **    May you do good and not evil.
   27107 **    May you find forgiveness for yourself and forgive others.
   27108 **    May you share freely, never taking more than you give.
   27109 **
   27110 ******************************************************************************
   27111 **
   27112 ** This file contains code that is specific to windows.
   27113 */
   27114 #if SQLITE_OS_WIN               /* This file is used for windows only */
   27115 
   27116 
   27117 /*
   27118 ** A Note About Memory Allocation:
   27119 **
   27120 ** This driver uses malloc()/free() directly rather than going through
   27121 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
   27122 ** are designed for use on embedded systems where memory is scarce and
   27123 ** malloc failures happen frequently.  Win32 does not typically run on
   27124 ** embedded systems, and when it does the developers normally have bigger
   27125 ** problems to worry about than running out of memory.  So there is not
   27126 ** a compelling need to use the wrappers.
   27127 **
   27128 ** But there is a good reason to not use the wrappers.  If we use the
   27129 ** wrappers then we will get simulated malloc() failures within this
   27130 ** driver.  And that causes all kinds of problems for our tests.  We
   27131 ** could enhance SQLite to deal with simulated malloc failures within
   27132 ** the OS driver, but the code to deal with those failure would not
   27133 ** be exercised on Linux (which does not need to malloc() in the driver)
   27134 ** and so we would have difficulty writing coverage tests for that
   27135 ** code.  Better to leave the code out, we think.
   27136 **
   27137 ** The point of this discussion is as follows:  When creating a new
   27138 ** OS layer for an embedded system, if you use this file as an example,
   27139 ** avoid the use of malloc()/free().  Those routines work ok on windows
   27140 ** desktops but not so well in embedded systems.
   27141 */
   27142 
   27143 #include <winbase.h>
   27144 
   27145 #ifdef __CYGWIN__
   27146 # include <sys/cygwin.h>
   27147 #endif
   27148 
   27149 /*
   27150 ** Macros used to determine whether or not to use threads.
   27151 */
   27152 #if defined(THREADSAFE) && THREADSAFE
   27153 # define SQLITE_W32_THREADS 1
   27154 #endif
   27155 
   27156 /*
   27157 ** Include code that is common to all os_*.c files
   27158 */
   27159 /************** Include os_common.h in the middle of os_win.c ****************/
   27160 /************** Begin file os_common.h ***************************************/
   27161 /*
   27162 ** 2004 May 22
   27163 **
   27164 ** The author disclaims copyright to this source code.  In place of
   27165 ** a legal notice, here is a blessing:
   27166 **
   27167 **    May you do good and not evil.
   27168 **    May you find forgiveness for yourself and forgive others.
   27169 **    May you share freely, never taking more than you give.
   27170 **
   27171 ******************************************************************************
   27172 **
   27173 ** This file contains macros and a little bit of code that is common to
   27174 ** all of the platform-specific files (os_*.c) and is #included into those
   27175 ** files.
   27176 **
   27177 ** This file should be #included by the os_*.c files only.  It is not a
   27178 ** general purpose header file.
   27179 */
   27180 #ifndef _OS_COMMON_H_
   27181 #define _OS_COMMON_H_
   27182 
   27183 /*
   27184 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   27185 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   27186 ** switch.  The following code should catch this problem at compile-time.
   27187 */
   27188 #ifdef MEMORY_DEBUG
   27189 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   27190 #endif
   27191 
   27192 #ifdef SQLITE_DEBUG
   27193 SQLITE_PRIVATE int sqlite3OSTrace = 0;
   27194 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
   27195 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
   27196 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
   27197 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
   27198 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
   27199 #define OSTRACE6(X,Y,Z,A,B,C) \
   27200     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
   27201 #define OSTRACE7(X,Y,Z,A,B,C,D) \
   27202     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
   27203 #else
   27204 #define OSTRACE1(X)
   27205 #define OSTRACE2(X,Y)
   27206 #define OSTRACE3(X,Y,Z)
   27207 #define OSTRACE4(X,Y,Z,A)
   27208 #define OSTRACE5(X,Y,Z,A,B)
   27209 #define OSTRACE6(X,Y,Z,A,B,C)
   27210 #define OSTRACE7(X,Y,Z,A,B,C,D)
   27211 #endif
   27212 
   27213 /*
   27214 ** Macros for performance tracing.  Normally turned off.  Only works
   27215 ** on i486 hardware.
   27216 */
   27217 #ifdef SQLITE_PERFORMANCE_TRACE
   27218 
   27219 /*
   27220 ** hwtime.h contains inline assembler code for implementing
   27221 ** high-performance timing routines.
   27222 */
   27223 /************** Include hwtime.h in the middle of os_common.h ****************/
   27224 /************** Begin file hwtime.h ******************************************/
   27225 /*
   27226 ** 2008 May 27
   27227 **
   27228 ** The author disclaims copyright to this source code.  In place of
   27229 ** a legal notice, here is a blessing:
   27230 **
   27231 **    May you do good and not evil.
   27232 **    May you find forgiveness for yourself and forgive others.
   27233 **    May you share freely, never taking more than you give.
   27234 **
   27235 ******************************************************************************
   27236 **
   27237 ** This file contains inline asm code for retrieving "high-performance"
   27238 ** counters for x86 class CPUs.
   27239 */
   27240 #ifndef _HWTIME_H_
   27241 #define _HWTIME_H_
   27242 
   27243 /*
   27244 ** The following routine only works on pentium-class (or newer) processors.
   27245 ** It uses the RDTSC opcode to read the cycle count value out of the
   27246 ** processor and returns that value.  This can be used for high-res
   27247 ** profiling.
   27248 */
   27249 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   27250       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   27251 
   27252   #if defined(__GNUC__)
   27253 
   27254   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   27255      unsigned int lo, hi;
   27256      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   27257      return (sqlite_uint64)hi << 32 | lo;
   27258   }
   27259 
   27260   #elif defined(_MSC_VER)
   27261 
   27262   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   27263      __asm {
   27264         rdtsc
   27265         ret       ; return value at EDX:EAX
   27266      }
   27267   }
   27268 
   27269   #endif
   27270 
   27271 #elif (defined(__GNUC__) && defined(__x86_64__))
   27272 
   27273   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   27274       unsigned long val;
   27275       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   27276       return val;
   27277   }
   27278 
   27279 #elif (defined(__GNUC__) && defined(__ppc__))
   27280 
   27281   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   27282       unsigned long long retval;
   27283       unsigned long junk;
   27284       __asm__ __volatile__ ("\n\
   27285           1:      mftbu   %1\n\
   27286                   mftb    %L0\n\
   27287                   mftbu   %0\n\
   27288                   cmpw    %0,%1\n\
   27289                   bne     1b"
   27290                   : "=r" (retval), "=r" (junk));
   27291       return retval;
   27292   }
   27293 
   27294 #else
   27295 
   27296   #error Need implementation of sqlite3Hwtime() for your platform.
   27297 
   27298   /*
   27299   ** To compile without implementing sqlite3Hwtime() for your platform,
   27300   ** you can remove the above #error and use the following
   27301   ** stub function.  You will lose timing support for many
   27302   ** of the debugging and testing utilities, but it should at
   27303   ** least compile and run.
   27304   */
   27305 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   27306 
   27307 #endif
   27308 
   27309 #endif /* !defined(_HWTIME_H_) */
   27310 
   27311 /************** End of hwtime.h **********************************************/
   27312 /************** Continuing where we left off in os_common.h ******************/
   27313 
   27314 static sqlite_uint64 g_start;
   27315 static sqlite_uint64 g_elapsed;
   27316 #define TIMER_START       g_start=sqlite3Hwtime()
   27317 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   27318 #define TIMER_ELAPSED     g_elapsed
   27319 #else
   27320 #define TIMER_START
   27321 #define TIMER_END
   27322 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   27323 #endif
   27324 
   27325 /*
   27326 ** If we compile with the SQLITE_TEST macro set, then the following block
   27327 ** of code will give us the ability to simulate a disk I/O error.  This
   27328 ** is used for testing the I/O recovery logic.
   27329 */
   27330 #ifdef SQLITE_TEST
   27331 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   27332 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   27333 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   27334 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   27335 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   27336 SQLITE_API int sqlite3_diskfull_pending = 0;
   27337 SQLITE_API int sqlite3_diskfull = 0;
   27338 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   27339 #define SimulateIOError(CODE)  \
   27340   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   27341        || sqlite3_io_error_pending-- == 1 )  \
   27342               { local_ioerr(); CODE; }
   27343 static void local_ioerr(){
   27344   IOTRACE(("IOERR\n"));
   27345   sqlite3_io_error_hit++;
   27346   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   27347 }
   27348 #define SimulateDiskfullError(CODE) \
   27349    if( sqlite3_diskfull_pending ){ \
   27350      if( sqlite3_diskfull_pending == 1 ){ \
   27351        local_ioerr(); \
   27352        sqlite3_diskfull = 1; \
   27353        sqlite3_io_error_hit = 1; \
   27354        CODE; \
   27355      }else{ \
   27356        sqlite3_diskfull_pending--; \
   27357      } \
   27358    }
   27359 #else
   27360 #define SimulateIOErrorBenign(X)
   27361 #define SimulateIOError(A)
   27362 #define SimulateDiskfullError(A)
   27363 #endif
   27364 
   27365 /*
   27366 ** When testing, keep a count of the number of open files.
   27367 */
   27368 #ifdef SQLITE_TEST
   27369 SQLITE_API int sqlite3_open_file_count = 0;
   27370 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   27371 #else
   27372 #define OpenCounter(X)
   27373 #endif
   27374 
   27375 #endif /* !defined(_OS_COMMON_H_) */
   27376 
   27377 /************** End of os_common.h *******************************************/
   27378 /************** Continuing where we left off in os_win.c *********************/
   27379 
   27380 /*
   27381 ** Some microsoft compilers lack this definition.
   27382 */
   27383 #ifndef INVALID_FILE_ATTRIBUTES
   27384 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
   27385 #endif
   27386 
   27387 /*
   27388 ** Determine if we are dealing with WindowsCE - which has a much
   27389 ** reduced API.
   27390 */
   27391 #if SQLITE_OS_WINCE
   27392 # define AreFileApisANSI() 1
   27393 # define FormatMessageW(a,b,c,d,e,f,g) 0
   27394 #endif
   27395 
   27396 /*
   27397 ** WinCE lacks native support for file locking so we have to fake it
   27398 ** with some code of our own.
   27399 */
   27400 #if SQLITE_OS_WINCE
   27401 typedef struct winceLock {
   27402   int nReaders;       /* Number of reader locks obtained */
   27403   BOOL bPending;      /* Indicates a pending lock has been obtained */
   27404   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
   27405   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
   27406 } winceLock;
   27407 #endif
   27408 
   27409 /*
   27410 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
   27411 ** portability layer.
   27412 */
   27413 typedef struct winFile winFile;
   27414 struct winFile {
   27415   const sqlite3_io_methods *pMethod;/* Must be first */
   27416   HANDLE h;               /* Handle for accessing the file */
   27417   unsigned char locktype; /* Type of lock currently held on this file */
   27418   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
   27419   DWORD lastErrno;        /* The Windows errno from the last I/O error */
   27420   DWORD sectorSize;       /* Sector size of the device file is on */
   27421 #if SQLITE_OS_WINCE
   27422   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
   27423   HANDLE hMutex;          /* Mutex used to control access to shared lock */
   27424   HANDLE hShared;         /* Shared memory segment used for locking */
   27425   winceLock local;        /* Locks obtained by this instance of winFile */
   27426   winceLock *shared;      /* Global shared lock memory for the file  */
   27427 #endif
   27428 };
   27429 
   27430 /*
   27431 ** Forward prototypes.
   27432 */
   27433 static int getSectorSize(
   27434     sqlite3_vfs *pVfs,
   27435     const char *zRelative     /* UTF-8 file name */
   27436 );
   27437 
   27438 /*
   27439 ** The following variable is (normally) set once and never changes
   27440 ** thereafter.  It records whether the operating system is Win95
   27441 ** or WinNT.
   27442 **
   27443 ** 0:   Operating system unknown.
   27444 ** 1:   Operating system is Win95.
   27445 ** 2:   Operating system is WinNT.
   27446 **
   27447 ** In order to facilitate testing on a WinNT system, the test fixture
   27448 ** can manually set this value to 1 to emulate Win98 behavior.
   27449 */
   27450 #ifdef SQLITE_TEST
   27451 SQLITE_API int sqlite3_os_type = 0;
   27452 #else
   27453 static int sqlite3_os_type = 0;
   27454 #endif
   27455 
   27456 /*
   27457 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
   27458 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
   27459 **
   27460 ** Here is an interesting observation:  Win95, Win98, and WinME lack
   27461 ** the LockFileEx() API.  But we can still statically link against that
   27462 ** API as long as we don't call it when running Win95/98/ME.  A call to
   27463 ** this routine is used to determine if the host is Win95/98/ME or
   27464 ** WinNT/2K/XP so that we will know whether or not we can safely call
   27465 ** the LockFileEx() API.
   27466 */
   27467 #if SQLITE_OS_WINCE
   27468 # define isNT()  (1)
   27469 #else
   27470   static int isNT(void){
   27471     if( sqlite3_os_type==0 ){
   27472       OSVERSIONINFO sInfo;
   27473       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
   27474       GetVersionEx(&sInfo);
   27475       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
   27476     }
   27477     return sqlite3_os_type==2;
   27478   }
   27479 #endif /* SQLITE_OS_WINCE */
   27480 
   27481 /*
   27482 ** Convert a UTF-8 string to microsoft unicode (UTF-16?).
   27483 **
   27484 ** Space to hold the returned string is obtained from malloc.
   27485 */
   27486 static WCHAR *utf8ToUnicode(const char *zFilename){
   27487   int nChar;
   27488   WCHAR *zWideFilename;
   27489 
   27490   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
   27491   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
   27492   if( zWideFilename==0 ){
   27493     return 0;
   27494   }
   27495   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
   27496   if( nChar==0 ){
   27497     free(zWideFilename);
   27498     zWideFilename = 0;
   27499   }
   27500   return zWideFilename;
   27501 }
   27502 
   27503 /*
   27504 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
   27505 ** obtained from malloc().
   27506 */
   27507 static char *unicodeToUtf8(const WCHAR *zWideFilename){
   27508   int nByte;
   27509   char *zFilename;
   27510 
   27511   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
   27512   zFilename = malloc( nByte );
   27513   if( zFilename==0 ){
   27514     return 0;
   27515   }
   27516   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
   27517                               0, 0);
   27518   if( nByte == 0 ){
   27519     free(zFilename);
   27520     zFilename = 0;
   27521   }
   27522   return zFilename;
   27523 }
   27524 
   27525 /*
   27526 ** Convert an ansi string to microsoft unicode, based on the
   27527 ** current codepage settings for file apis.
   27528 **
   27529 ** Space to hold the returned string is obtained
   27530 ** from malloc.
   27531 */
   27532 static WCHAR *mbcsToUnicode(const char *zFilename){
   27533   int nByte;
   27534   WCHAR *zMbcsFilename;
   27535   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
   27536 
   27537   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
   27538   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
   27539   if( zMbcsFilename==0 ){
   27540     return 0;
   27541   }
   27542   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
   27543   if( nByte==0 ){
   27544     free(zMbcsFilename);
   27545     zMbcsFilename = 0;
   27546   }
   27547   return zMbcsFilename;
   27548 }
   27549 
   27550 /*
   27551 ** Convert microsoft unicode to multibyte character string, based on the
   27552 ** user's Ansi codepage.
   27553 **
   27554 ** Space to hold the returned string is obtained from
   27555 ** malloc().
   27556 */
   27557 static char *unicodeToMbcs(const WCHAR *zWideFilename){
   27558   int nByte;
   27559   char *zFilename;
   27560   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
   27561 
   27562   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
   27563   zFilename = malloc( nByte );
   27564   if( zFilename==0 ){
   27565     return 0;
   27566   }
   27567   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
   27568                               0, 0);
   27569   if( nByte == 0 ){
   27570     free(zFilename);
   27571     zFilename = 0;
   27572   }
   27573   return zFilename;
   27574 }
   27575 
   27576 /*
   27577 ** Convert multibyte character string to UTF-8.  Space to hold the
   27578 ** returned string is obtained from malloc().
   27579 */
   27580 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
   27581   char *zFilenameUtf8;
   27582   WCHAR *zTmpWide;
   27583 
   27584   zTmpWide = mbcsToUnicode(zFilename);
   27585   if( zTmpWide==0 ){
   27586     return 0;
   27587   }
   27588   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
   27589   free(zTmpWide);
   27590   return zFilenameUtf8;
   27591 }
   27592 
   27593 /*
   27594 ** Convert UTF-8 to multibyte character string.  Space to hold the
   27595 ** returned string is obtained from malloc().
   27596 */
   27597 static char *utf8ToMbcs(const char *zFilename){
   27598   char *zFilenameMbcs;
   27599   WCHAR *zTmpWide;
   27600 
   27601   zTmpWide = utf8ToUnicode(zFilename);
   27602   if( zTmpWide==0 ){
   27603     return 0;
   27604   }
   27605   zFilenameMbcs = unicodeToMbcs(zTmpWide);
   27606   free(zTmpWide);
   27607   return zFilenameMbcs;
   27608 }
   27609 
   27610 #if SQLITE_OS_WINCE
   27611 /*************************************************************************
   27612 ** This section contains code for WinCE only.
   27613 */
   27614 /*
   27615 ** WindowsCE does not have a localtime() function.  So create a
   27616 ** substitute.
   27617 */
   27618 struct tm *__cdecl localtime(const time_t *t)
   27619 {
   27620   static struct tm y;
   27621   FILETIME uTm, lTm;
   27622   SYSTEMTIME pTm;
   27623   sqlite3_int64 t64;
   27624   t64 = *t;
   27625   t64 = (t64 + 11644473600)*10000000;
   27626   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
   27627   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
   27628   FileTimeToLocalFileTime(&uTm,&lTm);
   27629   FileTimeToSystemTime(&lTm,&pTm);
   27630   y.tm_year = pTm.wYear - 1900;
   27631   y.tm_mon = pTm.wMonth - 1;
   27632   y.tm_wday = pTm.wDayOfWeek;
   27633   y.tm_mday = pTm.wDay;
   27634   y.tm_hour = pTm.wHour;
   27635   y.tm_min = pTm.wMinute;
   27636   y.tm_sec = pTm.wSecond;
   27637   return &y;
   27638 }
   27639 
   27640 /* This will never be called, but defined to make the code compile */
   27641 #define GetTempPathA(a,b)
   27642 
   27643 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
   27644 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
   27645 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
   27646 
   27647 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
   27648 
   27649 /*
   27650 ** Acquire a lock on the handle h
   27651 */
   27652 static void winceMutexAcquire(HANDLE h){
   27653    DWORD dwErr;
   27654    do {
   27655      dwErr = WaitForSingleObject(h, INFINITE);
   27656    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
   27657 }
   27658 /*
   27659 ** Release a lock acquired by winceMutexAcquire()
   27660 */
   27661 #define winceMutexRelease(h) ReleaseMutex(h)
   27662 
   27663 /*
   27664 ** Create the mutex and shared memory used for locking in the file
   27665 ** descriptor pFile
   27666 */
   27667 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
   27668   WCHAR *zTok;
   27669   WCHAR *zName = utf8ToUnicode(zFilename);
   27670   BOOL bInit = TRUE;
   27671 
   27672   /* Initialize the local lockdata */
   27673   ZeroMemory(&pFile->local, sizeof(pFile->local));
   27674 
   27675   /* Replace the backslashes from the filename and lowercase it
   27676   ** to derive a mutex name. */
   27677   zTok = CharLowerW(zName);
   27678   for (;*zTok;zTok++){
   27679     if (*zTok == '\\') *zTok = '_';
   27680   }
   27681 
   27682   /* Create/open the named mutex */
   27683   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
   27684   if (!pFile->hMutex){
   27685     pFile->lastErrno = GetLastError();
   27686     free(zName);
   27687     return FALSE;
   27688   }
   27689 
   27690   /* Acquire the mutex before continuing */
   27691   winceMutexAcquire(pFile->hMutex);
   27692 
   27693   /* Since the names of named mutexes, semaphores, file mappings etc are
   27694   ** case-sensitive, take advantage of that by uppercasing the mutex name
   27695   ** and using that as the shared filemapping name.
   27696   */
   27697   CharUpperW(zName);
   27698   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
   27699                                        PAGE_READWRITE, 0, sizeof(winceLock),
   27700                                        zName);
   27701 
   27702   /* Set a flag that indicates we're the first to create the memory so it
   27703   ** must be zero-initialized */
   27704   if (GetLastError() == ERROR_ALREADY_EXISTS){
   27705     bInit = FALSE;
   27706   }
   27707 
   27708   free(zName);
   27709 
   27710   /* If we succeeded in making the shared memory handle, map it. */
   27711   if (pFile->hShared){
   27712     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
   27713              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
   27714     /* If mapping failed, close the shared memory handle and erase it */
   27715     if (!pFile->shared){
   27716       pFile->lastErrno = GetLastError();
   27717       CloseHandle(pFile->hShared);
   27718       pFile->hShared = NULL;
   27719     }
   27720   }
   27721 
   27722   /* If shared memory could not be created, then close the mutex and fail */
   27723   if (pFile->hShared == NULL){
   27724     winceMutexRelease(pFile->hMutex);
   27725     CloseHandle(pFile->hMutex);
   27726     pFile->hMutex = NULL;
   27727     return FALSE;
   27728   }
   27729 
   27730   /* Initialize the shared memory if we're supposed to */
   27731   if (bInit) {
   27732     ZeroMemory(pFile->shared, sizeof(winceLock));
   27733   }
   27734 
   27735   winceMutexRelease(pFile->hMutex);
   27736   return TRUE;
   27737 }
   27738 
   27739 /*
   27740 ** Destroy the part of winFile that deals with wince locks
   27741 */
   27742 static void winceDestroyLock(winFile *pFile){
   27743   if (pFile->hMutex){
   27744     /* Acquire the mutex */
   27745     winceMutexAcquire(pFile->hMutex);
   27746 
   27747     /* The following blocks should probably assert in debug mode, but they
   27748        are to cleanup in case any locks remained open */
   27749     if (pFile->local.nReaders){
   27750       pFile->shared->nReaders --;
   27751     }
   27752     if (pFile->local.bReserved){
   27753       pFile->shared->bReserved = FALSE;
   27754     }
   27755     if (pFile->local.bPending){
   27756       pFile->shared->bPending = FALSE;
   27757     }
   27758     if (pFile->local.bExclusive){
   27759       pFile->shared->bExclusive = FALSE;
   27760     }
   27761 
   27762     /* De-reference and close our copy of the shared memory handle */
   27763     UnmapViewOfFile(pFile->shared);
   27764     CloseHandle(pFile->hShared);
   27765 
   27766     /* Done with the mutex */
   27767     winceMutexRelease(pFile->hMutex);
   27768     CloseHandle(pFile->hMutex);
   27769     pFile->hMutex = NULL;
   27770   }
   27771 }
   27772 
   27773 /*
   27774 ** An implementation of the LockFile() API of windows for wince
   27775 */
   27776 static BOOL winceLockFile(
   27777   HANDLE *phFile,
   27778   DWORD dwFileOffsetLow,
   27779   DWORD dwFileOffsetHigh,
   27780   DWORD nNumberOfBytesToLockLow,
   27781   DWORD nNumberOfBytesToLockHigh
   27782 ){
   27783   winFile *pFile = HANDLE_TO_WINFILE(phFile);
   27784   BOOL bReturn = FALSE;
   27785 
   27786   UNUSED_PARAMETER(dwFileOffsetHigh);
   27787   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
   27788 
   27789   if (!pFile->hMutex) return TRUE;
   27790   winceMutexAcquire(pFile->hMutex);
   27791 
   27792   /* Wanting an exclusive lock? */
   27793   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
   27794        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
   27795     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
   27796        pFile->shared->bExclusive = TRUE;
   27797        pFile->local.bExclusive = TRUE;
   27798        bReturn = TRUE;
   27799     }
   27800   }
   27801 
   27802   /* Want a read-only lock? */
   27803   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
   27804            nNumberOfBytesToLockLow == 1){
   27805     if (pFile->shared->bExclusive == 0){
   27806       pFile->local.nReaders ++;
   27807       if (pFile->local.nReaders == 1){
   27808         pFile->shared->nReaders ++;
   27809       }
   27810       bReturn = TRUE;
   27811     }
   27812   }
   27813 
   27814   /* Want a pending lock? */
   27815   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
   27816     /* If no pending lock has been acquired, then acquire it */
   27817     if (pFile->shared->bPending == 0) {
   27818       pFile->shared->bPending = TRUE;
   27819       pFile->local.bPending = TRUE;
   27820       bReturn = TRUE;
   27821     }
   27822   }
   27823 
   27824   /* Want a reserved lock? */
   27825   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
   27826     if (pFile->shared->bReserved == 0) {
   27827       pFile->shared->bReserved = TRUE;
   27828       pFile->local.bReserved = TRUE;
   27829       bReturn = TRUE;
   27830     }
   27831   }
   27832 
   27833   winceMutexRelease(pFile->hMutex);
   27834   return bReturn;
   27835 }
   27836 
   27837 /*
   27838 ** An implementation of the UnlockFile API of windows for wince
   27839 */
   27840 static BOOL winceUnlockFile(
   27841   HANDLE *phFile,
   27842   DWORD dwFileOffsetLow,
   27843   DWORD dwFileOffsetHigh,
   27844   DWORD nNumberOfBytesToUnlockLow,
   27845   DWORD nNumberOfBytesToUnlockHigh
   27846 ){
   27847   winFile *pFile = HANDLE_TO_WINFILE(phFile);
   27848   BOOL bReturn = FALSE;
   27849 
   27850   UNUSED_PARAMETER(dwFileOffsetHigh);
   27851   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
   27852 
   27853   if (!pFile->hMutex) return TRUE;
   27854   winceMutexAcquire(pFile->hMutex);
   27855 
   27856   /* Releasing a reader lock or an exclusive lock */
   27857   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
   27858     /* Did we have an exclusive lock? */
   27859     if (pFile->local.bExclusive){
   27860       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
   27861       pFile->local.bExclusive = FALSE;
   27862       pFile->shared->bExclusive = FALSE;
   27863       bReturn = TRUE;
   27864     }
   27865 
   27866     /* Did we just have a reader lock? */
   27867     else if (pFile->local.nReaders){
   27868       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
   27869       pFile->local.nReaders --;
   27870       if (pFile->local.nReaders == 0)
   27871       {
   27872         pFile->shared->nReaders --;
   27873       }
   27874       bReturn = TRUE;
   27875     }
   27876   }
   27877 
   27878   /* Releasing a pending lock */
   27879   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
   27880     if (pFile->local.bPending){
   27881       pFile->local.bPending = FALSE;
   27882       pFile->shared->bPending = FALSE;
   27883       bReturn = TRUE;
   27884     }
   27885   }
   27886   /* Releasing a reserved lock */
   27887   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
   27888     if (pFile->local.bReserved) {
   27889       pFile->local.bReserved = FALSE;
   27890       pFile->shared->bReserved = FALSE;
   27891       bReturn = TRUE;
   27892     }
   27893   }
   27894 
   27895   winceMutexRelease(pFile->hMutex);
   27896   return bReturn;
   27897 }
   27898 
   27899 /*
   27900 ** An implementation of the LockFileEx() API of windows for wince
   27901 */
   27902 static BOOL winceLockFileEx(
   27903   HANDLE *phFile,
   27904   DWORD dwFlags,
   27905   DWORD dwReserved,
   27906   DWORD nNumberOfBytesToLockLow,
   27907   DWORD nNumberOfBytesToLockHigh,
   27908   LPOVERLAPPED lpOverlapped
   27909 ){
   27910   UNUSED_PARAMETER(dwReserved);
   27911   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
   27912 
   27913   /* If the caller wants a shared read lock, forward this call
   27914   ** to winceLockFile */
   27915   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
   27916       dwFlags == 1 &&
   27917       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
   27918     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
   27919   }
   27920   return FALSE;
   27921 }
   27922 /*
   27923 ** End of the special code for wince
   27924 *****************************************************************************/
   27925 #endif /* SQLITE_OS_WINCE */
   27926 
   27927 /*****************************************************************************
   27928 ** The next group of routines implement the I/O methods specified
   27929 ** by the sqlite3_io_methods object.
   27930 ******************************************************************************/
   27931 
   27932 /*
   27933 ** Close a file.
   27934 **
   27935 ** It is reported that an attempt to close a handle might sometimes
   27936 ** fail.  This is a very unreasonable result, but windows is notorious
   27937 ** for being unreasonable so I do not doubt that it might happen.  If
   27938 ** the close fails, we pause for 100 milliseconds and try again.  As
   27939 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
   27940 ** giving up and returning an error.
   27941 */
   27942 #define MX_CLOSE_ATTEMPT 3
   27943 static int winClose(sqlite3_file *id){
   27944   int rc, cnt = 0;
   27945   winFile *pFile = (winFile*)id;
   27946 
   27947   assert( id!=0 );
   27948   OSTRACE2("CLOSE %d\n", pFile->h);
   27949   do{
   27950     rc = CloseHandle(pFile->h);
   27951   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
   27952 #if SQLITE_OS_WINCE
   27953 #define WINCE_DELETION_ATTEMPTS 3
   27954   winceDestroyLock(pFile);
   27955   if( pFile->zDeleteOnClose ){
   27956     int cnt = 0;
   27957     while(
   27958            DeleteFileW(pFile->zDeleteOnClose)==0
   27959         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
   27960         && cnt++ < WINCE_DELETION_ATTEMPTS
   27961     ){
   27962        Sleep(100);  /* Wait a little before trying again */
   27963     }
   27964     free(pFile->zDeleteOnClose);
   27965   }
   27966 #endif
   27967   OpenCounter(-1);
   27968   return rc ? SQLITE_OK : SQLITE_IOERR;
   27969 }
   27970 
   27971 /*
   27972 ** Some microsoft compilers lack this definition.
   27973 */
   27974 #ifndef INVALID_SET_FILE_POINTER
   27975 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
   27976 #endif
   27977 
   27978 /*
   27979 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   27980 ** bytes were read successfully and SQLITE_IOERR if anything goes
   27981 ** wrong.
   27982 */
   27983 static int winRead(
   27984   sqlite3_file *id,          /* File to read from */
   27985   void *pBuf,                /* Write content into this buffer */
   27986   int amt,                   /* Number of bytes to read */
   27987   sqlite3_int64 offset       /* Begin reading at this offset */
   27988 ){
   27989   LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
   27990   LONG lowerBits = (LONG)(offset & 0xffffffff);
   27991   DWORD rc;
   27992   winFile *pFile = (winFile*)id;
   27993   DWORD error;
   27994   DWORD got;
   27995 
   27996   assert( id!=0 );
   27997   SimulateIOError(return SQLITE_IOERR_READ);
   27998   OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
   27999   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
   28000   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
   28001     pFile->lastErrno = error;
   28002     return SQLITE_FULL;
   28003   }
   28004   if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
   28005     pFile->lastErrno = GetLastError();
   28006     return SQLITE_IOERR_READ;
   28007   }
   28008   if( got==(DWORD)amt ){
   28009     return SQLITE_OK;
   28010   }else{
   28011     /* Unread parts of the buffer must be zero-filled */
   28012     memset(&((char*)pBuf)[got], 0, amt-got);
   28013     return SQLITE_IOERR_SHORT_READ;
   28014   }
   28015 }
   28016 
   28017 /*
   28018 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   28019 ** or some other error code on failure.
   28020 */
   28021 static int winWrite(
   28022   sqlite3_file *id,         /* File to write into */
   28023   const void *pBuf,         /* The bytes to be written */
   28024   int amt,                  /* Number of bytes to write */
   28025   sqlite3_int64 offset      /* Offset into the file to begin writing at */
   28026 ){
   28027   LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
   28028   LONG lowerBits = (LONG)(offset & 0xffffffff);
   28029   DWORD rc;
   28030   winFile *pFile = (winFile*)id;
   28031   DWORD error;
   28032   DWORD wrote = 0;
   28033 
   28034   assert( id!=0 );
   28035   SimulateIOError(return SQLITE_IOERR_WRITE);
   28036   SimulateDiskfullError(return SQLITE_FULL);
   28037   OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
   28038   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
   28039   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
   28040     pFile->lastErrno = error;
   28041     return SQLITE_FULL;
   28042   }
   28043   assert( amt>0 );
   28044   while(
   28045      amt>0
   28046      && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
   28047      && wrote>0
   28048   ){
   28049     amt -= wrote;
   28050     pBuf = &((char*)pBuf)[wrote];
   28051   }
   28052   if( !rc || amt>(int)wrote ){
   28053     pFile->lastErrno = GetLastError();
   28054     return SQLITE_FULL;
   28055   }
   28056   return SQLITE_OK;
   28057 }
   28058 
   28059 /*
   28060 ** Truncate an open file to a specified size
   28061 */
   28062 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
   28063   LONG upperBits = (LONG)((nByte>>32) & 0x7fffffff);
   28064   LONG lowerBits = (LONG)(nByte & 0xffffffff);
   28065   DWORD rc;
   28066   winFile *pFile = (winFile*)id;
   28067   DWORD error;
   28068 
   28069   assert( id!=0 );
   28070   OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
   28071   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
   28072   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
   28073   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
   28074     pFile->lastErrno = error;
   28075     return SQLITE_IOERR_TRUNCATE;
   28076   }
   28077   /* SetEndOfFile will fail if nByte is negative */
   28078   if( !SetEndOfFile(pFile->h) ){
   28079     pFile->lastErrno = GetLastError();
   28080     return SQLITE_IOERR_TRUNCATE;
   28081   }
   28082   return SQLITE_OK;
   28083 }
   28084 
   28085 #ifdef SQLITE_TEST
   28086 /*
   28087 ** Count the number of fullsyncs and normal syncs.  This is used to test
   28088 ** that syncs and fullsyncs are occuring at the right times.
   28089 */
   28090 SQLITE_API int sqlite3_sync_count = 0;
   28091 SQLITE_API int sqlite3_fullsync_count = 0;
   28092 #endif
   28093 
   28094 /*
   28095 ** Make sure all writes to a particular file are committed to disk.
   28096 */
   28097 static int winSync(sqlite3_file *id, int flags){
   28098 #ifndef SQLITE_NO_SYNC
   28099   winFile *pFile = (winFile*)id;
   28100 
   28101   assert( id!=0 );
   28102   OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
   28103 #else
   28104   UNUSED_PARAMETER(id);
   28105 #endif
   28106 #ifndef SQLITE_TEST
   28107   UNUSED_PARAMETER(flags);
   28108 #else
   28109   if( flags & SQLITE_SYNC_FULL ){
   28110     sqlite3_fullsync_count++;
   28111   }
   28112   sqlite3_sync_count++;
   28113 #endif
   28114   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   28115   ** no-op
   28116   */
   28117 #ifdef SQLITE_NO_SYNC
   28118     return SQLITE_OK;
   28119 #else
   28120   if( FlushFileBuffers(pFile->h) ){
   28121     return SQLITE_OK;
   28122   }else{
   28123     pFile->lastErrno = GetLastError();
   28124     return SQLITE_IOERR;
   28125   }
   28126 #endif
   28127 }
   28128 
   28129 /*
   28130 ** Determine the current size of a file in bytes
   28131 */
   28132 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
   28133   DWORD upperBits;
   28134   DWORD lowerBits;
   28135   winFile *pFile = (winFile*)id;
   28136   DWORD error;
   28137 
   28138   assert( id!=0 );
   28139   SimulateIOError(return SQLITE_IOERR_FSTAT);
   28140   lowerBits = GetFileSize(pFile->h, &upperBits);
   28141   if(   (lowerBits == INVALID_FILE_SIZE)
   28142      && ((error = GetLastError()) != NO_ERROR) )
   28143   {
   28144     pFile->lastErrno = error;
   28145     return SQLITE_IOERR_FSTAT;
   28146   }
   28147   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
   28148   return SQLITE_OK;
   28149 }
   28150 
   28151 /*
   28152 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
   28153 */
   28154 #ifndef LOCKFILE_FAIL_IMMEDIATELY
   28155 # define LOCKFILE_FAIL_IMMEDIATELY 1
   28156 #endif
   28157 
   28158 /*
   28159 ** Acquire a reader lock.
   28160 ** Different API routines are called depending on whether or not this
   28161 ** is Win95 or WinNT.
   28162 */
   28163 static int getReadLock(winFile *pFile){
   28164   int res;
   28165   if( isNT() ){
   28166     OVERLAPPED ovlp;
   28167     ovlp.Offset = SHARED_FIRST;
   28168     ovlp.OffsetHigh = 0;
   28169     ovlp.hEvent = 0;
   28170     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
   28171                      0, SHARED_SIZE, 0, &ovlp);
   28172 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   28173 */
   28174 #if SQLITE_OS_WINCE==0
   28175   }else{
   28176     int lk;
   28177     sqlite3_randomness(sizeof(lk), &lk);
   28178     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
   28179     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
   28180 #endif
   28181   }
   28182   if( res == 0 ){
   28183     pFile->lastErrno = GetLastError();
   28184   }
   28185   return res;
   28186 }
   28187 
   28188 /*
   28189 ** Undo a readlock
   28190 */
   28191 static int unlockReadLock(winFile *pFile){
   28192   int res;
   28193   if( isNT() ){
   28194     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   28195 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   28196 */
   28197 #if SQLITE_OS_WINCE==0
   28198   }else{
   28199     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
   28200 #endif
   28201   }
   28202   if( res == 0 ){
   28203     pFile->lastErrno = GetLastError();
   28204   }
   28205   return res;
   28206 }
   28207 
   28208 /*
   28209 ** Lock the file with the lock specified by parameter locktype - one
   28210 ** of the following:
   28211 **
   28212 **     (1) SHARED_LOCK
   28213 **     (2) RESERVED_LOCK
   28214 **     (3) PENDING_LOCK
   28215 **     (4) EXCLUSIVE_LOCK
   28216 **
   28217 ** Sometimes when requesting one lock state, additional lock states
   28218 ** are inserted in between.  The locking might fail on one of the later
   28219 ** transitions leaving the lock state different from what it started but
   28220 ** still short of its goal.  The following chart shows the allowed
   28221 ** transitions and the inserted intermediate states:
   28222 **
   28223 **    UNLOCKED -> SHARED
   28224 **    SHARED -> RESERVED
   28225 **    SHARED -> (PENDING) -> EXCLUSIVE
   28226 **    RESERVED -> (PENDING) -> EXCLUSIVE
   28227 **    PENDING -> EXCLUSIVE
   28228 **
   28229 ** This routine will only increase a lock.  The winUnlock() routine
   28230 ** erases all locks at once and returns us immediately to locking level 0.
   28231 ** It is not possible to lower the locking level one step at a time.  You
   28232 ** must go straight to locking level 0.
   28233 */
   28234 static int winLock(sqlite3_file *id, int locktype){
   28235   int rc = SQLITE_OK;    /* Return code from subroutines */
   28236   int res = 1;           /* Result of a windows lock call */
   28237   int newLocktype;       /* Set pFile->locktype to this value before exiting */
   28238   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
   28239   winFile *pFile = (winFile*)id;
   28240   DWORD error = NO_ERROR;
   28241 
   28242   assert( id!=0 );
   28243   OSTRACE5("LOCK %d %d was %d(%d)\n",
   28244           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
   28245 
   28246   /* If there is already a lock of this type or more restrictive on the
   28247   ** OsFile, do nothing. Don't use the end_lock: exit path, as
   28248   ** sqlite3OsEnterMutex() hasn't been called yet.
   28249   */
   28250   if( pFile->locktype>=locktype ){
   28251     return SQLITE_OK;
   28252   }
   28253 
   28254   /* Make sure the locking sequence is correct
   28255   */
   28256   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
   28257   assert( locktype!=PENDING_LOCK );
   28258   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
   28259 
   28260   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
   28261   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
   28262   ** the PENDING_LOCK byte is temporary.
   28263   */
   28264   newLocktype = pFile->locktype;
   28265   if(   (pFile->locktype==NO_LOCK)
   28266      || (   (locktype==EXCLUSIVE_LOCK)
   28267          && (pFile->locktype==RESERVED_LOCK))
   28268   ){
   28269     int cnt = 3;
   28270     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
   28271       /* Try 3 times to get the pending lock.  The pending lock might be
   28272       ** held by another reader process who will release it momentarily.
   28273       */
   28274       OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
   28275       Sleep(1);
   28276     }
   28277     gotPendingLock = res;
   28278     if( !res ){
   28279       error = GetLastError();
   28280     }
   28281   }
   28282 
   28283   /* Acquire a shared lock
   28284   */
   28285   if( locktype==SHARED_LOCK && res ){
   28286     assert( pFile->locktype==NO_LOCK );
   28287     res = getReadLock(pFile);
   28288     if( res ){
   28289       newLocktype = SHARED_LOCK;
   28290     }else{
   28291       error = GetLastError();
   28292     }
   28293   }
   28294 
   28295   /* Acquire a RESERVED lock
   28296   */
   28297   if( locktype==RESERVED_LOCK && res ){
   28298     assert( pFile->locktype==SHARED_LOCK );
   28299     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
   28300     if( res ){
   28301       newLocktype = RESERVED_LOCK;
   28302     }else{
   28303       error = GetLastError();
   28304     }
   28305   }
   28306 
   28307   /* Acquire a PENDING lock
   28308   */
   28309   if( locktype==EXCLUSIVE_LOCK && res ){
   28310     newLocktype = PENDING_LOCK;
   28311     gotPendingLock = 0;
   28312   }
   28313 
   28314   /* Acquire an EXCLUSIVE lock
   28315   */
   28316   if( locktype==EXCLUSIVE_LOCK && res ){
   28317     assert( pFile->locktype>=SHARED_LOCK );
   28318     res = unlockReadLock(pFile);
   28319     OSTRACE2("unreadlock = %d\n", res);
   28320     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   28321     if( res ){
   28322       newLocktype = EXCLUSIVE_LOCK;
   28323     }else{
   28324       error = GetLastError();
   28325       OSTRACE2("error-code = %d\n", error);
   28326       getReadLock(pFile);
   28327     }
   28328   }
   28329 
   28330   /* If we are holding a PENDING lock that ought to be released, then
   28331   ** release it now.
   28332   */
   28333   if( gotPendingLock && locktype==SHARED_LOCK ){
   28334     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
   28335   }
   28336 
   28337   /* Update the state of the lock has held in the file descriptor then
   28338   ** return the appropriate result code.
   28339   */
   28340   if( res ){
   28341     rc = SQLITE_OK;
   28342   }else{
   28343     OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
   28344            locktype, newLocktype);
   28345     pFile->lastErrno = error;
   28346     rc = SQLITE_BUSY;
   28347   }
   28348   pFile->locktype = (u8)newLocktype;
   28349   return rc;
   28350 }
   28351 
   28352 /*
   28353 ** This routine checks if there is a RESERVED lock held on the specified
   28354 ** file by this or any other process. If such a lock is held, return
   28355 ** non-zero, otherwise zero.
   28356 */
   28357 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
   28358   int rc;
   28359   winFile *pFile = (winFile*)id;
   28360 
   28361   assert( id!=0 );
   28362   if( pFile->locktype>=RESERVED_LOCK ){
   28363     rc = 1;
   28364     OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
   28365   }else{
   28366     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
   28367     if( rc ){
   28368       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
   28369     }
   28370     rc = !rc;
   28371     OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
   28372   }
   28373   *pResOut = rc;
   28374   return SQLITE_OK;
   28375 }
   28376 
   28377 /*
   28378 ** Lower the locking level on file descriptor id to locktype.  locktype
   28379 ** must be either NO_LOCK or SHARED_LOCK.
   28380 **
   28381 ** If the locking level of the file descriptor is already at or below
   28382 ** the requested locking level, this routine is a no-op.
   28383 **
   28384 ** It is not possible for this routine to fail if the second argument
   28385 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
   28386 ** might return SQLITE_IOERR;
   28387 */
   28388 static int winUnlock(sqlite3_file *id, int locktype){
   28389   int type;
   28390   winFile *pFile = (winFile*)id;
   28391   int rc = SQLITE_OK;
   28392   assert( pFile!=0 );
   28393   assert( locktype<=SHARED_LOCK );
   28394   OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
   28395           pFile->locktype, pFile->sharedLockByte);
   28396   type = pFile->locktype;
   28397   if( type>=EXCLUSIVE_LOCK ){
   28398     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   28399     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
   28400       /* This should never happen.  We should always be able to
   28401       ** reacquire the read lock */
   28402       rc = SQLITE_IOERR_UNLOCK;
   28403     }
   28404   }
   28405   if( type>=RESERVED_LOCK ){
   28406     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
   28407   }
   28408   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
   28409     unlockReadLock(pFile);
   28410   }
   28411   if( type>=PENDING_LOCK ){
   28412     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
   28413   }
   28414   pFile->locktype = (u8)locktype;
   28415   return rc;
   28416 }
   28417 
   28418 /*
   28419 ** Control and query of the open file handle.
   28420 */
   28421 static int winFileControl(sqlite3_file *id, int op, void *pArg){
   28422   switch( op ){
   28423     case SQLITE_FCNTL_LOCKSTATE: {
   28424       *(int*)pArg = ((winFile*)id)->locktype;
   28425       return SQLITE_OK;
   28426     }
   28427     case SQLITE_LAST_ERRNO: {
   28428       *(int*)pArg = (int)((winFile*)id)->lastErrno;
   28429       return SQLITE_OK;
   28430     }
   28431   }
   28432   return SQLITE_ERROR;
   28433 }
   28434 
   28435 /*
   28436 ** Return the sector size in bytes of the underlying block device for
   28437 ** the specified file. This is almost always 512 bytes, but may be
   28438 ** larger for some devices.
   28439 **
   28440 ** SQLite code assumes this function cannot fail. It also assumes that
   28441 ** if two files are created in the same file-system directory (i.e.
   28442 ** a database and its journal file) that the sector size will be the
   28443 ** same for both.
   28444 */
   28445 static int winSectorSize(sqlite3_file *id){
   28446   assert( id!=0 );
   28447   return (int)(((winFile*)id)->sectorSize);
   28448 }
   28449 
   28450 /*
   28451 ** Return a vector of device characteristics.
   28452 */
   28453 static int winDeviceCharacteristics(sqlite3_file *id){
   28454   UNUSED_PARAMETER(id);
   28455   return 0;
   28456 }
   28457 
   28458 /*
   28459 ** This vector defines all the methods that can operate on an
   28460 ** sqlite3_file for win32.
   28461 */
   28462 static const sqlite3_io_methods winIoMethod = {
   28463   1,                        /* iVersion */
   28464   winClose,
   28465   winRead,
   28466   winWrite,
   28467   winTruncate,
   28468   winSync,
   28469   winFileSize,
   28470   winLock,
   28471   winUnlock,
   28472   winCheckReservedLock,
   28473   winFileControl,
   28474   winSectorSize,
   28475   winDeviceCharacteristics
   28476 };
   28477 
   28478 /***************************************************************************
   28479 ** Here ends the I/O methods that form the sqlite3_io_methods object.
   28480 **
   28481 ** The next block of code implements the VFS methods.
   28482 ****************************************************************************/
   28483 
   28484 /*
   28485 ** Convert a UTF-8 filename into whatever form the underlying
   28486 ** operating system wants filenames in.  Space to hold the result
   28487 ** is obtained from malloc and must be freed by the calling
   28488 ** function.
   28489 */
   28490 static void *convertUtf8Filename(const char *zFilename){
   28491   void *zConverted = 0;
   28492   if( isNT() ){
   28493     zConverted = utf8ToUnicode(zFilename);
   28494 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   28495 */
   28496 #if SQLITE_OS_WINCE==0
   28497   }else{
   28498     zConverted = utf8ToMbcs(zFilename);
   28499 #endif
   28500   }
   28501   /* caller will handle out of memory */
   28502   return zConverted;
   28503 }
   28504 
   28505 /*
   28506 ** Create a temporary file name in zBuf.  zBuf must be big enough to
   28507 ** hold at pVfs->mxPathname characters.
   28508 */
   28509 static int getTempname(int nBuf, char *zBuf){
   28510   static char zChars[] =
   28511     "abcdefghijklmnopqrstuvwxyz"
   28512     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   28513     "0123456789";
   28514   size_t i, j;
   28515   char zTempPath[MAX_PATH+1];
   28516   if( sqlite3_temp_directory ){
   28517     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
   28518   }else if( isNT() ){
   28519     char *zMulti;
   28520     WCHAR zWidePath[MAX_PATH];
   28521     GetTempPathW(MAX_PATH-30, zWidePath);
   28522     zMulti = unicodeToUtf8(zWidePath);
   28523     if( zMulti ){
   28524       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
   28525       free(zMulti);
   28526     }else{
   28527       return SQLITE_NOMEM;
   28528     }
   28529 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   28530 ** Since the ASCII version of these Windows API do not exist for WINCE,
   28531 ** it's important to not reference them for WINCE builds.
   28532 */
   28533 #if SQLITE_OS_WINCE==0
   28534   }else{
   28535     char *zUtf8;
   28536     char zMbcsPath[MAX_PATH];
   28537     GetTempPathA(MAX_PATH-30, zMbcsPath);
   28538     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
   28539     if( zUtf8 ){
   28540       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
   28541       free(zUtf8);
   28542     }else{
   28543       return SQLITE_NOMEM;
   28544     }
   28545 #endif
   28546   }
   28547   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
   28548   zTempPath[i] = 0;
   28549   sqlite3_snprintf(nBuf-30, zBuf,
   28550                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
   28551   j = sqlite3Strlen30(zBuf);
   28552   sqlite3_randomness(20, &zBuf[j]);
   28553   for(i=0; i<20; i++, j++){
   28554     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   28555   }
   28556   zBuf[j] = 0;
   28557   OSTRACE2("TEMP FILENAME: %s\n", zBuf);
   28558   return SQLITE_OK;
   28559 }
   28560 
   28561 /*
   28562 ** The return value of getLastErrorMsg
   28563 ** is zero if the error message fits in the buffer, or non-zero
   28564 ** otherwise (if the message was truncated).
   28565 */
   28566 static int getLastErrorMsg(int nBuf, char *zBuf){
   28567   /* FormatMessage returns 0 on failure.  Otherwise it
   28568   ** returns the number of TCHARs written to the output
   28569   ** buffer, excluding the terminating null char.
   28570   */
   28571   DWORD error = GetLastError();
   28572   DWORD dwLen = 0;
   28573   char *zOut = 0;
   28574 
   28575   if( isNT() ){
   28576     WCHAR *zTempWide = NULL;
   28577     dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
   28578                            NULL,
   28579                            error,
   28580                            0,
   28581                            (LPWSTR) &zTempWide,
   28582                            0,
   28583                            0);
   28584     if( dwLen > 0 ){
   28585       /* allocate a buffer and convert to UTF8 */
   28586       zOut = unicodeToUtf8(zTempWide);
   28587       /* free the system buffer allocated by FormatMessage */
   28588       LocalFree(zTempWide);
   28589     }
   28590 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   28591 ** Since the ASCII version of these Windows API do not exist for WINCE,
   28592 ** it's important to not reference them for WINCE builds.
   28593 */
   28594 #if SQLITE_OS_WINCE==0
   28595   }else{
   28596     char *zTemp = NULL;
   28597     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
   28598                            NULL,
   28599                            error,
   28600                            0,
   28601                            (LPSTR) &zTemp,
   28602                            0,
   28603                            0);
   28604     if( dwLen > 0 ){
   28605       /* allocate a buffer and convert to UTF8 */
   28606       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
   28607       /* free the system buffer allocated by FormatMessage */
   28608       LocalFree(zTemp);
   28609     }
   28610 #endif
   28611   }
   28612   if( 0 == dwLen ){
   28613     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
   28614   }else{
   28615     /* copy a maximum of nBuf chars to output buffer */
   28616     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
   28617     /* free the UTF8 buffer */
   28618     free(zOut);
   28619   }
   28620   return 0;
   28621 }
   28622 
   28623 /*
   28624 ** Open a file.
   28625 */
   28626 static int winOpen(
   28627   sqlite3_vfs *pVfs,        /* Not used */
   28628   const char *zName,        /* Name of the file (UTF-8) */
   28629   sqlite3_file *id,         /* Write the SQLite file handle here */
   28630   int flags,                /* Open mode flags */
   28631   int *pOutFlags            /* Status return flags */
   28632 ){
   28633   HANDLE h;
   28634   DWORD dwDesiredAccess;
   28635   DWORD dwShareMode;
   28636   DWORD dwCreationDisposition;
   28637   DWORD dwFlagsAndAttributes = 0;
   28638 #if SQLITE_OS_WINCE
   28639   int isTemp = 0;
   28640 #endif
   28641   winFile *pFile = (winFile*)id;
   28642   void *zConverted;                 /* Filename in OS encoding */
   28643   const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
   28644   char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
   28645 
   28646   assert( id!=0 );
   28647   UNUSED_PARAMETER(pVfs);
   28648 
   28649   /* If the second argument to this function is NULL, generate a
   28650   ** temporary file name to use
   28651   */
   28652   if( !zUtf8Name ){
   28653     int rc = getTempname(MAX_PATH+1, zTmpname);
   28654     if( rc!=SQLITE_OK ){
   28655       return rc;
   28656     }
   28657     zUtf8Name = zTmpname;
   28658   }
   28659 
   28660   /* Convert the filename to the system encoding. */
   28661   zConverted = convertUtf8Filename(zUtf8Name);
   28662   if( zConverted==0 ){
   28663     return SQLITE_NOMEM;
   28664   }
   28665 
   28666   if( flags & SQLITE_OPEN_READWRITE ){
   28667     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
   28668   }else{
   28669     dwDesiredAccess = GENERIC_READ;
   28670   }
   28671   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
   28672   ** created. SQLite doesn't use it to indicate "exclusive access"
   28673   ** as it is usually understood.
   28674   */
   28675   assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
   28676   if( flags & SQLITE_OPEN_EXCLUSIVE ){
   28677     /* Creates a new file, only if it does not already exist. */
   28678     /* If the file exists, it fails. */
   28679     dwCreationDisposition = CREATE_NEW;
   28680   }else if( flags & SQLITE_OPEN_CREATE ){
   28681     /* Open existing file, or create if it doesn't exist */
   28682     dwCreationDisposition = OPEN_ALWAYS;
   28683   }else{
   28684     /* Opens a file, only if it exists. */
   28685     dwCreationDisposition = OPEN_EXISTING;
   28686   }
   28687   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
   28688   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
   28689 #if SQLITE_OS_WINCE
   28690     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
   28691     isTemp = 1;
   28692 #else
   28693     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
   28694                                | FILE_ATTRIBUTE_HIDDEN
   28695                                | FILE_FLAG_DELETE_ON_CLOSE;
   28696 #endif
   28697   }else{
   28698     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
   28699   }
   28700   /* Reports from the internet are that performance is always
   28701   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
   28702 #if SQLITE_OS_WINCE
   28703   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
   28704 #endif
   28705   if( isNT() ){
   28706     h = CreateFileW((WCHAR*)zConverted,
   28707        dwDesiredAccess,
   28708        dwShareMode,
   28709        NULL,
   28710        dwCreationDisposition,
   28711        dwFlagsAndAttributes,
   28712        NULL
   28713     );
   28714 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   28715 ** Since the ASCII version of these Windows API do not exist for WINCE,
   28716 ** it's important to not reference them for WINCE builds.
   28717 */
   28718 #if SQLITE_OS_WINCE==0
   28719   }else{
   28720     h = CreateFileA((char*)zConverted,
   28721        dwDesiredAccess,
   28722        dwShareMode,
   28723        NULL,
   28724        dwCreationDisposition,
   28725        dwFlagsAndAttributes,
   28726        NULL
   28727     );
   28728 #endif
   28729   }
   28730   if( h==INVALID_HANDLE_VALUE ){
   28731     free(zConverted);
   28732     if( flags & SQLITE_OPEN_READWRITE ){
   28733       return winOpen(pVfs, zName, id,
   28734              ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
   28735     }else{
   28736       return SQLITE_CANTOPEN_BKPT;
   28737     }
   28738   }
   28739   if( pOutFlags ){
   28740     if( flags & SQLITE_OPEN_READWRITE ){
   28741       *pOutFlags = SQLITE_OPEN_READWRITE;
   28742     }else{
   28743       *pOutFlags = SQLITE_OPEN_READONLY;
   28744     }
   28745   }
   28746   memset(pFile, 0, sizeof(*pFile));
   28747   pFile->pMethod = &winIoMethod;
   28748   pFile->h = h;
   28749   pFile->lastErrno = NO_ERROR;
   28750   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
   28751 #if SQLITE_OS_WINCE
   28752   if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
   28753                (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
   28754        && !winceCreateLock(zName, pFile)
   28755   ){
   28756     CloseHandle(h);
   28757     free(zConverted);
   28758     return SQLITE_CANTOPEN_BKPT;
   28759   }
   28760   if( isTemp ){
   28761     pFile->zDeleteOnClose = zConverted;
   28762   }else
   28763 #endif
   28764   {
   28765     free(zConverted);
   28766   }
   28767   OpenCounter(+1);
   28768   return SQLITE_OK;
   28769 }
   28770 
   28771 /*
   28772 ** Delete the named file.
   28773 **
   28774 ** Note that windows does not allow a file to be deleted if some other
   28775 ** process has it open.  Sometimes a virus scanner or indexing program
   28776 ** will open a journal file shortly after it is created in order to do
   28777 ** whatever it does.  While this other process is holding the
   28778 ** file open, we will be unable to delete it.  To work around this
   28779 ** problem, we delay 100 milliseconds and try to delete again.  Up
   28780 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
   28781 ** up and returning an error.
   28782 */
   28783 #define MX_DELETION_ATTEMPTS 5
   28784 static int winDelete(
   28785   sqlite3_vfs *pVfs,          /* Not used on win32 */
   28786   const char *zFilename,      /* Name of file to delete */
   28787   int syncDir                 /* Not used on win32 */
   28788 ){
   28789   int cnt = 0;
   28790   DWORD rc;
   28791   DWORD error = 0;
   28792   void *zConverted = convertUtf8Filename(zFilename);
   28793   UNUSED_PARAMETER(pVfs);
   28794   UNUSED_PARAMETER(syncDir);
   28795   if( zConverted==0 ){
   28796     return SQLITE_NOMEM;
   28797   }
   28798   SimulateIOError(return SQLITE_IOERR_DELETE);
   28799   if( isNT() ){
   28800     do{
   28801       DeleteFileW(zConverted);
   28802     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
   28803                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
   28804            && (++cnt < MX_DELETION_ATTEMPTS)
   28805            && (Sleep(100), 1) );
   28806 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   28807 ** Since the ASCII version of these Windows API do not exist for WINCE,
   28808 ** it's important to not reference them for WINCE builds.
   28809 */
   28810 #if SQLITE_OS_WINCE==0
   28811   }else{
   28812     do{
   28813       DeleteFileA(zConverted);
   28814     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
   28815                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
   28816            && (++cnt < MX_DELETION_ATTEMPTS)
   28817            && (Sleep(100), 1) );
   28818 #endif
   28819   }
   28820   free(zConverted);
   28821   OSTRACE2("DELETE \"%s\"\n", zFilename);
   28822   return (   (rc == INVALID_FILE_ATTRIBUTES)
   28823           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
   28824 }
   28825 
   28826 /*
   28827 ** Check the existance and status of a file.
   28828 */
   28829 static int winAccess(
   28830   sqlite3_vfs *pVfs,         /* Not used on win32 */
   28831   const char *zFilename,     /* Name of file to check */
   28832   int flags,                 /* Type of test to make on this file */
   28833   int *pResOut               /* OUT: Result */
   28834 ){
   28835   DWORD attr;
   28836   int rc = 0;
   28837   void *zConverted = convertUtf8Filename(zFilename);
   28838   UNUSED_PARAMETER(pVfs);
   28839   if( zConverted==0 ){
   28840     return SQLITE_NOMEM;
   28841   }
   28842   if( isNT() ){
   28843     attr = GetFileAttributesW((WCHAR*)zConverted);
   28844 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   28845 ** Since the ASCII version of these Windows API do not exist for WINCE,
   28846 ** it's important to not reference them for WINCE builds.
   28847 */
   28848 #if SQLITE_OS_WINCE==0
   28849   }else{
   28850     attr = GetFileAttributesA((char*)zConverted);
   28851 #endif
   28852   }
   28853   free(zConverted);
   28854   switch( flags ){
   28855     case SQLITE_ACCESS_READ:
   28856     case SQLITE_ACCESS_EXISTS:
   28857       rc = attr!=INVALID_FILE_ATTRIBUTES;
   28858       break;
   28859     case SQLITE_ACCESS_READWRITE:
   28860       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
   28861       break;
   28862     default:
   28863       assert(!"Invalid flags argument");
   28864   }
   28865   *pResOut = rc;
   28866   return SQLITE_OK;
   28867 }
   28868 
   28869 
   28870 /*
   28871 ** Turn a relative pathname into a full pathname.  Write the full
   28872 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
   28873 ** bytes in size.
   28874 */
   28875 static int winFullPathname(
   28876   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
   28877   const char *zRelative,        /* Possibly relative input path */
   28878   int nFull,                    /* Size of output buffer in bytes */
   28879   char *zFull                   /* Output buffer */
   28880 ){
   28881 
   28882 #if defined(__CYGWIN__)
   28883   UNUSED_PARAMETER(nFull);
   28884   cygwin_conv_to_full_win32_path(zRelative, zFull);
   28885   return SQLITE_OK;
   28886 #endif
   28887 
   28888 #if SQLITE_OS_WINCE
   28889   UNUSED_PARAMETER(nFull);
   28890   /* WinCE has no concept of a relative pathname, or so I am told. */
   28891   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
   28892   return SQLITE_OK;
   28893 #endif
   28894 
   28895 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
   28896   int nByte;
   28897   void *zConverted;
   28898   char *zOut;
   28899   UNUSED_PARAMETER(nFull);
   28900   zConverted = convertUtf8Filename(zRelative);
   28901   if( isNT() ){
   28902     WCHAR *zTemp;
   28903     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
   28904     zTemp = malloc( nByte*sizeof(zTemp[0]) );
   28905     if( zTemp==0 ){
   28906       free(zConverted);
   28907       return SQLITE_NOMEM;
   28908     }
   28909     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
   28910     free(zConverted);
   28911     zOut = unicodeToUtf8(zTemp);
   28912     free(zTemp);
   28913 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   28914 ** Since the ASCII version of these Windows API do not exist for WINCE,
   28915 ** it's important to not reference them for WINCE builds.
   28916 */
   28917 #if SQLITE_OS_WINCE==0
   28918   }else{
   28919     char *zTemp;
   28920     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
   28921     zTemp = malloc( nByte*sizeof(zTemp[0]) );
   28922     if( zTemp==0 ){
   28923       free(zConverted);
   28924       return SQLITE_NOMEM;
   28925     }
   28926     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
   28927     free(zConverted);
   28928     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
   28929     free(zTemp);
   28930 #endif
   28931   }
   28932   if( zOut ){
   28933     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
   28934     free(zOut);
   28935     return SQLITE_OK;
   28936   }else{
   28937     return SQLITE_NOMEM;
   28938   }
   28939 #endif
   28940 }
   28941 
   28942 /*
   28943 ** Get the sector size of the device used to store
   28944 ** file.
   28945 */
   28946 static int getSectorSize(
   28947     sqlite3_vfs *pVfs,
   28948     const char *zRelative     /* UTF-8 file name */
   28949 ){
   28950   DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
   28951   /* GetDiskFreeSpace is not supported under WINCE */
   28952 #if SQLITE_OS_WINCE
   28953   UNUSED_PARAMETER(pVfs);
   28954   UNUSED_PARAMETER(zRelative);
   28955 #else
   28956   char zFullpath[MAX_PATH+1];
   28957   int rc;
   28958   DWORD dwRet = 0;
   28959   DWORD dwDummy;
   28960 
   28961   /*
   28962   ** We need to get the full path name of the file
   28963   ** to get the drive letter to look up the sector
   28964   ** size.
   28965   */
   28966   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
   28967   if( rc == SQLITE_OK )
   28968   {
   28969     void *zConverted = convertUtf8Filename(zFullpath);
   28970     if( zConverted ){
   28971       if( isNT() ){
   28972         /* trim path to just drive reference */
   28973         WCHAR *p = zConverted;
   28974         for(;*p;p++){
   28975           if( *p == '\\' ){
   28976             *p = '\0';
   28977             break;
   28978           }
   28979         }
   28980         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
   28981                                   &dwDummy,
   28982                                   &bytesPerSector,
   28983                                   &dwDummy,
   28984                                   &dwDummy);
   28985       }else{
   28986         /* trim path to just drive reference */
   28987         char *p = (char *)zConverted;
   28988         for(;*p;p++){
   28989           if( *p == '\\' ){
   28990             *p = '\0';
   28991             break;
   28992           }
   28993         }
   28994         dwRet = GetDiskFreeSpaceA((char*)zConverted,
   28995                                   &dwDummy,
   28996                                   &bytesPerSector,
   28997                                   &dwDummy,
   28998                                   &dwDummy);
   28999       }
   29000       free(zConverted);
   29001     }
   29002     if( !dwRet ){
   29003       bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
   29004     }
   29005   }
   29006 #endif
   29007   return (int) bytesPerSector;
   29008 }
   29009 
   29010 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   29011 /*
   29012 ** Interfaces for opening a shared library, finding entry points
   29013 ** within the shared library, and closing the shared library.
   29014 */
   29015 /*
   29016 ** Interfaces for opening a shared library, finding entry points
   29017 ** within the shared library, and closing the shared library.
   29018 */
   29019 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
   29020   HANDLE h;
   29021   void *zConverted = convertUtf8Filename(zFilename);
   29022   UNUSED_PARAMETER(pVfs);
   29023   if( zConverted==0 ){
   29024     return 0;
   29025   }
   29026   if( isNT() ){
   29027     h = LoadLibraryW((WCHAR*)zConverted);
   29028 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   29029 ** Since the ASCII version of these Windows API do not exist for WINCE,
   29030 ** it's important to not reference them for WINCE builds.
   29031 */
   29032 #if SQLITE_OS_WINCE==0
   29033   }else{
   29034     h = LoadLibraryA((char*)zConverted);
   29035 #endif
   29036   }
   29037   free(zConverted);
   29038   return (void*)h;
   29039 }
   29040 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
   29041   UNUSED_PARAMETER(pVfs);
   29042   getLastErrorMsg(nBuf, zBufOut);
   29043 }
   29044 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
   29045   UNUSED_PARAMETER(pVfs);
   29046 #if SQLITE_OS_WINCE
   29047   /* The GetProcAddressA() routine is only available on wince. */
   29048   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
   29049 #else
   29050   /* All other windows platforms expect GetProcAddress() to take
   29051   ** an Ansi string regardless of the _UNICODE setting */
   29052   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
   29053 #endif
   29054 }
   29055 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
   29056   UNUSED_PARAMETER(pVfs);
   29057   FreeLibrary((HANDLE)pHandle);
   29058 }
   29059 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   29060   #define winDlOpen  0
   29061   #define winDlError 0
   29062   #define winDlSym   0
   29063   #define winDlClose 0
   29064 #endif
   29065 
   29066 
   29067 /*
   29068 ** Write up to nBuf bytes of randomness into zBuf.
   29069 */
   29070 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   29071   int n = 0;
   29072   UNUSED_PARAMETER(pVfs);
   29073 #if defined(SQLITE_TEST)
   29074   n = nBuf;
   29075   memset(zBuf, 0, nBuf);
   29076 #else
   29077   if( sizeof(SYSTEMTIME)<=nBuf-n ){
   29078     SYSTEMTIME x;
   29079     GetSystemTime(&x);
   29080     memcpy(&zBuf[n], &x, sizeof(x));
   29081     n += sizeof(x);
   29082   }
   29083   if( sizeof(DWORD)<=nBuf-n ){
   29084     DWORD pid = GetCurrentProcessId();
   29085     memcpy(&zBuf[n], &pid, sizeof(pid));
   29086     n += sizeof(pid);
   29087   }
   29088   if( sizeof(DWORD)<=nBuf-n ){
   29089     DWORD cnt = GetTickCount();
   29090     memcpy(&zBuf[n], &cnt, sizeof(cnt));
   29091     n += sizeof(cnt);
   29092   }
   29093   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
   29094     LARGE_INTEGER i;
   29095     QueryPerformanceCounter(&i);
   29096     memcpy(&zBuf[n], &i, sizeof(i));
   29097     n += sizeof(i);
   29098   }
   29099 #endif
   29100   return n;
   29101 }
   29102 
   29103 
   29104 /*
   29105 ** Sleep for a little while.  Return the amount of time slept.
   29106 */
   29107 static int winSleep(sqlite3_vfs *pVfs, int microsec){
   29108   Sleep((microsec+999)/1000);
   29109   UNUSED_PARAMETER(pVfs);
   29110   return ((microsec+999)/1000)*1000;
   29111 }
   29112 
   29113 /*
   29114 ** The following variable, if set to a non-zero value, becomes the result
   29115 ** returned from sqlite3OsCurrentTime().  This is used for testing.
   29116 */
   29117 #ifdef SQLITE_TEST
   29118 SQLITE_API int sqlite3_current_time = 0;
   29119 #endif
   29120 
   29121 /*
   29122 ** Find the current time (in Universal Coordinated Time).  Write the
   29123 ** current time and date as a Julian Day number into *prNow and
   29124 ** return 0.  Return 1 if the time and date cannot be found.
   29125 */
   29126 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
   29127   FILETIME ft;
   29128   /* FILETIME structure is a 64-bit value representing the number of
   29129      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
   29130   */
   29131   sqlite3_int64 timeW;   /* Whole days */
   29132   sqlite3_int64 timeF;   /* Fractional Days */
   29133 
   29134   /* Number of 100-nanosecond intervals in a single day */
   29135   static const sqlite3_int64 ntuPerDay =
   29136       10000000*(sqlite3_int64)86400;
   29137 
   29138   /* Number of 100-nanosecond intervals in half of a day */
   29139   static const sqlite3_int64 ntuPerHalfDay =
   29140       10000000*(sqlite3_int64)43200;
   29141 
   29142   /* 2^32 - to avoid use of LL and warnings in gcc */
   29143   static const sqlite3_int64 max32BitValue =
   29144       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
   29145 
   29146 #if SQLITE_OS_WINCE
   29147   SYSTEMTIME time;
   29148   GetSystemTime(&time);
   29149   /* if SystemTimeToFileTime() fails, it returns zero. */
   29150   if (!SystemTimeToFileTime(&time,&ft)){
   29151     return 1;
   29152   }
   29153 #else
   29154   GetSystemTimeAsFileTime( &ft );
   29155 #endif
   29156   UNUSED_PARAMETER(pVfs);
   29157   timeW = (((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + (sqlite3_int64)ft.dwLowDateTime;
   29158   timeF = timeW % ntuPerDay;          /* fractional days (100-nanoseconds) */
   29159   timeW = timeW / ntuPerDay;          /* whole days */
   29160   timeW = timeW + 2305813;            /* add whole days (from 2305813.5) */
   29161   timeF = timeF + ntuPerHalfDay;      /* add half a day (from 2305813.5) */
   29162   timeW = timeW + (timeF/ntuPerDay);  /* add whole day if half day made one */
   29163   timeF = timeF % ntuPerDay;          /* compute new fractional days */
   29164   *prNow = (double)timeW + ((double)timeF / (double)ntuPerDay);
   29165 #ifdef SQLITE_TEST
   29166   if( sqlite3_current_time ){
   29167     *prNow = ((double)sqlite3_current_time + (double)43200) / (double)86400 + (double)2440587;
   29168   }
   29169 #endif
   29170   return 0;
   29171 }
   29172 
   29173 /*
   29174 ** The idea is that this function works like a combination of
   29175 ** GetLastError() and FormatMessage() on windows (or errno and
   29176 ** strerror_r() on unix). After an error is returned by an OS
   29177 ** function, SQLite calls this function with zBuf pointing to
   29178 ** a buffer of nBuf bytes. The OS layer should populate the
   29179 ** buffer with a nul-terminated UTF-8 encoded error message
   29180 ** describing the last IO error to have occurred within the calling
   29181 ** thread.
   29182 **
   29183 ** If the error message is too large for the supplied buffer,
   29184 ** it should be truncated. The return value of xGetLastError
   29185 ** is zero if the error message fits in the buffer, or non-zero
   29186 ** otherwise (if the message was truncated). If non-zero is returned,
   29187 ** then it is not necessary to include the nul-terminator character
   29188 ** in the output buffer.
   29189 **
   29190 ** Not supplying an error message will have no adverse effect
   29191 ** on SQLite. It is fine to have an implementation that never
   29192 ** returns an error message:
   29193 **
   29194 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   29195 **     assert(zBuf[0]=='\0');
   29196 **     return 0;
   29197 **   }
   29198 **
   29199 ** However if an error message is supplied, it will be incorporated
   29200 ** by sqlite into the error message available to the user using
   29201 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
   29202 */
   29203 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   29204   UNUSED_PARAMETER(pVfs);
   29205   return getLastErrorMsg(nBuf, zBuf);
   29206 }
   29207 
   29208 /*
   29209 ** Initialize and deinitialize the operating system interface.
   29210 */
   29211 SQLITE_API int sqlite3_os_init(void){
   29212   static sqlite3_vfs winVfs = {
   29213     1,                 /* iVersion */
   29214     sizeof(winFile),   /* szOsFile */
   29215     MAX_PATH,          /* mxPathname */
   29216     0,                 /* pNext */
   29217     "win32",           /* zName */
   29218     0,                 /* pAppData */
   29219 
   29220     winOpen,           /* xOpen */
   29221     winDelete,         /* xDelete */
   29222     winAccess,         /* xAccess */
   29223     winFullPathname,   /* xFullPathname */
   29224     winDlOpen,         /* xDlOpen */
   29225     winDlError,        /* xDlError */
   29226     winDlSym,          /* xDlSym */
   29227     winDlClose,        /* xDlClose */
   29228     winRandomness,     /* xRandomness */
   29229     winSleep,          /* xSleep */
   29230     winCurrentTime,    /* xCurrentTime */
   29231     winGetLastError    /* xGetLastError */
   29232   };
   29233 
   29234   sqlite3_vfs_register(&winVfs, 1);
   29235   return SQLITE_OK;
   29236 }
   29237 SQLITE_API int sqlite3_os_end(void){
   29238   return SQLITE_OK;
   29239 }
   29240 
   29241 #endif /* SQLITE_OS_WIN */
   29242 
   29243 /************** End of os_win.c **********************************************/
   29244 /************** Begin file bitvec.c ******************************************/
   29245 /*
   29246 ** 2008 February 16
   29247 **
   29248 ** The author disclaims copyright to this source code.  In place of
   29249 ** a legal notice, here is a blessing:
   29250 **
   29251 **    May you do good and not evil.
   29252 **    May you find forgiveness for yourself and forgive others.
   29253 **    May you share freely, never taking more than you give.
   29254 **
   29255 *************************************************************************
   29256 ** This file implements an object that represents a fixed-length
   29257 ** bitmap.  Bits are numbered starting with 1.
   29258 **
   29259 ** A bitmap is used to record which pages of a database file have been
   29260 ** journalled during a transaction, or which pages have the "dont-write"
   29261 ** property.  Usually only a few pages are meet either condition.
   29262 ** So the bitmap is usually sparse and has low cardinality.
   29263 ** But sometimes (for example when during a DROP of a large table) most
   29264 ** or all of the pages in a database can get journalled.  In those cases,
   29265 ** the bitmap becomes dense with high cardinality.  The algorithm needs
   29266 ** to handle both cases well.
   29267 **
   29268 ** The size of the bitmap is fixed when the object is created.
   29269 **
   29270 ** All bits are clear when the bitmap is created.  Individual bits
   29271 ** may be set or cleared one at a time.
   29272 **
   29273 ** Test operations are about 100 times more common that set operations.
   29274 ** Clear operations are exceedingly rare.  There are usually between
   29275 ** 5 and 500 set operations per Bitvec object, though the number of sets can
   29276 ** sometimes grow into tens of thousands or larger.  The size of the
   29277 ** Bitvec object is the number of pages in the database file at the
   29278 ** start of a transaction, and is thus usually less than a few thousand,
   29279 ** but can be as large as 2 billion for a really big database.
   29280 */
   29281 
   29282 /* Size of the Bitvec structure in bytes. */
   29283 #define BITVEC_SZ        (sizeof(void*)*128)  /* 512 on 32bit.  1024 on 64bit */
   29284 
   29285 /* Round the union size down to the nearest pointer boundary, since that's how
   29286 ** it will be aligned within the Bitvec struct. */
   29287 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
   29288 
   29289 /* Type of the array "element" for the bitmap representation.
   29290 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
   29291 ** Setting this to the "natural word" size of your CPU may improve
   29292 ** performance. */
   29293 #define BITVEC_TELEM     u8
   29294 /* Size, in bits, of the bitmap element. */
   29295 #define BITVEC_SZELEM    8
   29296 /* Number of elements in a bitmap array. */
   29297 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
   29298 /* Number of bits in the bitmap array. */
   29299 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
   29300 
   29301 /* Number of u32 values in hash table. */
   29302 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
   29303 /* Maximum number of entries in hash table before
   29304 ** sub-dividing and re-hashing. */
   29305 #define BITVEC_MXHASH    (BITVEC_NINT/2)
   29306 /* Hashing function for the aHash representation.
   29307 ** Empirical testing showed that the *37 multiplier
   29308 ** (an arbitrary prime)in the hash function provided
   29309 ** no fewer collisions than the no-op *1. */
   29310 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
   29311 
   29312 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
   29313 
   29314 
   29315 /*
   29316 ** A bitmap is an instance of the following structure.
   29317 **
   29318 ** This bitmap records the existance of zero or more bits
   29319 ** with values between 1 and iSize, inclusive.
   29320 **
   29321 ** There are three possible representations of the bitmap.
   29322 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
   29323 ** bitmap.  The least significant bit is bit 1.
   29324 **
   29325 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
   29326 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
   29327 **
   29328 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
   29329 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
   29330 ** handles up to iDivisor separate values of i.  apSub[0] holds
   29331 ** values between 1 and iDivisor.  apSub[1] holds values between
   29332 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
   29333 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
   29334 ** to hold deal with values between 1 and iDivisor.
   29335 */
   29336 struct Bitvec {
   29337   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
   29338   u32 nSet;       /* Number of bits that are set - only valid for aHash
   29339                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
   29340                   ** this would be 125. */
   29341   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
   29342                   /* Should >=0 for apSub element. */
   29343                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
   29344                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
   29345   union {
   29346     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
   29347     u32 aHash[BITVEC_NINT];      /* Hash table representation */
   29348     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
   29349   } u;
   29350 };
   29351 
   29352 /*
   29353 ** Create a new bitmap object able to handle bits between 0 and iSize,
   29354 ** inclusive.  Return a pointer to the new object.  Return NULL if
   29355 ** malloc fails.
   29356 */
   29357 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
   29358   Bitvec *p;
   29359   assert( sizeof(*p)==BITVEC_SZ );
   29360   p = sqlite3MallocZero( sizeof(*p) );
   29361   if( p ){
   29362     p->iSize = iSize;
   29363   }
   29364   return p;
   29365 }
   29366 
   29367 /*
   29368 ** Check to see if the i-th bit is set.  Return true or false.
   29369 ** If p is NULL (if the bitmap has not been created) or if
   29370 ** i is out of range, then return false.
   29371 */
   29372 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
   29373   if( p==0 ) return 0;
   29374   if( i>p->iSize || i==0 ) return 0;
   29375   i--;
   29376   while( p->iDivisor ){
   29377     u32 bin = i/p->iDivisor;
   29378     i = i%p->iDivisor;
   29379     p = p->u.apSub[bin];
   29380     if (!p) {
   29381       return 0;
   29382     }
   29383   }
   29384   if( p->iSize<=BITVEC_NBIT ){
   29385     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
   29386   } else{
   29387     u32 h = BITVEC_HASH(i++);
   29388     while( p->u.aHash[h] ){
   29389       if( p->u.aHash[h]==i ) return 1;
   29390       h = (h+1) % BITVEC_NINT;
   29391     }
   29392     return 0;
   29393   }
   29394 }
   29395 
   29396 /*
   29397 ** Set the i-th bit.  Return 0 on success and an error code if
   29398 ** anything goes wrong.
   29399 **
   29400 ** This routine might cause sub-bitmaps to be allocated.  Failing
   29401 ** to get the memory needed to hold the sub-bitmap is the only
   29402 ** that can go wrong with an insert, assuming p and i are valid.
   29403 **
   29404 ** The calling function must ensure that p is a valid Bitvec object
   29405 ** and that the value for "i" is within range of the Bitvec object.
   29406 ** Otherwise the behavior is undefined.
   29407 */
   29408 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
   29409   u32 h;
   29410   if( p==0 ) return SQLITE_OK;
   29411   assert( i>0 );
   29412   assert( i<=p->iSize );
   29413   i--;
   29414   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
   29415     u32 bin = i/p->iDivisor;
   29416     i = i%p->iDivisor;
   29417     if( p->u.apSub[bin]==0 ){
   29418       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
   29419       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
   29420     }
   29421     p = p->u.apSub[bin];
   29422   }
   29423   if( p->iSize<=BITVEC_NBIT ){
   29424     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
   29425     return SQLITE_OK;
   29426   }
   29427   h = BITVEC_HASH(i++);
   29428   /* if there wasn't a hash collision, and this doesn't */
   29429   /* completely fill the hash, then just add it without */
   29430   /* worring about sub-dividing and re-hashing. */
   29431   if( !p->u.aHash[h] ){
   29432     if (p->nSet<(BITVEC_NINT-1)) {
   29433       goto bitvec_set_end;
   29434     } else {
   29435       goto bitvec_set_rehash;
   29436     }
   29437   }
   29438   /* there was a collision, check to see if it's already */
   29439   /* in hash, if not, try to find a spot for it */
   29440   do {
   29441     if( p->u.aHash[h]==i ) return SQLITE_OK;
   29442     h++;
   29443     if( h>=BITVEC_NINT ) h = 0;
   29444   } while( p->u.aHash[h] );
   29445   /* we didn't find it in the hash.  h points to the first */
   29446   /* available free spot. check to see if this is going to */
   29447   /* make our hash too "full".  */
   29448 bitvec_set_rehash:
   29449   if( p->nSet>=BITVEC_MXHASH ){
   29450     unsigned int j;
   29451     int rc;
   29452     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
   29453     if( aiValues==0 ){
   29454       return SQLITE_NOMEM;
   29455     }else{
   29456       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
   29457       memset(p->u.apSub, 0, sizeof(p->u.apSub));
   29458       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
   29459       rc = sqlite3BitvecSet(p, i);
   29460       for(j=0; j<BITVEC_NINT; j++){
   29461         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
   29462       }
   29463       sqlite3StackFree(0, aiValues);
   29464       return rc;
   29465     }
   29466   }
   29467 bitvec_set_end:
   29468   p->nSet++;
   29469   p->u.aHash[h] = i;
   29470   return SQLITE_OK;
   29471 }
   29472 
   29473 /*
   29474 ** Clear the i-th bit.
   29475 **
   29476 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
   29477 ** that BitvecClear can use to rebuilt its hash table.
   29478 */
   29479 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
   29480   if( p==0 ) return;
   29481   assert( i>0 );
   29482   i--;
   29483   while( p->iDivisor ){
   29484     u32 bin = i/p->iDivisor;
   29485     i = i%p->iDivisor;
   29486     p = p->u.apSub[bin];
   29487     if (!p) {
   29488       return;
   29489     }
   29490   }
   29491   if( p->iSize<=BITVEC_NBIT ){
   29492     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
   29493   }else{
   29494     unsigned int j;
   29495     u32 *aiValues = pBuf;
   29496     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
   29497     memset(p->u.aHash, 0, sizeof(p->u.aHash));
   29498     p->nSet = 0;
   29499     for(j=0; j<BITVEC_NINT; j++){
   29500       if( aiValues[j] && aiValues[j]!=(i+1) ){
   29501         u32 h = BITVEC_HASH(aiValues[j]-1);
   29502         p->nSet++;
   29503         while( p->u.aHash[h] ){
   29504           h++;
   29505           if( h>=BITVEC_NINT ) h = 0;
   29506         }
   29507         p->u.aHash[h] = aiValues[j];
   29508       }
   29509     }
   29510   }
   29511 }
   29512 
   29513 /*
   29514 ** Destroy a bitmap object.  Reclaim all memory used.
   29515 */
   29516 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
   29517   if( p==0 ) return;
   29518   if( p->iDivisor ){
   29519     unsigned int i;
   29520     for(i=0; i<BITVEC_NPTR; i++){
   29521       sqlite3BitvecDestroy(p->u.apSub[i]);
   29522     }
   29523   }
   29524   sqlite3_free(p);
   29525 }
   29526 
   29527 /*
   29528 ** Return the value of the iSize parameter specified when Bitvec *p
   29529 ** was created.
   29530 */
   29531 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
   29532   return p->iSize;
   29533 }
   29534 
   29535 #ifndef SQLITE_OMIT_BUILTIN_TEST
   29536 /*
   29537 ** Let V[] be an array of unsigned characters sufficient to hold
   29538 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
   29539 ** Then the following macros can be used to set, clear, or test
   29540 ** individual bits within V.
   29541 */
   29542 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
   29543 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
   29544 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
   29545 
   29546 /*
   29547 ** This routine runs an extensive test of the Bitvec code.
   29548 **
   29549 ** The input is an array of integers that acts as a program
   29550 ** to test the Bitvec.  The integers are opcodes followed
   29551 ** by 0, 1, or 3 operands, depending on the opcode.  Another
   29552 ** opcode follows immediately after the last operand.
   29553 **
   29554 ** There are 6 opcodes numbered from 0 through 5.  0 is the
   29555 ** "halt" opcode and causes the test to end.
   29556 **
   29557 **    0          Halt and return the number of errors
   29558 **    1 N S X    Set N bits beginning with S and incrementing by X
   29559 **    2 N S X    Clear N bits beginning with S and incrementing by X
   29560 **    3 N        Set N randomly chosen bits
   29561 **    4 N        Clear N randomly chosen bits
   29562 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
   29563 **
   29564 ** The opcodes 1 through 4 perform set and clear operations are performed
   29565 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
   29566 ** Opcode 5 works on the linear array only, not on the Bitvec.
   29567 ** Opcode 5 is used to deliberately induce a fault in order to
   29568 ** confirm that error detection works.
   29569 **
   29570 ** At the conclusion of the test the linear array is compared
   29571 ** against the Bitvec object.  If there are any differences,
   29572 ** an error is returned.  If they are the same, zero is returned.
   29573 **
   29574 ** If a memory allocation error occurs, return -1.
   29575 */
   29576 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
   29577   Bitvec *pBitvec = 0;
   29578   unsigned char *pV = 0;
   29579   int rc = -1;
   29580   int i, nx, pc, op;
   29581   void *pTmpSpace;
   29582 
   29583   /* Allocate the Bitvec to be tested and a linear array of
   29584   ** bits to act as the reference */
   29585   pBitvec = sqlite3BitvecCreate( sz );
   29586   pV = sqlite3_malloc( (sz+7)/8 + 1 );
   29587   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
   29588   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
   29589   memset(pV, 0, (sz+7)/8 + 1);
   29590 
   29591   /* NULL pBitvec tests */
   29592   sqlite3BitvecSet(0, 1);
   29593   sqlite3BitvecClear(0, 1, pTmpSpace);
   29594 
   29595   /* Run the program */
   29596   pc = 0;
   29597   while( (op = aOp[pc])!=0 ){
   29598     switch( op ){
   29599       case 1:
   29600       case 2:
   29601       case 5: {
   29602         nx = 4;
   29603         i = aOp[pc+2] - 1;
   29604         aOp[pc+2] += aOp[pc+3];
   29605         break;
   29606       }
   29607       case 3:
   29608       case 4:
   29609       default: {
   29610         nx = 2;
   29611         sqlite3_randomness(sizeof(i), &i);
   29612         break;
   29613       }
   29614     }
   29615     if( (--aOp[pc+1]) > 0 ) nx = 0;
   29616     pc += nx;
   29617     i = (i & 0x7fffffff)%sz;
   29618     if( (op & 1)!=0 ){
   29619       SETBIT(pV, (i+1));
   29620       if( op!=5 ){
   29621         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
   29622       }
   29623     }else{
   29624       CLEARBIT(pV, (i+1));
   29625       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
   29626     }
   29627   }
   29628 
   29629   /* Test to make sure the linear array exactly matches the
   29630   ** Bitvec object.  Start with the assumption that they do
   29631   ** match (rc==0).  Change rc to non-zero if a discrepancy
   29632   ** is found.
   29633   */
   29634   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
   29635           + sqlite3BitvecTest(pBitvec, 0)
   29636           + (sqlite3BitvecSize(pBitvec) - sz);
   29637   for(i=1; i<=sz; i++){
   29638     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
   29639       rc = i;
   29640       break;
   29641     }
   29642   }
   29643 
   29644   /* Free allocated structure */
   29645 bitvec_end:
   29646   sqlite3_free(pTmpSpace);
   29647   sqlite3_free(pV);
   29648   sqlite3BitvecDestroy(pBitvec);
   29649   return rc;
   29650 }
   29651 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   29652 
   29653 /************** End of bitvec.c **********************************************/
   29654 /************** Begin file pcache.c ******************************************/
   29655 /*
   29656 ** 2008 August 05
   29657 **
   29658 ** The author disclaims copyright to this source code.  In place of
   29659 ** a legal notice, here is a blessing:
   29660 **
   29661 **    May you do good and not evil.
   29662 **    May you find forgiveness for yourself and forgive others.
   29663 **    May you share freely, never taking more than you give.
   29664 **
   29665 *************************************************************************
   29666 ** This file implements that page cache.
   29667 */
   29668 
   29669 /*
   29670 ** A complete page cache is an instance of this structure.
   29671 */
   29672 struct PCache {
   29673   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
   29674   PgHdr *pSynced;                     /* Last synced page in dirty page list */
   29675   int nRef;                           /* Number of referenced pages */
   29676   int nMax;                           /* Configured cache size */
   29677   int szPage;                         /* Size of every page in this cache */
   29678   int szExtra;                        /* Size of extra space for each page */
   29679   int bPurgeable;                     /* True if pages are on backing store */
   29680   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
   29681   void *pStress;                      /* Argument to xStress */
   29682   sqlite3_pcache *pCache;             /* Pluggable cache module */
   29683   PgHdr *pPage1;                      /* Reference to page 1 */
   29684 };
   29685 
   29686 /*
   29687 ** Some of the assert() macros in this code are too expensive to run
   29688 ** even during normal debugging.  Use them only rarely on long-running
   29689 ** tests.  Enable the expensive asserts using the
   29690 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
   29691 */
   29692 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   29693 # define expensive_assert(X)  assert(X)
   29694 #else
   29695 # define expensive_assert(X)
   29696 #endif
   29697 
   29698 /********************************** Linked List Management ********************/
   29699 
   29700 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
   29701 /*
   29702 ** Check that the pCache->pSynced variable is set correctly. If it
   29703 ** is not, either fail an assert or return zero. Otherwise, return
   29704 ** non-zero. This is only used in debugging builds, as follows:
   29705 **
   29706 **   expensive_assert( pcacheCheckSynced(pCache) );
   29707 */
   29708 static int pcacheCheckSynced(PCache *pCache){
   29709   PgHdr *p;
   29710   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
   29711     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
   29712   }
   29713   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
   29714 }
   29715 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
   29716 
   29717 /*
   29718 ** Remove page pPage from the list of dirty pages.
   29719 */
   29720 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
   29721   PCache *p = pPage->pCache;
   29722 
   29723   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
   29724   assert( pPage->pDirtyPrev || pPage==p->pDirty );
   29725 
   29726   /* Update the PCache1.pSynced variable if necessary. */
   29727   if( p->pSynced==pPage ){
   29728     PgHdr *pSynced = pPage->pDirtyPrev;
   29729     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
   29730       pSynced = pSynced->pDirtyPrev;
   29731     }
   29732     p->pSynced = pSynced;
   29733   }
   29734 
   29735   if( pPage->pDirtyNext ){
   29736     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
   29737   }else{
   29738     assert( pPage==p->pDirtyTail );
   29739     p->pDirtyTail = pPage->pDirtyPrev;
   29740   }
   29741   if( pPage->pDirtyPrev ){
   29742     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
   29743   }else{
   29744     assert( pPage==p->pDirty );
   29745     p->pDirty = pPage->pDirtyNext;
   29746   }
   29747   pPage->pDirtyNext = 0;
   29748   pPage->pDirtyPrev = 0;
   29749 
   29750   expensive_assert( pcacheCheckSynced(p) );
   29751 }
   29752 
   29753 /*
   29754 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
   29755 ** pPage).
   29756 */
   29757 static void pcacheAddToDirtyList(PgHdr *pPage){
   29758   PCache *p = pPage->pCache;
   29759 
   29760   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
   29761 
   29762   pPage->pDirtyNext = p->pDirty;
   29763   if( pPage->pDirtyNext ){
   29764     assert( pPage->pDirtyNext->pDirtyPrev==0 );
   29765     pPage->pDirtyNext->pDirtyPrev = pPage;
   29766   }
   29767   p->pDirty = pPage;
   29768   if( !p->pDirtyTail ){
   29769     p->pDirtyTail = pPage;
   29770   }
   29771   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
   29772     p->pSynced = pPage;
   29773   }
   29774   expensive_assert( pcacheCheckSynced(p) );
   29775 }
   29776 
   29777 /*
   29778 ** Wrapper around the pluggable caches xUnpin method. If the cache is
   29779 ** being used for an in-memory database, this function is a no-op.
   29780 */
   29781 static void pcacheUnpin(PgHdr *p){
   29782   PCache *pCache = p->pCache;
   29783   if( pCache->bPurgeable ){
   29784     if( p->pgno==1 ){
   29785       pCache->pPage1 = 0;
   29786     }
   29787     sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
   29788   }
   29789 }
   29790 
   29791 /*************************************************** General Interfaces ******
   29792 **
   29793 ** Initialize and shutdown the page cache subsystem. Neither of these
   29794 ** functions are threadsafe.
   29795 */
   29796 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
   29797   if( sqlite3GlobalConfig.pcache.xInit==0 ){
   29798     sqlite3PCacheSetDefault();
   29799   }
   29800   return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
   29801 }
   29802 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
   29803   if( sqlite3GlobalConfig.pcache.xShutdown ){
   29804     sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
   29805   }
   29806 }
   29807 
   29808 /*
   29809 ** Return the size in bytes of a PCache object.
   29810 */
   29811 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
   29812 
   29813 /*
   29814 ** Create a new PCache object. Storage space to hold the object
   29815 ** has already been allocated and is passed in as the p pointer.
   29816 ** The caller discovers how much space needs to be allocated by
   29817 ** calling sqlite3PcacheSize().
   29818 */
   29819 SQLITE_PRIVATE void sqlite3PcacheOpen(
   29820   int szPage,                  /* Size of every page */
   29821   int szExtra,                 /* Extra space associated with each page */
   29822   int bPurgeable,              /* True if pages are on backing store */
   29823   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
   29824   void *pStress,               /* Argument to xStress */
   29825   PCache *p                    /* Preallocated space for the PCache */
   29826 ){
   29827   memset(p, 0, sizeof(PCache));
   29828   p->szPage = szPage;
   29829   p->szExtra = szExtra;
   29830   p->bPurgeable = bPurgeable;
   29831   p->xStress = xStress;
   29832   p->pStress = pStress;
   29833   p->nMax = 100;
   29834 }
   29835 
   29836 /*
   29837 ** Change the page size for PCache object. The caller must ensure that there
   29838 ** are no outstanding page references when this function is called.
   29839 */
   29840 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
   29841   assert( pCache->nRef==0 && pCache->pDirty==0 );
   29842   if( pCache->pCache ){
   29843     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
   29844     pCache->pCache = 0;
   29845     pCache->pPage1 = 0;
   29846   }
   29847   pCache->szPage = szPage;
   29848 }
   29849 
   29850 /*
   29851 ** Try to obtain a page from the cache.
   29852 */
   29853 SQLITE_PRIVATE int sqlite3PcacheFetch(
   29854   PCache *pCache,       /* Obtain the page from this cache */
   29855   Pgno pgno,            /* Page number to obtain */
   29856   int createFlag,       /* If true, create page if it does not exist already */
   29857   PgHdr **ppPage        /* Write the page here */
   29858 ){
   29859   PgHdr *pPage = 0;
   29860   int eCreate;
   29861 
   29862   assert( pCache!=0 );
   29863   assert( createFlag==1 || createFlag==0 );
   29864   assert( pgno>0 );
   29865 
   29866   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
   29867   ** allocate it now.
   29868   */
   29869   if( !pCache->pCache && createFlag ){
   29870     sqlite3_pcache *p;
   29871     int nByte;
   29872     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
   29873     p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
   29874     if( !p ){
   29875       return SQLITE_NOMEM;
   29876     }
   29877     sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
   29878     pCache->pCache = p;
   29879   }
   29880 
   29881   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
   29882   if( pCache->pCache ){
   29883     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
   29884   }
   29885 
   29886   if( !pPage && eCreate==1 ){
   29887     PgHdr *pPg;
   29888 
   29889     /* Find a dirty page to write-out and recycle. First try to find a
   29890     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
   29891     ** cleared), but if that is not possible settle for any other
   29892     ** unreferenced dirty page.
   29893     */
   29894     expensive_assert( pcacheCheckSynced(pCache) );
   29895     for(pPg=pCache->pSynced;
   29896         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
   29897         pPg=pPg->pDirtyPrev
   29898     );
   29899     pCache->pSynced = pPg;
   29900     if( !pPg ){
   29901       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
   29902     }
   29903     if( pPg ){
   29904       int rc;
   29905       rc = pCache->xStress(pCache->pStress, pPg);
   29906       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
   29907         return rc;
   29908       }
   29909     }
   29910 
   29911     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
   29912   }
   29913 
   29914   if( pPage ){
   29915     if( !pPage->pData ){
   29916       memset(pPage, 0, sizeof(PgHdr) + pCache->szExtra);
   29917       pPage->pExtra = (void*)&pPage[1];
   29918       pPage->pData = (void *)&((char *)pPage)[sizeof(PgHdr) + pCache->szExtra];
   29919       pPage->pCache = pCache;
   29920       pPage->pgno = pgno;
   29921     }
   29922     assert( pPage->pCache==pCache );
   29923     assert( pPage->pgno==pgno );
   29924     assert( pPage->pExtra==(void *)&pPage[1] );
   29925 
   29926     if( 0==pPage->nRef ){
   29927       pCache->nRef++;
   29928     }
   29929     pPage->nRef++;
   29930     if( pgno==1 ){
   29931       pCache->pPage1 = pPage;
   29932     }
   29933   }
   29934   *ppPage = pPage;
   29935   return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
   29936 }
   29937 
   29938 /*
   29939 ** Decrement the reference count on a page. If the page is clean and the
   29940 ** reference count drops to 0, then it is made elible for recycling.
   29941 */
   29942 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
   29943   assert( p->nRef>0 );
   29944   p->nRef--;
   29945   if( p->nRef==0 ){
   29946     PCache *pCache = p->pCache;
   29947     pCache->nRef--;
   29948     if( (p->flags&PGHDR_DIRTY)==0 ){
   29949       pcacheUnpin(p);
   29950     }else{
   29951       /* Move the page to the head of the dirty list. */
   29952       pcacheRemoveFromDirtyList(p);
   29953       pcacheAddToDirtyList(p);
   29954     }
   29955   }
   29956 }
   29957 
   29958 /*
   29959 ** Increase the reference count of a supplied page by 1.
   29960 */
   29961 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
   29962   assert(p->nRef>0);
   29963   p->nRef++;
   29964 }
   29965 
   29966 /*
   29967 ** Drop a page from the cache. There must be exactly one reference to the
   29968 ** page. This function deletes that reference, so after it returns the
   29969 ** page pointed to by p is invalid.
   29970 */
   29971 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
   29972   PCache *pCache;
   29973   assert( p->nRef==1 );
   29974   if( p->flags&PGHDR_DIRTY ){
   29975     pcacheRemoveFromDirtyList(p);
   29976   }
   29977   pCache = p->pCache;
   29978   pCache->nRef--;
   29979   if( p->pgno==1 ){
   29980     pCache->pPage1 = 0;
   29981   }
   29982   sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
   29983 }
   29984 
   29985 /*
   29986 ** Make sure the page is marked as dirty. If it isn't dirty already,
   29987 ** make it so.
   29988 */
   29989 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
   29990   p->flags &= ~PGHDR_DONT_WRITE;
   29991   assert( p->nRef>0 );
   29992   if( 0==(p->flags & PGHDR_DIRTY) ){
   29993     p->flags |= PGHDR_DIRTY;
   29994     pcacheAddToDirtyList( p);
   29995   }
   29996 }
   29997 
   29998 /*
   29999 ** Make sure the page is marked as clean. If it isn't clean already,
   30000 ** make it so.
   30001 */
   30002 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
   30003   if( (p->flags & PGHDR_DIRTY) ){
   30004     pcacheRemoveFromDirtyList(p);
   30005     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
   30006     if( p->nRef==0 ){
   30007       pcacheUnpin(p);
   30008     }
   30009   }
   30010 }
   30011 
   30012 /*
   30013 ** Make every page in the cache clean.
   30014 */
   30015 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
   30016   PgHdr *p;
   30017   while( (p = pCache->pDirty)!=0 ){
   30018     sqlite3PcacheMakeClean(p);
   30019   }
   30020 }
   30021 
   30022 /*
   30023 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
   30024 */
   30025 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
   30026   PgHdr *p;
   30027   for(p=pCache->pDirty; p; p=p->pDirtyNext){
   30028     p->flags &= ~PGHDR_NEED_SYNC;
   30029   }
   30030   pCache->pSynced = pCache->pDirtyTail;
   30031 }
   30032 
   30033 /*
   30034 ** Change the page number of page p to newPgno.
   30035 */
   30036 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
   30037   PCache *pCache = p->pCache;
   30038   assert( p->nRef>0 );
   30039   assert( newPgno>0 );
   30040   sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
   30041   p->pgno = newPgno;
   30042   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
   30043     pcacheRemoveFromDirtyList(p);
   30044     pcacheAddToDirtyList(p);
   30045   }
   30046 }
   30047 
   30048 /*
   30049 ** Drop every cache entry whose page number is greater than "pgno". The
   30050 ** caller must ensure that there are no outstanding references to any pages
   30051 ** other than page 1 with a page number greater than pgno.
   30052 **
   30053 ** If there is a reference to page 1 and the pgno parameter passed to this
   30054 ** function is 0, then the data area associated with page 1 is zeroed, but
   30055 ** the page object is not dropped.
   30056 */
   30057 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
   30058   if( pCache->pCache ){
   30059     PgHdr *p;
   30060     PgHdr *pNext;
   30061     for(p=pCache->pDirty; p; p=pNext){
   30062       pNext = p->pDirtyNext;
   30063       if( p->pgno>pgno ){
   30064         assert( p->flags&PGHDR_DIRTY );
   30065         sqlite3PcacheMakeClean(p);
   30066       }
   30067     }
   30068     if( pgno==0 && pCache->pPage1 ){
   30069       memset(pCache->pPage1->pData, 0, pCache->szPage);
   30070       pgno = 1;
   30071     }
   30072     sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
   30073   }
   30074 }
   30075 
   30076 /*
   30077 ** Close a cache.
   30078 */
   30079 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
   30080   if( pCache->pCache ){
   30081     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
   30082   }
   30083 }
   30084 
   30085 /*
   30086 ** Discard the contents of the cache.
   30087 */
   30088 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
   30089   sqlite3PcacheTruncate(pCache, 0);
   30090 }
   30091 
   30092 /*
   30093 ** Merge two lists of pages connected by pDirty and in pgno order.
   30094 ** Do not both fixing the pDirtyPrev pointers.
   30095 */
   30096 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
   30097   PgHdr result, *pTail;
   30098   pTail = &result;
   30099   while( pA && pB ){
   30100     if( pA->pgno<pB->pgno ){
   30101       pTail->pDirty = pA;
   30102       pTail = pA;
   30103       pA = pA->pDirty;
   30104     }else{
   30105       pTail->pDirty = pB;
   30106       pTail = pB;
   30107       pB = pB->pDirty;
   30108     }
   30109   }
   30110   if( pA ){
   30111     pTail->pDirty = pA;
   30112   }else if( pB ){
   30113     pTail->pDirty = pB;
   30114   }else{
   30115     pTail->pDirty = 0;
   30116   }
   30117   return result.pDirty;
   30118 }
   30119 
   30120 /*
   30121 ** Sort the list of pages in accending order by pgno.  Pages are
   30122 ** connected by pDirty pointers.  The pDirtyPrev pointers are
   30123 ** corrupted by this sort.
   30124 **
   30125 ** Since there cannot be more than 2^31 distinct pages in a database,
   30126 ** there cannot be more than 31 buckets required by the merge sorter.
   30127 ** One extra bucket is added to catch overflow in case something
   30128 ** ever changes to make the previous sentence incorrect.
   30129 */
   30130 #define N_SORT_BUCKET  32
   30131 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
   30132   PgHdr *a[N_SORT_BUCKET], *p;
   30133   int i;
   30134   memset(a, 0, sizeof(a));
   30135   while( pIn ){
   30136     p = pIn;
   30137     pIn = p->pDirty;
   30138     p->pDirty = 0;
   30139     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
   30140       if( a[i]==0 ){
   30141         a[i] = p;
   30142         break;
   30143       }else{
   30144         p = pcacheMergeDirtyList(a[i], p);
   30145         a[i] = 0;
   30146       }
   30147     }
   30148     if( NEVER(i==N_SORT_BUCKET-1) ){
   30149       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
   30150       ** the input list.  But that is impossible.
   30151       */
   30152       a[i] = pcacheMergeDirtyList(a[i], p);
   30153     }
   30154   }
   30155   p = a[0];
   30156   for(i=1; i<N_SORT_BUCKET; i++){
   30157     p = pcacheMergeDirtyList(p, a[i]);
   30158   }
   30159   return p;
   30160 }
   30161 
   30162 /*
   30163 ** Return a list of all dirty pages in the cache, sorted by page number.
   30164 */
   30165 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
   30166   PgHdr *p;
   30167   for(p=pCache->pDirty; p; p=p->pDirtyNext){
   30168     p->pDirty = p->pDirtyNext;
   30169   }
   30170   return pcacheSortDirtyList(pCache->pDirty);
   30171 }
   30172 
   30173 /*
   30174 ** Return the total number of referenced pages held by the cache.
   30175 */
   30176 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
   30177   return pCache->nRef;
   30178 }
   30179 
   30180 /*
   30181 ** Return the number of references to the page supplied as an argument.
   30182 */
   30183 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
   30184   return p->nRef;
   30185 }
   30186 
   30187 /*
   30188 ** Return the total number of pages in the cache.
   30189 */
   30190 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
   30191   int nPage = 0;
   30192   if( pCache->pCache ){
   30193     nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
   30194   }
   30195   return nPage;
   30196 }
   30197 
   30198 #ifdef SQLITE_TEST
   30199 /*
   30200 ** Get the suggested cache-size value.
   30201 */
   30202 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
   30203   return pCache->nMax;
   30204 }
   30205 #endif
   30206 
   30207 /*
   30208 ** Set the suggested cache-size value.
   30209 */
   30210 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
   30211   pCache->nMax = mxPage;
   30212   if( pCache->pCache ){
   30213     sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
   30214   }
   30215 }
   30216 
   30217 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
   30218 /*
   30219 ** For all dirty pages currently in the cache, invoke the specified
   30220 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
   30221 ** defined.
   30222 */
   30223 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
   30224   PgHdr *pDirty;
   30225   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
   30226     xIter(pDirty);
   30227   }
   30228 }
   30229 #endif
   30230 
   30231 /************** End of pcache.c **********************************************/
   30232 /************** Begin file pcache1.c *****************************************/
   30233 /*
   30234 ** 2008 November 05
   30235 **
   30236 ** The author disclaims copyright to this source code.  In place of
   30237 ** a legal notice, here is a blessing:
   30238 **
   30239 **    May you do good and not evil.
   30240 **    May you find forgiveness for yourself and forgive others.
   30241 **    May you share freely, never taking more than you give.
   30242 **
   30243 *************************************************************************
   30244 **
   30245 ** This file implements the default page cache implementation (the
   30246 ** sqlite3_pcache interface). It also contains part of the implementation
   30247 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
   30248 ** If the default page cache implementation is overriden, then neither of
   30249 ** these two features are available.
   30250 */
   30251 
   30252 
   30253 typedef struct PCache1 PCache1;
   30254 typedef struct PgHdr1 PgHdr1;
   30255 typedef struct PgFreeslot PgFreeslot;
   30256 
   30257 /* Pointers to structures of this type are cast and returned as
   30258 ** opaque sqlite3_pcache* handles
   30259 */
   30260 struct PCache1 {
   30261   /* Cache configuration parameters. Page size (szPage) and the purgeable
   30262   ** flag (bPurgeable) are set when the cache is created. nMax may be
   30263   ** modified at any time by a call to the pcache1CacheSize() method.
   30264   ** The global mutex must be held when accessing nMax.
   30265   */
   30266   int szPage;                         /* Size of allocated pages in bytes */
   30267   int bPurgeable;                     /* True if cache is purgeable */
   30268   unsigned int nMin;                  /* Minimum number of pages reserved */
   30269   unsigned int nMax;                  /* Configured "cache_size" value */
   30270 
   30271   /* Hash table of all pages. The following variables may only be accessed
   30272   ** when the accessor is holding the global mutex (see pcache1EnterMutex()
   30273   ** and pcache1LeaveMutex()).
   30274   */
   30275   unsigned int nRecyclable;           /* Number of pages in the LRU list */
   30276   unsigned int nPage;                 /* Total number of pages in apHash */
   30277   unsigned int nHash;                 /* Number of slots in apHash[] */
   30278   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
   30279 
   30280   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
   30281 };
   30282 
   30283 /*
   30284 ** Each cache entry is represented by an instance of the following
   30285 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
   30286 ** directly before this structure in memory (see the PGHDR1_TO_PAGE()
   30287 ** macro below).
   30288 */
   30289 struct PgHdr1 {
   30290   unsigned int iKey;             /* Key value (page number) */
   30291   PgHdr1 *pNext;                 /* Next in hash table chain */
   30292   PCache1 *pCache;               /* Cache that currently owns this page */
   30293   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
   30294   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
   30295 };
   30296 
   30297 /*
   30298 ** Free slots in the allocator used to divide up the buffer provided using
   30299 ** the SQLITE_CONFIG_PAGECACHE mechanism.
   30300 */
   30301 struct PgFreeslot {
   30302   PgFreeslot *pNext;  /* Next free slot */
   30303 };
   30304 
   30305 /*
   30306 ** Global data used by this cache.
   30307 */
   30308 static SQLITE_WSD struct PCacheGlobal {
   30309   sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
   30310 
   30311   int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
   30312   int nMinPage;                       /* Sum of nMinPage for purgeable caches */
   30313   int nCurrentPage;                   /* Number of purgeable pages allocated */
   30314   PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */
   30315 
   30316   /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
   30317   int szSlot;                         /* Size of each free slot */
   30318   void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
   30319   PgFreeslot *pFree;                  /* Free page blocks */
   30320   int isInit;                         /* True if initialized */
   30321 } pcache1_g;
   30322 
   30323 /*
   30324 ** All code in this file should access the global structure above via the
   30325 ** alias "pcache1". This ensures that the WSD emulation is used when
   30326 ** compiling for systems that do not support real WSD.
   30327 */
   30328 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
   30329 
   30330 /*
   30331 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
   30332 ** bytes of data are located directly before it in memory (i.e. the total
   30333 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
   30334 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
   30335 ** an argument and returns a pointer to the associated block of szPage
   30336 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
   30337 ** a pointer to a block of szPage bytes of data and the return value is
   30338 ** a pointer to the associated PgHdr1 structure.
   30339 **
   30340 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
   30341 */
   30342 #define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
   30343 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
   30344 
   30345 /*
   30346 ** Macros to enter and leave the global LRU mutex.
   30347 */
   30348 #define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
   30349 #define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
   30350 
   30351 /******************************************************************************/
   30352 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
   30353 
   30354 /*
   30355 ** This function is called during initialization if a static buffer is
   30356 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
   30357 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
   30358 ** enough to contain 'n' buffers of 'sz' bytes each.
   30359 */
   30360 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
   30361   if( pcache1.isInit ){
   30362     PgFreeslot *p;
   30363     sz = ROUNDDOWN8(sz);
   30364     pcache1.szSlot = sz;
   30365     pcache1.pStart = pBuf;
   30366     pcache1.pFree = 0;
   30367     while( n-- ){
   30368       p = (PgFreeslot*)pBuf;
   30369       p->pNext = pcache1.pFree;
   30370       pcache1.pFree = p;
   30371       pBuf = (void*)&((char*)pBuf)[sz];
   30372     }
   30373     pcache1.pEnd = pBuf;
   30374   }
   30375 }
   30376 
   30377 /*
   30378 ** Malloc function used within this file to allocate space from the buffer
   30379 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
   30380 ** such buffer exists or there is no space left in it, this function falls
   30381 ** back to sqlite3Malloc().
   30382 */
   30383 static void *pcache1Alloc(int nByte){
   30384   void *p;
   30385   assert( sqlite3_mutex_held(pcache1.mutex) );
   30386   if( nByte<=pcache1.szSlot && pcache1.pFree ){
   30387     assert( pcache1.isInit );
   30388     p = (PgHdr1 *)pcache1.pFree;
   30389     pcache1.pFree = pcache1.pFree->pNext;
   30390     sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
   30391     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
   30392   }else{
   30393 
   30394     /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
   30395     ** global pcache mutex and unlock the pager-cache object pCache. This is
   30396     ** so that if the attempt to allocate a new buffer causes the the
   30397     ** configured soft-heap-limit to be breached, it will be possible to
   30398     ** reclaim memory from this pager-cache.
   30399     */
   30400     pcache1LeaveMutex();
   30401     p = sqlite3Malloc(nByte);
   30402     pcache1EnterMutex();
   30403     if( p ){
   30404       int sz = sqlite3MallocSize(p);
   30405       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
   30406     }
   30407   }
   30408   return p;
   30409 }
   30410 
   30411 /*
   30412 ** Free an allocated buffer obtained from pcache1Alloc().
   30413 */
   30414 static void pcache1Free(void *p){
   30415   assert( sqlite3_mutex_held(pcache1.mutex) );
   30416   if( p==0 ) return;
   30417   if( p>=pcache1.pStart && p<pcache1.pEnd ){
   30418     PgFreeslot *pSlot;
   30419     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
   30420     pSlot = (PgFreeslot*)p;
   30421     pSlot->pNext = pcache1.pFree;
   30422     pcache1.pFree = pSlot;
   30423   }else{
   30424     int iSize = sqlite3MallocSize(p);
   30425     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
   30426     sqlite3_free(p);
   30427   }
   30428 }
   30429 
   30430 /*
   30431 ** Allocate a new page object initially associated with cache pCache.
   30432 */
   30433 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
   30434   int nByte = sizeof(PgHdr1) + pCache->szPage;
   30435   void *pPg = pcache1Alloc(nByte);
   30436   PgHdr1 *p;
   30437   if( pPg ){
   30438     p = PAGE_TO_PGHDR1(pCache, pPg);
   30439     if( pCache->bPurgeable ){
   30440       pcache1.nCurrentPage++;
   30441     }
   30442   }else{
   30443     p = 0;
   30444   }
   30445   return p;
   30446 }
   30447 
   30448 /*
   30449 ** Free a page object allocated by pcache1AllocPage().
   30450 **
   30451 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
   30452 ** that the current implementation happens to never call this routine
   30453 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
   30454 */
   30455 static void pcache1FreePage(PgHdr1 *p){
   30456   if( ALWAYS(p) ){
   30457     if( p->pCache->bPurgeable ){
   30458       pcache1.nCurrentPage--;
   30459     }
   30460     pcache1Free(PGHDR1_TO_PAGE(p));
   30461   }
   30462 }
   30463 
   30464 /*
   30465 ** Malloc function used by SQLite to obtain space from the buffer configured
   30466 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
   30467 ** exists, this function falls back to sqlite3Malloc().
   30468 */
   30469 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
   30470   void *p;
   30471   pcache1EnterMutex();
   30472   p = pcache1Alloc(sz);
   30473   pcache1LeaveMutex();
   30474   return p;
   30475 }
   30476 
   30477 /*
   30478 ** Free an allocated buffer obtained from sqlite3PageMalloc().
   30479 */
   30480 SQLITE_PRIVATE void sqlite3PageFree(void *p){
   30481   pcache1EnterMutex();
   30482   pcache1Free(p);
   30483   pcache1LeaveMutex();
   30484 }
   30485 
   30486 /******************************************************************************/
   30487 /******** General Implementation Functions ************************************/
   30488 
   30489 /*
   30490 ** This function is used to resize the hash table used by the cache passed
   30491 ** as the first argument.
   30492 **
   30493 ** The global mutex must be held when this function is called.
   30494 */
   30495 static int pcache1ResizeHash(PCache1 *p){
   30496   PgHdr1 **apNew;
   30497   unsigned int nNew;
   30498   unsigned int i;
   30499 
   30500   assert( sqlite3_mutex_held(pcache1.mutex) );
   30501 
   30502   nNew = p->nHash*2;
   30503   if( nNew<256 ){
   30504     nNew = 256;
   30505   }
   30506 
   30507   pcache1LeaveMutex();
   30508   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
   30509   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
   30510   if( p->nHash ){ sqlite3EndBenignMalloc(); }
   30511   pcache1EnterMutex();
   30512   if( apNew ){
   30513     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
   30514     for(i=0; i<p->nHash; i++){
   30515       PgHdr1 *pPage;
   30516       PgHdr1 *pNext = p->apHash[i];
   30517       while( (pPage = pNext)!=0 ){
   30518         unsigned int h = pPage->iKey % nNew;
   30519         pNext = pPage->pNext;
   30520         pPage->pNext = apNew[h];
   30521         apNew[h] = pPage;
   30522       }
   30523     }
   30524     sqlite3_free(p->apHash);
   30525     p->apHash = apNew;
   30526     p->nHash = nNew;
   30527   }
   30528 
   30529   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
   30530 }
   30531 
   30532 /*
   30533 ** This function is used internally to remove the page pPage from the
   30534 ** global LRU list, if is part of it. If pPage is not part of the global
   30535 ** LRU list, then this function is a no-op.
   30536 **
   30537 ** The global mutex must be held when this function is called.
   30538 */
   30539 static void pcache1PinPage(PgHdr1 *pPage){
   30540   assert( sqlite3_mutex_held(pcache1.mutex) );
   30541   if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
   30542     if( pPage->pLruPrev ){
   30543       pPage->pLruPrev->pLruNext = pPage->pLruNext;
   30544     }
   30545     if( pPage->pLruNext ){
   30546       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
   30547     }
   30548     if( pcache1.pLruHead==pPage ){
   30549       pcache1.pLruHead = pPage->pLruNext;
   30550     }
   30551     if( pcache1.pLruTail==pPage ){
   30552       pcache1.pLruTail = pPage->pLruPrev;
   30553     }
   30554     pPage->pLruNext = 0;
   30555     pPage->pLruPrev = 0;
   30556     pPage->pCache->nRecyclable--;
   30557   }
   30558 }
   30559 
   30560 
   30561 /*
   30562 ** Remove the page supplied as an argument from the hash table
   30563 ** (PCache1.apHash structure) that it is currently stored in.
   30564 **
   30565 ** The global mutex must be held when this function is called.
   30566 */
   30567 static void pcache1RemoveFromHash(PgHdr1 *pPage){
   30568   unsigned int h;
   30569   PCache1 *pCache = pPage->pCache;
   30570   PgHdr1 **pp;
   30571 
   30572   h = pPage->iKey % pCache->nHash;
   30573   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
   30574   *pp = (*pp)->pNext;
   30575 
   30576   pCache->nPage--;
   30577 }
   30578 
   30579 /*
   30580 ** If there are currently more than pcache.nMaxPage pages allocated, try
   30581 ** to recycle pages to reduce the number allocated to pcache.nMaxPage.
   30582 */
   30583 static void pcache1EnforceMaxPage(void){
   30584   assert( sqlite3_mutex_held(pcache1.mutex) );
   30585   while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
   30586     PgHdr1 *p = pcache1.pLruTail;
   30587     pcache1PinPage(p);
   30588     pcache1RemoveFromHash(p);
   30589     pcache1FreePage(p);
   30590   }
   30591 }
   30592 
   30593 /*
   30594 ** Discard all pages from cache pCache with a page number (key value)
   30595 ** greater than or equal to iLimit. Any pinned pages that meet this
   30596 ** criteria are unpinned before they are discarded.
   30597 **
   30598 ** The global mutex must be held when this function is called.
   30599 */
   30600 static void pcache1TruncateUnsafe(
   30601   PCache1 *pCache,
   30602   unsigned int iLimit
   30603 ){
   30604   TESTONLY( unsigned int nPage = 0; )      /* Used to assert pCache->nPage is correct */
   30605   unsigned int h;
   30606   assert( sqlite3_mutex_held(pcache1.mutex) );
   30607   for(h=0; h<pCache->nHash; h++){
   30608     PgHdr1 **pp = &pCache->apHash[h];
   30609     PgHdr1 *pPage;
   30610     while( (pPage = *pp)!=0 ){
   30611       if( pPage->iKey>=iLimit ){
   30612         pCache->nPage--;
   30613         *pp = pPage->pNext;
   30614         pcache1PinPage(pPage);
   30615         pcache1FreePage(pPage);
   30616       }else{
   30617         pp = &pPage->pNext;
   30618         TESTONLY( nPage++; )
   30619       }
   30620     }
   30621   }
   30622   assert( pCache->nPage==nPage );
   30623 }
   30624 
   30625 /******************************************************************************/
   30626 /******** sqlite3_pcache Methods **********************************************/
   30627 
   30628 /*
   30629 ** Implementation of the sqlite3_pcache.xInit method.
   30630 */
   30631 static int pcache1Init(void *NotUsed){
   30632   UNUSED_PARAMETER(NotUsed);
   30633   assert( pcache1.isInit==0 );
   30634   memset(&pcache1, 0, sizeof(pcache1));
   30635   if( sqlite3GlobalConfig.bCoreMutex ){
   30636     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
   30637   }
   30638   pcache1.isInit = 1;
   30639   return SQLITE_OK;
   30640 }
   30641 
   30642 /*
   30643 ** Implementation of the sqlite3_pcache.xShutdown method.
   30644 ** Note that the static mutex allocated in xInit does
   30645 ** not need to be freed.
   30646 */
   30647 static void pcache1Shutdown(void *NotUsed){
   30648   UNUSED_PARAMETER(NotUsed);
   30649   assert( pcache1.isInit!=0 );
   30650   memset(&pcache1, 0, sizeof(pcache1));
   30651 }
   30652 
   30653 /*
   30654 ** Implementation of the sqlite3_pcache.xCreate method.
   30655 **
   30656 ** Allocate a new cache.
   30657 */
   30658 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
   30659   PCache1 *pCache;
   30660 
   30661   pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
   30662   if( pCache ){
   30663     memset(pCache, 0, sizeof(PCache1));
   30664     pCache->szPage = szPage;
   30665     pCache->bPurgeable = (bPurgeable ? 1 : 0);
   30666     if( bPurgeable ){
   30667       pCache->nMin = 10;
   30668       pcache1EnterMutex();
   30669       pcache1.nMinPage += pCache->nMin;
   30670       pcache1LeaveMutex();
   30671     }
   30672   }
   30673   return (sqlite3_pcache *)pCache;
   30674 }
   30675 
   30676 /*
   30677 ** Implementation of the sqlite3_pcache.xCachesize method.
   30678 **
   30679 ** Configure the cache_size limit for a cache.
   30680 */
   30681 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
   30682   PCache1 *pCache = (PCache1 *)p;
   30683   if( pCache->bPurgeable ){
   30684     pcache1EnterMutex();
   30685     pcache1.nMaxPage += (nMax - pCache->nMax);
   30686     pCache->nMax = nMax;
   30687     pcache1EnforceMaxPage();
   30688     pcache1LeaveMutex();
   30689   }
   30690 }
   30691 
   30692 /*
   30693 ** Implementation of the sqlite3_pcache.xPagecount method.
   30694 */
   30695 static int pcache1Pagecount(sqlite3_pcache *p){
   30696   int n;
   30697   pcache1EnterMutex();
   30698   n = ((PCache1 *)p)->nPage;
   30699   pcache1LeaveMutex();
   30700   return n;
   30701 }
   30702 
   30703 /*
   30704 ** Implementation of the sqlite3_pcache.xFetch method.
   30705 **
   30706 ** Fetch a page by key value.
   30707 **
   30708 ** Whether or not a new page may be allocated by this function depends on
   30709 ** the value of the createFlag argument.  0 means do not allocate a new
   30710 ** page.  1 means allocate a new page if space is easily available.  2
   30711 ** means to try really hard to allocate a new page.
   30712 **
   30713 ** For a non-purgeable cache (a cache used as the storage for an in-memory
   30714 ** database) there is really no difference between createFlag 1 and 2.  So
   30715 ** the calling function (pcache.c) will never have a createFlag of 1 on
   30716 ** a non-purgable cache.
   30717 **
   30718 ** There are three different approaches to obtaining space for a page,
   30719 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
   30720 **
   30721 **   1. Regardless of the value of createFlag, the cache is searched for a
   30722 **      copy of the requested page. If one is found, it is returned.
   30723 **
   30724 **   2. If createFlag==0 and the page is not already in the cache, NULL is
   30725 **      returned.
   30726 **
   30727 **   3. If createFlag is 1, and the page is not already in the cache,
   30728 **      and if either of the following are true, return NULL:
   30729 **
   30730 **       (a) the number of pages pinned by the cache is greater than
   30731 **           PCache1.nMax, or
   30732 **       (b) the number of pages pinned by the cache is greater than
   30733 **           the sum of nMax for all purgeable caches, less the sum of
   30734 **           nMin for all other purgeable caches.
   30735 **
   30736 **   4. If none of the first three conditions apply and the cache is marked
   30737 **      as purgeable, and if one of the following is true:
   30738 **
   30739 **       (a) The number of pages allocated for the cache is already
   30740 **           PCache1.nMax, or
   30741 **
   30742 **       (b) The number of pages allocated for all purgeable caches is
   30743 **           already equal to or greater than the sum of nMax for all
   30744 **           purgeable caches,
   30745 **
   30746 **      then attempt to recycle a page from the LRU list. If it is the right
   30747 **      size, return the recycled buffer. Otherwise, free the buffer and
   30748 **      proceed to step 5.
   30749 **
   30750 **   5. Otherwise, allocate and return a new page buffer.
   30751 */
   30752 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
   30753   unsigned int nPinned;
   30754   PCache1 *pCache = (PCache1 *)p;
   30755   PgHdr1 *pPage = 0;
   30756 
   30757   assert( pCache->bPurgeable || createFlag!=1 );
   30758   pcache1EnterMutex();
   30759   if( createFlag==1 ) sqlite3BeginBenignMalloc();
   30760 
   30761   /* Search the hash table for an existing entry. */
   30762   if( pCache->nHash>0 ){
   30763     unsigned int h = iKey % pCache->nHash;
   30764     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
   30765   }
   30766 
   30767   if( pPage || createFlag==0 ){
   30768     pcache1PinPage(pPage);
   30769     goto fetch_out;
   30770   }
   30771 
   30772   /* Step 3 of header comment. */
   30773   nPinned = pCache->nPage - pCache->nRecyclable;
   30774   if( createFlag==1 && (
   30775         nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
   30776      || nPinned>=(pCache->nMax * 9 / 10)
   30777   )){
   30778     goto fetch_out;
   30779   }
   30780 
   30781   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
   30782     goto fetch_out;
   30783   }
   30784 
   30785   /* Step 4. Try to recycle a page buffer if appropriate. */
   30786   if( pCache->bPurgeable && pcache1.pLruTail && (
   30787      (pCache->nPage+1>=pCache->nMax) || pcache1.nCurrentPage>=pcache1.nMaxPage
   30788   )){
   30789     pPage = pcache1.pLruTail;
   30790     pcache1RemoveFromHash(pPage);
   30791     pcache1PinPage(pPage);
   30792     if( pPage->pCache->szPage!=pCache->szPage ){
   30793       pcache1FreePage(pPage);
   30794       pPage = 0;
   30795     }else{
   30796       pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
   30797     }
   30798   }
   30799 
   30800   /* Step 5. If a usable page buffer has still not been found,
   30801   ** attempt to allocate a new one.
   30802   */
   30803   if( !pPage ){
   30804     pPage = pcache1AllocPage(pCache);
   30805   }
   30806 
   30807   if( pPage ){
   30808     unsigned int h = iKey % pCache->nHash;
   30809     pCache->nPage++;
   30810     pPage->iKey = iKey;
   30811     pPage->pNext = pCache->apHash[h];
   30812     pPage->pCache = pCache;
   30813     pPage->pLruPrev = 0;
   30814     pPage->pLruNext = 0;
   30815     *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
   30816     pCache->apHash[h] = pPage;
   30817   }
   30818 
   30819 fetch_out:
   30820   if( pPage && iKey>pCache->iMaxKey ){
   30821     pCache->iMaxKey = iKey;
   30822   }
   30823   if( createFlag==1 ) sqlite3EndBenignMalloc();
   30824   pcache1LeaveMutex();
   30825   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
   30826 }
   30827 
   30828 
   30829 /*
   30830 ** Implementation of the sqlite3_pcache.xUnpin method.
   30831 **
   30832 ** Mark a page as unpinned (eligible for asynchronous recycling).
   30833 */
   30834 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
   30835   PCache1 *pCache = (PCache1 *)p;
   30836   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
   30837 
   30838   assert( pPage->pCache==pCache );
   30839   pcache1EnterMutex();
   30840 
   30841   /* It is an error to call this function if the page is already
   30842   ** part of the global LRU list.
   30843   */
   30844   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
   30845   assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
   30846 
   30847   if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
   30848     pcache1RemoveFromHash(pPage);
   30849     pcache1FreePage(pPage);
   30850   }else{
   30851     /* Add the page to the global LRU list. Normally, the page is added to
   30852     ** the head of the list (last page to be recycled). However, if the
   30853     ** reuseUnlikely flag passed to this function is true, the page is added
   30854     ** to the tail of the list (first page to be recycled).
   30855     */
   30856     if( pcache1.pLruHead ){
   30857       pcache1.pLruHead->pLruPrev = pPage;
   30858       pPage->pLruNext = pcache1.pLruHead;
   30859       pcache1.pLruHead = pPage;
   30860     }else{
   30861       pcache1.pLruTail = pPage;
   30862       pcache1.pLruHead = pPage;
   30863     }
   30864     pCache->nRecyclable++;
   30865   }
   30866 
   30867   pcache1LeaveMutex();
   30868 }
   30869 
   30870 /*
   30871 ** Implementation of the sqlite3_pcache.xRekey method.
   30872 */
   30873 static void pcache1Rekey(
   30874   sqlite3_pcache *p,
   30875   void *pPg,
   30876   unsigned int iOld,
   30877   unsigned int iNew
   30878 ){
   30879   PCache1 *pCache = (PCache1 *)p;
   30880   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
   30881   PgHdr1 **pp;
   30882   unsigned int h;
   30883   assert( pPage->iKey==iOld );
   30884   assert( pPage->pCache==pCache );
   30885 
   30886   pcache1EnterMutex();
   30887 
   30888   h = iOld%pCache->nHash;
   30889   pp = &pCache->apHash[h];
   30890   while( (*pp)!=pPage ){
   30891     pp = &(*pp)->pNext;
   30892   }
   30893   *pp = pPage->pNext;
   30894 
   30895   h = iNew%pCache->nHash;
   30896   pPage->iKey = iNew;
   30897   pPage->pNext = pCache->apHash[h];
   30898   pCache->apHash[h] = pPage;
   30899   if( iNew>pCache->iMaxKey ){
   30900     pCache->iMaxKey = iNew;
   30901   }
   30902 
   30903   pcache1LeaveMutex();
   30904 }
   30905 
   30906 /*
   30907 ** Implementation of the sqlite3_pcache.xTruncate method.
   30908 **
   30909 ** Discard all unpinned pages in the cache with a page number equal to
   30910 ** or greater than parameter iLimit. Any pinned pages with a page number
   30911 ** equal to or greater than iLimit are implicitly unpinned.
   30912 */
   30913 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
   30914   PCache1 *pCache = (PCache1 *)p;
   30915   pcache1EnterMutex();
   30916   if( iLimit<=pCache->iMaxKey ){
   30917     pcache1TruncateUnsafe(pCache, iLimit);
   30918     pCache->iMaxKey = iLimit-1;
   30919   }
   30920   pcache1LeaveMutex();
   30921 }
   30922 
   30923 /*
   30924 ** Implementation of the sqlite3_pcache.xDestroy method.
   30925 **
   30926 ** Destroy a cache allocated using pcache1Create().
   30927 */
   30928 static void pcache1Destroy(sqlite3_pcache *p){
   30929   PCache1 *pCache = (PCache1 *)p;
   30930   pcache1EnterMutex();
   30931   pcache1TruncateUnsafe(pCache, 0);
   30932   pcache1.nMaxPage -= pCache->nMax;
   30933   pcache1.nMinPage -= pCache->nMin;
   30934   pcache1EnforceMaxPage();
   30935   pcache1LeaveMutex();
   30936   sqlite3_free(pCache->apHash);
   30937   sqlite3_free(pCache);
   30938 }
   30939 
   30940 /*
   30941 ** This function is called during initialization (sqlite3_initialize()) to
   30942 ** install the default pluggable cache module, assuming the user has not
   30943 ** already provided an alternative.
   30944 */
   30945 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
   30946   static sqlite3_pcache_methods defaultMethods = {
   30947     0,                       /* pArg */
   30948     pcache1Init,             /* xInit */
   30949     pcache1Shutdown,         /* xShutdown */
   30950     pcache1Create,           /* xCreate */
   30951     pcache1Cachesize,        /* xCachesize */
   30952     pcache1Pagecount,        /* xPagecount */
   30953     pcache1Fetch,            /* xFetch */
   30954     pcache1Unpin,            /* xUnpin */
   30955     pcache1Rekey,            /* xRekey */
   30956     pcache1Truncate,         /* xTruncate */
   30957     pcache1Destroy           /* xDestroy */
   30958   };
   30959   sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
   30960 }
   30961 
   30962 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   30963 /*
   30964 ** This function is called to free superfluous dynamically allocated memory
   30965 ** held by the pager system. Memory in use by any SQLite pager allocated
   30966 ** by the current thread may be sqlite3_free()ed.
   30967 **
   30968 ** nReq is the number of bytes of memory required. Once this much has
   30969 ** been released, the function returns. The return value is the total number
   30970 ** of bytes of memory released.
   30971 */
   30972 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
   30973   int nFree = 0;
   30974   if( pcache1.pStart==0 ){
   30975     PgHdr1 *p;
   30976     pcache1EnterMutex();
   30977     while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
   30978       nFree += sqlite3MallocSize(PGHDR1_TO_PAGE(p));
   30979       pcache1PinPage(p);
   30980       pcache1RemoveFromHash(p);
   30981       pcache1FreePage(p);
   30982     }
   30983     pcache1LeaveMutex();
   30984   }
   30985   return nFree;
   30986 }
   30987 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
   30988 
   30989 #ifdef SQLITE_TEST
   30990 /*
   30991 ** This function is used by test procedures to inspect the internal state
   30992 ** of the global cache.
   30993 */
   30994 SQLITE_PRIVATE void sqlite3PcacheStats(
   30995   int *pnCurrent,      /* OUT: Total number of pages cached */
   30996   int *pnMax,          /* OUT: Global maximum cache size */
   30997   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
   30998   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
   30999 ){
   31000   PgHdr1 *p;
   31001   int nRecyclable = 0;
   31002   for(p=pcache1.pLruHead; p; p=p->pLruNext){
   31003     nRecyclable++;
   31004   }
   31005   *pnCurrent = pcache1.nCurrentPage;
   31006   *pnMax = pcache1.nMaxPage;
   31007   *pnMin = pcache1.nMinPage;
   31008   *pnRecyclable = nRecyclable;
   31009 }
   31010 #endif
   31011 
   31012 /************** End of pcache1.c *********************************************/
   31013 /************** Begin file rowset.c ******************************************/
   31014 /*
   31015 ** 2008 December 3
   31016 **
   31017 ** The author disclaims copyright to this source code.  In place of
   31018 ** a legal notice, here is a blessing:
   31019 **
   31020 **    May you do good and not evil.
   31021 **    May you find forgiveness for yourself and forgive others.
   31022 **    May you share freely, never taking more than you give.
   31023 **
   31024 *************************************************************************
   31025 **
   31026 ** This module implements an object we call a "RowSet".
   31027 **
   31028 ** The RowSet object is a collection of rowids.  Rowids
   31029 ** are inserted into the RowSet in an arbitrary order.  Inserts
   31030 ** can be intermixed with tests to see if a given rowid has been
   31031 ** previously inserted into the RowSet.
   31032 **
   31033 ** After all inserts are finished, it is possible to extract the
   31034 ** elements of the RowSet in sorted order.  Once this extraction
   31035 ** process has started, no new elements may be inserted.
   31036 **
   31037 ** Hence, the primitive operations for a RowSet are:
   31038 **
   31039 **    CREATE
   31040 **    INSERT
   31041 **    TEST
   31042 **    SMALLEST
   31043 **    DESTROY
   31044 **
   31045 ** The CREATE and DESTROY primitives are the constructor and destructor,
   31046 ** obviously.  The INSERT primitive adds a new element to the RowSet.
   31047 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
   31048 ** extracts the least value from the RowSet.
   31049 **
   31050 ** The INSERT primitive might allocate additional memory.  Memory is
   31051 ** allocated in chunks so most INSERTs do no allocation.  There is an
   31052 ** upper bound on the size of allocated memory.  No memory is freed
   31053 ** until DESTROY.
   31054 **
   31055 ** The TEST primitive includes a "batch" number.  The TEST primitive
   31056 ** will only see elements that were inserted before the last change
   31057 ** in the batch number.  In other words, if an INSERT occurs between
   31058 ** two TESTs where the TESTs have the same batch nubmer, then the
   31059 ** value added by the INSERT will not be visible to the second TEST.
   31060 ** The initial batch number is zero, so if the very first TEST contains
   31061 ** a non-zero batch number, it will see all prior INSERTs.
   31062 **
   31063 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
   31064 ** that is attempted.
   31065 **
   31066 ** The cost of an INSERT is roughly constant.  (Sometime new memory
   31067 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
   31068 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
   31069 ** The cost of a TEST using the same batch number is O(logN).  The cost
   31070 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
   31071 ** primitives are constant time.  The cost of DESTROY is O(N).
   31072 **
   31073 ** There is an added cost of O(N) when switching between TEST and
   31074 ** SMALLEST primitives.
   31075 */
   31076 
   31077 
   31078 /*
   31079 ** Target size for allocation chunks.
   31080 */
   31081 #define ROWSET_ALLOCATION_SIZE 1024
   31082 
   31083 /*
   31084 ** The number of rowset entries per allocation chunk.
   31085 */
   31086 #define ROWSET_ENTRY_PER_CHUNK  \
   31087                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
   31088 
   31089 /*
   31090 ** Each entry in a RowSet is an instance of the following object.
   31091 */
   31092 struct RowSetEntry {
   31093   i64 v;                        /* ROWID value for this entry */
   31094   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
   31095   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
   31096 };
   31097 
   31098 /*
   31099 ** RowSetEntry objects are allocated in large chunks (instances of the
   31100 ** following structure) to reduce memory allocation overhead.  The
   31101 ** chunks are kept on a linked list so that they can be deallocated
   31102 ** when the RowSet is destroyed.
   31103 */
   31104 struct RowSetChunk {
   31105   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
   31106   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
   31107 };
   31108 
   31109 /*
   31110 ** A RowSet in an instance of the following structure.
   31111 **
   31112 ** A typedef of this structure if found in sqliteInt.h.
   31113 */
   31114 struct RowSet {
   31115   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
   31116   sqlite3 *db;                   /* The database connection */
   31117   struct RowSetEntry *pEntry;    /* List of entries using pRight */
   31118   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
   31119   struct RowSetEntry *pFresh;    /* Source of new entry objects */
   31120   struct RowSetEntry *pTree;     /* Binary tree of entries */
   31121   u16 nFresh;                    /* Number of objects on pFresh */
   31122   u8 isSorted;                   /* True if pEntry is sorted */
   31123   u8 iBatch;                     /* Current insert batch */
   31124 };
   31125 
   31126 /*
   31127 ** Turn bulk memory into a RowSet object.  N bytes of memory
   31128 ** are available at pSpace.  The db pointer is used as a memory context
   31129 ** for any subsequent allocations that need to occur.
   31130 ** Return a pointer to the new RowSet object.
   31131 **
   31132 ** It must be the case that N is sufficient to make a Rowset.  If not
   31133 ** an assertion fault occurs.
   31134 **
   31135 ** If N is larger than the minimum, use the surplus as an initial
   31136 ** allocation of entries available to be filled.
   31137 */
   31138 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
   31139   RowSet *p;
   31140   assert( N >= ROUND8(sizeof(*p)) );
   31141   p = pSpace;
   31142   p->pChunk = 0;
   31143   p->db = db;
   31144   p->pEntry = 0;
   31145   p->pLast = 0;
   31146   p->pTree = 0;
   31147   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
   31148   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
   31149   p->isSorted = 1;
   31150   p->iBatch = 0;
   31151   return p;
   31152 }
   31153 
   31154 /*
   31155 ** Deallocate all chunks from a RowSet.  This frees all memory that
   31156 ** the RowSet has allocated over its lifetime.  This routine is
   31157 ** the destructor for the RowSet.
   31158 */
   31159 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
   31160   struct RowSetChunk *pChunk, *pNextChunk;
   31161   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
   31162     pNextChunk = pChunk->pNextChunk;
   31163     sqlite3DbFree(p->db, pChunk);
   31164   }
   31165   p->pChunk = 0;
   31166   p->nFresh = 0;
   31167   p->pEntry = 0;
   31168   p->pLast = 0;
   31169   p->pTree = 0;
   31170   p->isSorted = 1;
   31171 }
   31172 
   31173 /*
   31174 ** Insert a new value into a RowSet.
   31175 **
   31176 ** The mallocFailed flag of the database connection is set if a
   31177 ** memory allocation fails.
   31178 */
   31179 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
   31180   struct RowSetEntry *pEntry;  /* The new entry */
   31181   struct RowSetEntry *pLast;   /* The last prior entry */
   31182   assert( p!=0 );
   31183   if( p->nFresh==0 ){
   31184     struct RowSetChunk *pNew;
   31185     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
   31186     if( pNew==0 ){
   31187       return;
   31188     }
   31189     pNew->pNextChunk = p->pChunk;
   31190     p->pChunk = pNew;
   31191     p->pFresh = pNew->aEntry;
   31192     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
   31193   }
   31194   pEntry = p->pFresh++;
   31195   p->nFresh--;
   31196   pEntry->v = rowid;
   31197   pEntry->pRight = 0;
   31198   pLast = p->pLast;
   31199   if( pLast ){
   31200     if( p->isSorted && rowid<=pLast->v ){
   31201       p->isSorted = 0;
   31202     }
   31203     pLast->pRight = pEntry;
   31204   }else{
   31205     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
   31206     p->pEntry = pEntry;
   31207   }
   31208   p->pLast = pEntry;
   31209 }
   31210 
   31211 /*
   31212 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
   31213 **
   31214 ** The input lists are connected via pRight pointers and are
   31215 ** assumed to each already be in sorted order.
   31216 */
   31217 static struct RowSetEntry *rowSetMerge(
   31218   struct RowSetEntry *pA,    /* First sorted list to be merged */
   31219   struct RowSetEntry *pB     /* Second sorted list to be merged */
   31220 ){
   31221   struct RowSetEntry head;
   31222   struct RowSetEntry *pTail;
   31223 
   31224   pTail = &head;
   31225   while( pA && pB ){
   31226     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
   31227     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
   31228     if( pA->v<pB->v ){
   31229       pTail->pRight = pA;
   31230       pA = pA->pRight;
   31231       pTail = pTail->pRight;
   31232     }else if( pB->v<pA->v ){
   31233       pTail->pRight = pB;
   31234       pB = pB->pRight;
   31235       pTail = pTail->pRight;
   31236     }else{
   31237       pA = pA->pRight;
   31238     }
   31239   }
   31240   if( pA ){
   31241     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
   31242     pTail->pRight = pA;
   31243   }else{
   31244     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
   31245     pTail->pRight = pB;
   31246   }
   31247   return head.pRight;
   31248 }
   31249 
   31250 /*
   31251 ** Sort all elements on the pEntry list of the RowSet into ascending order.
   31252 */
   31253 static void rowSetSort(RowSet *p){
   31254   unsigned int i;
   31255   struct RowSetEntry *pEntry;
   31256   struct RowSetEntry *aBucket[40];
   31257 
   31258   assert( p->isSorted==0 );
   31259   memset(aBucket, 0, sizeof(aBucket));
   31260   while( p->pEntry ){
   31261     pEntry = p->pEntry;
   31262     p->pEntry = pEntry->pRight;
   31263     pEntry->pRight = 0;
   31264     for(i=0; aBucket[i]; i++){
   31265       pEntry = rowSetMerge(aBucket[i], pEntry);
   31266       aBucket[i] = 0;
   31267     }
   31268     aBucket[i] = pEntry;
   31269   }
   31270   pEntry = 0;
   31271   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
   31272     pEntry = rowSetMerge(pEntry, aBucket[i]);
   31273   }
   31274   p->pEntry = pEntry;
   31275   p->pLast = 0;
   31276   p->isSorted = 1;
   31277 }
   31278 
   31279 
   31280 /*
   31281 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
   31282 ** Convert this tree into a linked list connected by the pRight pointers
   31283 ** and return pointers to the first and last elements of the new list.
   31284 */
   31285 static void rowSetTreeToList(
   31286   struct RowSetEntry *pIn,         /* Root of the input tree */
   31287   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
   31288   struct RowSetEntry **ppLast      /* Write tail of the output list here */
   31289 ){
   31290   assert( pIn!=0 );
   31291   if( pIn->pLeft ){
   31292     struct RowSetEntry *p;
   31293     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
   31294     p->pRight = pIn;
   31295   }else{
   31296     *ppFirst = pIn;
   31297   }
   31298   if( pIn->pRight ){
   31299     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
   31300   }else{
   31301     *ppLast = pIn;
   31302   }
   31303   assert( (*ppLast)->pRight==0 );
   31304 }
   31305 
   31306 
   31307 /*
   31308 ** Convert a sorted list of elements (connected by pRight) into a binary
   31309 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
   31310 ** node taken from the head of *ppList.  A depth of 2 means a tree with
   31311 ** three nodes.  And so forth.
   31312 **
   31313 ** Use as many entries from the input list as required and update the
   31314 ** *ppList to point to the unused elements of the list.  If the input
   31315 ** list contains too few elements, then construct an incomplete tree
   31316 ** and leave *ppList set to NULL.
   31317 **
   31318 ** Return a pointer to the root of the constructed binary tree.
   31319 */
   31320 static struct RowSetEntry *rowSetNDeepTree(
   31321   struct RowSetEntry **ppList,
   31322   int iDepth
   31323 ){
   31324   struct RowSetEntry *p;         /* Root of the new tree */
   31325   struct RowSetEntry *pLeft;     /* Left subtree */
   31326   if( *ppList==0 ){
   31327     return 0;
   31328   }
   31329   if( iDepth==1 ){
   31330     p = *ppList;
   31331     *ppList = p->pRight;
   31332     p->pLeft = p->pRight = 0;
   31333     return p;
   31334   }
   31335   pLeft = rowSetNDeepTree(ppList, iDepth-1);
   31336   p = *ppList;
   31337   if( p==0 ){
   31338     return pLeft;
   31339   }
   31340   p->pLeft = pLeft;
   31341   *ppList = p->pRight;
   31342   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
   31343   return p;
   31344 }
   31345 
   31346 /*
   31347 ** Convert a sorted list of elements into a binary tree. Make the tree
   31348 ** as deep as it needs to be in order to contain the entire list.
   31349 */
   31350 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
   31351   int iDepth;           /* Depth of the tree so far */
   31352   struct RowSetEntry *p;       /* Current tree root */
   31353   struct RowSetEntry *pLeft;   /* Left subtree */
   31354 
   31355   assert( pList!=0 );
   31356   p = pList;
   31357   pList = p->pRight;
   31358   p->pLeft = p->pRight = 0;
   31359   for(iDepth=1; pList; iDepth++){
   31360     pLeft = p;
   31361     p = pList;
   31362     pList = p->pRight;
   31363     p->pLeft = pLeft;
   31364     p->pRight = rowSetNDeepTree(&pList, iDepth);
   31365   }
   31366   return p;
   31367 }
   31368 
   31369 /*
   31370 ** Convert the list in p->pEntry into a sorted list if it is not
   31371 ** sorted already.  If there is a binary tree on p->pTree, then
   31372 ** convert it into a list too and merge it into the p->pEntry list.
   31373 */
   31374 static void rowSetToList(RowSet *p){
   31375   if( !p->isSorted ){
   31376     rowSetSort(p);
   31377   }
   31378   if( p->pTree ){
   31379     struct RowSetEntry *pHead, *pTail;
   31380     rowSetTreeToList(p->pTree, &pHead, &pTail);
   31381     p->pTree = 0;
   31382     p->pEntry = rowSetMerge(p->pEntry, pHead);
   31383   }
   31384 }
   31385 
   31386 /*
   31387 ** Extract the smallest element from the RowSet.
   31388 ** Write the element into *pRowid.  Return 1 on success.  Return
   31389 ** 0 if the RowSet is already empty.
   31390 **
   31391 ** After this routine has been called, the sqlite3RowSetInsert()
   31392 ** routine may not be called again.
   31393 */
   31394 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
   31395   rowSetToList(p);
   31396   if( p->pEntry ){
   31397     *pRowid = p->pEntry->v;
   31398     p->pEntry = p->pEntry->pRight;
   31399     if( p->pEntry==0 ){
   31400       sqlite3RowSetClear(p);
   31401     }
   31402     return 1;
   31403   }else{
   31404     return 0;
   31405   }
   31406 }
   31407 
   31408 /*
   31409 ** Check to see if element iRowid was inserted into the the rowset as
   31410 ** part of any insert batch prior to iBatch.  Return 1 or 0.
   31411 */
   31412 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
   31413   struct RowSetEntry *p;
   31414   if( iBatch!=pRowSet->iBatch ){
   31415     if( pRowSet->pEntry ){
   31416       rowSetToList(pRowSet);
   31417       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
   31418       pRowSet->pEntry = 0;
   31419       pRowSet->pLast = 0;
   31420     }
   31421     pRowSet->iBatch = iBatch;
   31422   }
   31423   p = pRowSet->pTree;
   31424   while( p ){
   31425     if( p->v<iRowid ){
   31426       p = p->pRight;
   31427     }else if( p->v>iRowid ){
   31428       p = p->pLeft;
   31429     }else{
   31430       return 1;
   31431     }
   31432   }
   31433   return 0;
   31434 }
   31435 
   31436 /************** End of rowset.c **********************************************/
   31437 /************** Begin file pager.c *******************************************/
   31438 /*
   31439 ** 2001 September 15
   31440 **
   31441 ** The author disclaims copyright to this source code.  In place of
   31442 ** a legal notice, here is a blessing:
   31443 **
   31444 **    May you do good and not evil.
   31445 **    May you find forgiveness for yourself and forgive others.
   31446 **    May you share freely, never taking more than you give.
   31447 **
   31448 *************************************************************************
   31449 ** This is the implementation of the page cache subsystem or "pager".
   31450 **
   31451 ** The pager is used to access a database disk file.  It implements
   31452 ** atomic commit and rollback through the use of a journal file that
   31453 ** is separate from the database file.  The pager also implements file
   31454 ** locking to prevent two processes from writing the same database
   31455 ** file simultaneously, or one process from reading the database while
   31456 ** another is writing.
   31457 */
   31458 #ifndef SQLITE_OMIT_DISKIO
   31459 
   31460 /*
   31461 ** Macros for troubleshooting.  Normally turned off
   31462 */
   31463 #if 0
   31464 int sqlite3PagerTrace=1;  /* True to enable tracing */
   31465 #define sqlite3DebugPrintf printf
   31466 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
   31467 #else
   31468 #define PAGERTRACE(X)
   31469 #endif
   31470 
   31471 /*
   31472 ** The following two macros are used within the PAGERTRACE() macros above
   31473 ** to print out file-descriptors.
   31474 **
   31475 ** PAGERID() takes a pointer to a Pager struct as its argument. The
   31476 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
   31477 ** struct as its argument.
   31478 */
   31479 #define PAGERID(p) ((int)(p->fd))
   31480 #define FILEHANDLEID(fd) ((int)fd)
   31481 
   31482 /*
   31483 ** The page cache as a whole is always in one of the following
   31484 ** states:
   31485 **
   31486 **   PAGER_UNLOCK        The page cache is not currently reading or
   31487 **                       writing the database file.  There is no
   31488 **                       data held in memory.  This is the initial
   31489 **                       state.
   31490 **
   31491 **   PAGER_SHARED        The page cache is reading the database.
   31492 **                       Writing is not permitted.  There can be
   31493 **                       multiple readers accessing the same database
   31494 **                       file at the same time.
   31495 **
   31496 **   PAGER_RESERVED      This process has reserved the database for writing
   31497 **                       but has not yet made any changes.  Only one process
   31498 **                       at a time can reserve the database.  The original
   31499 **                       database file has not been modified so other
   31500 **                       processes may still be reading the on-disk
   31501 **                       database file.
   31502 **
   31503 **   PAGER_EXCLUSIVE     The page cache is writing the database.
   31504 **                       Access is exclusive.  No other processes or
   31505 **                       threads can be reading or writing while one
   31506 **                       process is writing.
   31507 **
   31508 **   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
   31509 **                       after all dirty pages have been written to the
   31510 **                       database file and the file has been synced to
   31511 **                       disk. All that remains to do is to remove or
   31512 **                       truncate the journal file and the transaction
   31513 **                       will be committed.
   31514 **
   31515 ** The page cache comes up in PAGER_UNLOCK.  The first time a
   31516 ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
   31517 ** After all pages have been released using sqlite_page_unref(),
   31518 ** the state transitions back to PAGER_UNLOCK.  The first time
   31519 ** that sqlite3PagerWrite() is called, the state transitions to
   31520 ** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
   31521 ** called on an outstanding page which means that the pager must
   31522 ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
   31523 ** PAGER_RESERVED means that there is an open rollback journal.
   31524 ** The transition to PAGER_EXCLUSIVE occurs before any changes
   31525 ** are made to the database file, though writes to the rollback
   31526 ** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
   31527 ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
   31528 ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
   31529 */
   31530 #define PAGER_UNLOCK      0
   31531 #define PAGER_SHARED      1   /* same as SHARED_LOCK */
   31532 #define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
   31533 #define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
   31534 #define PAGER_SYNCED      5
   31535 
   31536 /*
   31537 ** A macro used for invoking the codec if there is one
   31538 */
   31539 #ifdef SQLITE_HAS_CODEC
   31540 # define CODEC1(P,D,N,X,E) \
   31541     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
   31542 # define CODEC2(P,D,N,X,E,O) \
   31543     if( P->xCodec==0 ){ O=(char*)D; }else \
   31544     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
   31545 #else
   31546 # define CODEC1(P,D,N,X,E)   /* NO-OP */
   31547 # define CODEC2(P,D,N,X,E,O) O=(char*)D
   31548 #endif
   31549 
   31550 /*
   31551 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
   31552 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
   31553 ** This could conceivably cause corruption following a power failure on
   31554 ** such a system. This is currently an undocumented limit.
   31555 */
   31556 #define MAX_SECTOR_SIZE 0x10000
   31557 
   31558 /*
   31559 ** An instance of the following structure is allocated for each active
   31560 ** savepoint and statement transaction in the system. All such structures
   31561 ** are stored in the Pager.aSavepoint[] array, which is allocated and
   31562 ** resized using sqlite3Realloc().
   31563 **
   31564 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
   31565 ** set to 0. If a journal-header is written into the main journal while
   31566 ** the savepoint is active, then iHdrOffset is set to the byte offset
   31567 ** immediately following the last journal record written into the main
   31568 ** journal before the journal-header. This is required during savepoint
   31569 ** rollback (see pagerPlaybackSavepoint()).
   31570 */
   31571 typedef struct PagerSavepoint PagerSavepoint;
   31572 struct PagerSavepoint {
   31573   i64 iOffset;                 /* Starting offset in main journal */
   31574   i64 iHdrOffset;              /* See above */
   31575   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
   31576   Pgno nOrig;                  /* Original number of pages in file */
   31577   Pgno iSubRec;                /* Index of first record in sub-journal */
   31578 };
   31579 
   31580 /*
   31581 ** A open page cache is an instance of the following structure.
   31582 **
   31583 ** errCode
   31584 **
   31585 **   Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
   31586 **   or SQLITE_FULL. Once one of the first three errors occurs, it persists
   31587 **   and is returned as the result of every major pager API call.  The
   31588 **   SQLITE_FULL return code is slightly different. It persists only until the
   31589 **   next successful rollback is performed on the pager cache. Also,
   31590 **   SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
   31591 **   APIs, they may still be used successfully.
   31592 **
   31593 ** dbSizeValid, dbSize, dbOrigSize, dbFileSize
   31594 **
   31595 **   Managing the size of the database file in pages is a little complicated.
   31596 **   The variable Pager.dbSize contains the number of pages that the database
   31597 **   image currently contains. As the database image grows or shrinks this
   31598 **   variable is updated. The variable Pager.dbFileSize contains the number
   31599 **   of pages in the database file. This may be different from Pager.dbSize
   31600 **   if some pages have been appended to the database image but not yet written
   31601 **   out from the cache to the actual file on disk. Or if the image has been
   31602 **   truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
   31603 **   contains the number of pages in the database image when the current
   31604 **   transaction was opened. The contents of all three of these variables is
   31605 **   only guaranteed to be correct if the boolean Pager.dbSizeValid is true.
   31606 **
   31607 **   TODO: Under what conditions is dbSizeValid set? Cleared?
   31608 **
   31609 ** changeCountDone
   31610 **
   31611 **   This boolean variable is used to make sure that the change-counter
   31612 **   (the 4-byte header field at byte offset 24 of the database file) is
   31613 **   not updated more often than necessary.
   31614 **
   31615 **   It is set to true when the change-counter field is updated, which
   31616 **   can only happen if an exclusive lock is held on the database file.
   31617 **   It is cleared (set to false) whenever an exclusive lock is
   31618 **   relinquished on the database file. Each time a transaction is committed,
   31619 **   The changeCountDone flag is inspected. If it is true, the work of
   31620 **   updating the change-counter is omitted for the current transaction.
   31621 **
   31622 **   This mechanism means that when running in exclusive mode, a connection
   31623 **   need only update the change-counter once, for the first transaction
   31624 **   committed.
   31625 **
   31626 ** dbModified
   31627 **
   31628 **   The dbModified flag is set whenever a database page is dirtied.
   31629 **   It is cleared at the end of each transaction.
   31630 **
   31631 **   It is used when committing or otherwise ending a transaction. If
   31632 **   the dbModified flag is clear then less work has to be done.
   31633 **
   31634 ** journalStarted
   31635 **
   31636 **   This flag is set whenever the the main journal is synced.
   31637 **
   31638 **   The point of this flag is that it must be set after the
   31639 **   first journal header in a journal file has been synced to disk.
   31640 **   After this has happened, new pages appended to the database
   31641 **   do not need the PGHDR_NEED_SYNC flag set, as they do not need
   31642 **   to wait for a journal sync before they can be written out to
   31643 **   the database file (see function pager_write()).
   31644 **
   31645 ** setMaster
   31646 **
   31647 **   This variable is used to ensure that the master journal file name
   31648 **   (if any) is only written into the journal file once.
   31649 **
   31650 **   When committing a transaction, the master journal file name (if any)
   31651 **   may be written into the journal file while the pager is still in
   31652 **   PAGER_RESERVED state (see CommitPhaseOne() for the action). It
   31653 **   then attempts to upgrade to an exclusive lock. If this attempt
   31654 **   fails, then SQLITE_BUSY may be returned to the user and the user
   31655 **   may attempt to commit the transaction again later (calling
   31656 **   CommitPhaseOne() again). This flag is used to ensure that the
   31657 **   master journal name is only written to the journal file the first
   31658 **   time CommitPhaseOne() is called.
   31659 **
   31660 ** doNotSync
   31661 **
   31662 **   This variable is set and cleared by sqlite3PagerWrite().
   31663 **
   31664 ** needSync
   31665 **
   31666 **   TODO: It might be easier to set this variable in writeJournalHdr()
   31667 **   and writeMasterJournal() only. Change its meaning to "unsynced data
   31668 **   has been written to the journal".
   31669 **
   31670 ** subjInMemory
   31671 **
   31672 **   This is a boolean variable. If true, then any required sub-journal
   31673 **   is opened as an in-memory journal file. If false, then in-memory
   31674 **   sub-journals are only used for in-memory pager files.
   31675 */
   31676 struct Pager {
   31677   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
   31678   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
   31679   u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
   31680   u8 useJournal;              /* Use a rollback journal on this file */
   31681   u8 noReadlock;              /* Do not bother to obtain readlocks */
   31682   u8 noSync;                  /* Do not sync the journal if true */
   31683   u8 fullSync;                /* Do extra syncs of the journal for robustness */
   31684   u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
   31685   u8 tempFile;                /* zFilename is a temporary file */
   31686   u8 readOnly;                /* True for a read-only database */
   31687   u8 memDb;                   /* True to inhibit all file I/O */
   31688 
   31689   /* The following block contains those class members that are dynamically
   31690   ** modified during normal operations. The other variables in this structure
   31691   ** are either constant throughout the lifetime of the pager, or else
   31692   ** used to store configuration parameters that affect the way the pager
   31693   ** operates.
   31694   **
   31695   ** The 'state' variable is described in more detail along with the
   31696   ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the
   31697   ** other variables in this block are described in the comment directly
   31698   ** above this class definition.
   31699   */
   31700   u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
   31701   u8 dbModified;              /* True if there are any changes to the Db */
   31702   u8 needSync;                /* True if an fsync() is needed on the journal */
   31703   u8 journalStarted;          /* True if header of journal is synced */
   31704   u8 changeCountDone;         /* Set after incrementing the change-counter */
   31705   u8 setMaster;               /* True if a m-j name has been written to jrnl */
   31706   u8 doNotSync;               /* Boolean. While true, do not spill the cache */
   31707   u8 dbSizeValid;             /* Set when dbSize is correct */
   31708   u8 subjInMemory;            /* True to use in-memory sub-journals */
   31709   Pgno dbSize;                /* Number of pages in the database */
   31710   Pgno dbOrigSize;            /* dbSize before the current transaction */
   31711   Pgno dbFileSize;            /* Number of pages in the database file */
   31712   int errCode;                /* One of several kinds of errors */
   31713   int nRec;                   /* Pages journalled since last j-header written */
   31714   u32 cksumInit;              /* Quasi-random value added to every checksum */
   31715   u32 nSubRec;                /* Number of records written to sub-journal */
   31716   Bitvec *pInJournal;         /* One bit for each page in the database file */
   31717   sqlite3_file *fd;           /* File descriptor for database */
   31718   sqlite3_file *jfd;          /* File descriptor for main journal */
   31719   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
   31720   i64 journalOff;             /* Current write offset in the journal file */
   31721   i64 journalHdr;             /* Byte offset to previous journal header */
   31722   PagerSavepoint *aSavepoint; /* Array of active savepoints */
   31723   int nSavepoint;             /* Number of elements in aSavepoint[] */
   31724   char dbFileVers[16];        /* Changes whenever database file changes */
   31725   u32 sectorSize;             /* Assumed sector size during rollback */
   31726 
   31727   u16 nExtra;                 /* Add this many bytes to each in-memory page */
   31728   i16 nReserve;               /* Number of unused bytes at end of each page */
   31729   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
   31730   int pageSize;               /* Number of bytes in a page */
   31731   Pgno mxPgno;                /* Maximum allowed size of the database */
   31732   char *zFilename;            /* Name of the database file */
   31733   char *zJournal;             /* Name of the journal file */
   31734   int (*xBusyHandler)(void*); /* Function to call when busy */
   31735   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
   31736 #ifdef SQLITE_TEST
   31737   int nHit, nMiss;            /* Cache hits and missing */
   31738   int nRead, nWrite;          /* Database pages read/written */
   31739 #endif
   31740   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
   31741 #ifdef SQLITE_HAS_CODEC
   31742   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
   31743   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
   31744   void (*xCodecFree)(void*);             /* Destructor for the codec */
   31745   void *pCodec;               /* First argument to xCodec... methods */
   31746 #endif
   31747   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
   31748   i64 journalSizeLimit;       /* Size limit for persistent journal files */
   31749   PCache *pPCache;            /* Pointer to page cache object */
   31750   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
   31751 };
   31752 
   31753 /*
   31754 ** The following global variables hold counters used for
   31755 ** testing purposes only.  These variables do not exist in
   31756 ** a non-testing build.  These variables are not thread-safe.
   31757 */
   31758 #ifdef SQLITE_TEST
   31759 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
   31760 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
   31761 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
   31762 # define PAGER_INCR(v)  v++
   31763 #else
   31764 # define PAGER_INCR(v)
   31765 #endif
   31766 
   31767 
   31768 
   31769 /*
   31770 ** Journal files begin with the following magic string.  The data
   31771 ** was obtained from /dev/random.  It is used only as a sanity check.
   31772 **
   31773 ** Since version 2.8.0, the journal format contains additional sanity
   31774 ** checking information.  If the power fails while the journal is being
   31775 ** written, semi-random garbage data might appear in the journal
   31776 ** file after power is restored.  If an attempt is then made
   31777 ** to roll the journal back, the database could be corrupted.  The additional
   31778 ** sanity checking data is an attempt to discover the garbage in the
   31779 ** journal and ignore it.
   31780 **
   31781 ** The sanity checking information for the new journal format consists
   31782 ** of a 32-bit checksum on each page of data.  The checksum covers both
   31783 ** the page number and the pPager->pageSize bytes of data for the page.
   31784 ** This cksum is initialized to a 32-bit random value that appears in the
   31785 ** journal file right after the header.  The random initializer is important,
   31786 ** because garbage data that appears at the end of a journal is likely
   31787 ** data that was once in other files that have now been deleted.  If the
   31788 ** garbage data came from an obsolete journal file, the checksums might
   31789 ** be correct.  But by initializing the checksum to random value which
   31790 ** is different for every journal, we minimize that risk.
   31791 */
   31792 static const unsigned char aJournalMagic[] = {
   31793   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
   31794 };
   31795 
   31796 /*
   31797 ** The size of the of each page record in the journal is given by
   31798 ** the following macro.
   31799 */
   31800 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
   31801 
   31802 /*
   31803 ** The journal header size for this pager. This is usually the same
   31804 ** size as a single disk sector. See also setSectorSize().
   31805 */
   31806 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
   31807 
   31808 /*
   31809 ** The macro MEMDB is true if we are dealing with an in-memory database.
   31810 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
   31811 ** the value of MEMDB will be a constant and the compiler will optimize
   31812 ** out code that would never execute.
   31813 */
   31814 #ifdef SQLITE_OMIT_MEMORYDB
   31815 # define MEMDB 0
   31816 #else
   31817 # define MEMDB pPager->memDb
   31818 #endif
   31819 
   31820 /*
   31821 ** The maximum legal page number is (2^31 - 1).
   31822 */
   31823 #define PAGER_MAX_PGNO 2147483647
   31824 
   31825 #ifndef NDEBUG
   31826 /*
   31827 ** Usage:
   31828 **
   31829 **   assert( assert_pager_state(pPager) );
   31830 */
   31831 static int assert_pager_state(Pager *pPager){
   31832 
   31833   /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */
   31834   assert( pPager->tempFile==0 || pPager->state>=PAGER_EXCLUSIVE );
   31835 
   31836   /* The changeCountDone flag is always set for temp-files */
   31837   assert( pPager->tempFile==0 || pPager->changeCountDone );
   31838 
   31839   return 1;
   31840 }
   31841 #endif
   31842 
   31843 /*
   31844 ** Return true if it is necessary to write page *pPg into the sub-journal.
   31845 ** A page needs to be written into the sub-journal if there exists one
   31846 ** or more open savepoints for which:
   31847 **
   31848 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
   31849 **   * The bit corresponding to the page-number is not set in
   31850 **     PagerSavepoint.pInSavepoint.
   31851 */
   31852 static int subjRequiresPage(PgHdr *pPg){
   31853   Pgno pgno = pPg->pgno;
   31854   Pager *pPager = pPg->pPager;
   31855   int i;
   31856   for(i=0; i<pPager->nSavepoint; i++){
   31857     PagerSavepoint *p = &pPager->aSavepoint[i];
   31858     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
   31859       return 1;
   31860     }
   31861   }
   31862   return 0;
   31863 }
   31864 
   31865 /*
   31866 ** Return true if the page is already in the journal file.
   31867 */
   31868 static int pageInJournal(PgHdr *pPg){
   31869   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
   31870 }
   31871 
   31872 /*
   31873 ** Read a 32-bit integer from the given file descriptor.  Store the integer
   31874 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
   31875 ** error code is something goes wrong.
   31876 **
   31877 ** All values are stored on disk as big-endian.
   31878 */
   31879 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
   31880   unsigned char ac[4];
   31881   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
   31882   if( rc==SQLITE_OK ){
   31883     *pRes = sqlite3Get4byte(ac);
   31884   }
   31885   return rc;
   31886 }
   31887 
   31888 /*
   31889 ** Write a 32-bit integer into a string buffer in big-endian byte order.
   31890 */
   31891 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
   31892 
   31893 /*
   31894 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
   31895 ** on success or an error code is something goes wrong.
   31896 */
   31897 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
   31898   char ac[4];
   31899   put32bits(ac, val);
   31900   return sqlite3OsWrite(fd, ac, 4, offset);
   31901 }
   31902 
   31903 /*
   31904 ** The argument to this macro is a file descriptor (type sqlite3_file*).
   31905 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
   31906 **
   31907 ** This is so that expressions can be written as:
   31908 **
   31909 **   if( isOpen(pPager->jfd) ){ ...
   31910 **
   31911 ** instead of
   31912 **
   31913 **   if( pPager->jfd->pMethods ){ ...
   31914 */
   31915 #define isOpen(pFd) ((pFd)->pMethods)
   31916 
   31917 /*
   31918 ** If file pFd is open, call sqlite3OsUnlock() on it.
   31919 */
   31920 static int osUnlock(sqlite3_file *pFd, int eLock){
   31921   if( !isOpen(pFd) ){
   31922     return SQLITE_OK;
   31923   }
   31924   return sqlite3OsUnlock(pFd, eLock);
   31925 }
   31926 
   31927 /*
   31928 ** This function determines whether or not the atomic-write optimization
   31929 ** can be used with this pager. The optimization can be used if:
   31930 **
   31931 **  (a) the value returned by OsDeviceCharacteristics() indicates that
   31932 **      a database page may be written atomically, and
   31933 **  (b) the value returned by OsSectorSize() is less than or equal
   31934 **      to the page size.
   31935 **
   31936 ** The optimization is also always enabled for temporary files. It is
   31937 ** an error to call this function if pPager is opened on an in-memory
   31938 ** database.
   31939 **
   31940 ** If the optimization cannot be used, 0 is returned. If it can be used,
   31941 ** then the value returned is the size of the journal file when it
   31942 ** contains rollback data for exactly one page.
   31943 */
   31944 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   31945 static int jrnlBufferSize(Pager *pPager){
   31946   assert( !MEMDB );
   31947   if( !pPager->tempFile ){
   31948     int dc;                           /* Device characteristics */
   31949     int nSector;                      /* Sector size */
   31950     int szPage;                       /* Page size */
   31951 
   31952     assert( isOpen(pPager->fd) );
   31953     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
   31954     nSector = pPager->sectorSize;
   31955     szPage = pPager->pageSize;
   31956 
   31957     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
   31958     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
   31959     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
   31960       return 0;
   31961     }
   31962   }
   31963 
   31964   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
   31965 }
   31966 #endif
   31967 
   31968 /*
   31969 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
   31970 ** on the cache using a hash function.  This is used for testing
   31971 ** and debugging only.
   31972 */
   31973 #ifdef SQLITE_CHECK_PAGES
   31974 /*
   31975 ** Return a 32-bit hash of the page data for pPage.
   31976 */
   31977 static u32 pager_datahash(int nByte, unsigned char *pData){
   31978   u32 hash = 0;
   31979   int i;
   31980   for(i=0; i<nByte; i++){
   31981     hash = (hash*1039) + pData[i];
   31982   }
   31983   return hash;
   31984 }
   31985 static u32 pager_pagehash(PgHdr *pPage){
   31986   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
   31987 }
   31988 static void pager_set_pagehash(PgHdr *pPage){
   31989   pPage->pageHash = pager_pagehash(pPage);
   31990 }
   31991 
   31992 /*
   31993 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
   31994 ** is defined, and NDEBUG is not defined, an assert() statement checks
   31995 ** that the page is either dirty or still matches the calculated page-hash.
   31996 */
   31997 #define CHECK_PAGE(x) checkPage(x)
   31998 static void checkPage(PgHdr *pPg){
   31999   Pager *pPager = pPg->pPager;
   32000   assert( !pPg->pageHash || pPager->errCode
   32001       || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
   32002 }
   32003 
   32004 #else
   32005 #define pager_datahash(X,Y)  0
   32006 #define pager_pagehash(X)  0
   32007 #define CHECK_PAGE(x)
   32008 #endif  /* SQLITE_CHECK_PAGES */
   32009 
   32010 /*
   32011 ** When this is called the journal file for pager pPager must be open.
   32012 ** This function attempts to read a master journal file name from the
   32013 ** end of the file and, if successful, copies it into memory supplied
   32014 ** by the caller. See comments above writeMasterJournal() for the format
   32015 ** used to store a master journal file name at the end of a journal file.
   32016 **
   32017 ** zMaster must point to a buffer of at least nMaster bytes allocated by
   32018 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
   32019 ** enough space to write the master journal name). If the master journal
   32020 ** name in the journal is longer than nMaster bytes (including a
   32021 ** nul-terminator), then this is handled as if no master journal name
   32022 ** were present in the journal.
   32023 **
   32024 ** If a master journal file name is present at the end of the journal
   32025 ** file, then it is copied into the buffer pointed to by zMaster. A
   32026 ** nul-terminator byte is appended to the buffer following the master
   32027 ** journal file name.
   32028 **
   32029 ** If it is determined that no master journal file name is present
   32030 ** zMaster[0] is set to 0 and SQLITE_OK returned.
   32031 **
   32032 ** If an error occurs while reading from the journal file, an SQLite
   32033 ** error code is returned.
   32034 */
   32035 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
   32036   int rc;                    /* Return code */
   32037   u32 len;                   /* Length in bytes of master journal name */
   32038   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
   32039   u32 cksum;                 /* MJ checksum value read from journal */
   32040   u32 u;                     /* Unsigned loop counter */
   32041   unsigned char aMagic[8];   /* A buffer to hold the magic header */
   32042   zMaster[0] = '\0';
   32043 
   32044   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
   32045    || szJ<16
   32046    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
   32047    || len>=nMaster
   32048    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
   32049    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
   32050    || memcmp(aMagic, aJournalMagic, 8)
   32051    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
   32052   ){
   32053     return rc;
   32054   }
   32055 
   32056   /* See if the checksum matches the master journal name */
   32057   for(u=0; u<len; u++){
   32058     cksum -= zMaster[u];
   32059   }
   32060   if( cksum ){
   32061     /* If the checksum doesn't add up, then one or more of the disk sectors
   32062     ** containing the master journal filename is corrupted. This means
   32063     ** definitely roll back, so just return SQLITE_OK and report a (nul)
   32064     ** master-journal filename.
   32065     */
   32066     len = 0;
   32067   }
   32068   zMaster[len] = '\0';
   32069 
   32070   return SQLITE_OK;
   32071 }
   32072 
   32073 /*
   32074 ** Return the offset of the sector boundary at or immediately
   32075 ** following the value in pPager->journalOff, assuming a sector
   32076 ** size of pPager->sectorSize bytes.
   32077 **
   32078 ** i.e for a sector size of 512:
   32079 **
   32080 **   Pager.journalOff          Return value
   32081 **   ---------------------------------------
   32082 **   0                         0
   32083 **   512                       512
   32084 **   100                       512
   32085 **   2000                      2048
   32086 **
   32087 */
   32088 static i64 journalHdrOffset(Pager *pPager){
   32089   i64 offset = 0;
   32090   i64 c = pPager->journalOff;
   32091   if( c ){
   32092     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
   32093   }
   32094   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
   32095   assert( offset>=c );
   32096   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
   32097   return offset;
   32098 }
   32099 
   32100 /*
   32101 ** The journal file must be open when this function is called.
   32102 **
   32103 ** This function is a no-op if the journal file has not been written to
   32104 ** within the current transaction (i.e. if Pager.journalOff==0).
   32105 **
   32106 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
   32107 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
   32108 ** zero the 28-byte header at the start of the journal file. In either case,
   32109 ** if the pager is not in no-sync mode, sync the journal file immediately
   32110 ** after writing or truncating it.
   32111 **
   32112 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
   32113 ** following the truncation or zeroing described above the size of the
   32114 ** journal file in bytes is larger than this value, then truncate the
   32115 ** journal file to Pager.journalSizeLimit bytes. The journal file does
   32116 ** not need to be synced following this operation.
   32117 **
   32118 ** If an IO error occurs, abandon processing and return the IO error code.
   32119 ** Otherwise, return SQLITE_OK.
   32120 */
   32121 static int zeroJournalHdr(Pager *pPager, int doTruncate){
   32122   int rc = SQLITE_OK;                               /* Return code */
   32123   assert( isOpen(pPager->jfd) );
   32124   if( pPager->journalOff ){
   32125     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
   32126 
   32127     IOTRACE(("JZEROHDR %p\n", pPager))
   32128     if( doTruncate || iLimit==0 ){
   32129       rc = sqlite3OsTruncate(pPager->jfd, 0);
   32130     }else{
   32131       static const char zeroHdr[28] = {0};
   32132       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
   32133     }
   32134     if( rc==SQLITE_OK && !pPager->noSync ){
   32135       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
   32136     }
   32137 
   32138     /* At this point the transaction is committed but the write lock
   32139     ** is still held on the file. If there is a size limit configured for
   32140     ** the persistent journal and the journal file currently consumes more
   32141     ** space than that limit allows for, truncate it now. There is no need
   32142     ** to sync the file following this operation.
   32143     */
   32144     if( rc==SQLITE_OK && iLimit>0 ){
   32145       i64 sz;
   32146       rc = sqlite3OsFileSize(pPager->jfd, &sz);
   32147       if( rc==SQLITE_OK && sz>iLimit ){
   32148         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
   32149       }
   32150     }
   32151   }
   32152   return rc;
   32153 }
   32154 
   32155 /*
   32156 ** The journal file must be open when this routine is called. A journal
   32157 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
   32158 ** current location.
   32159 **
   32160 ** The format for the journal header is as follows:
   32161 ** - 8 bytes: Magic identifying journal format.
   32162 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
   32163 ** - 4 bytes: Random number used for page hash.
   32164 ** - 4 bytes: Initial database page count.
   32165 ** - 4 bytes: Sector size used by the process that wrote this journal.
   32166 ** - 4 bytes: Database page size.
   32167 **
   32168 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
   32169 */
   32170 static int writeJournalHdr(Pager *pPager){
   32171   int rc = SQLITE_OK;                 /* Return code */
   32172   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
   32173   u32 nHeader = pPager->pageSize;     /* Size of buffer pointed to by zHeader */
   32174   u32 nWrite;                         /* Bytes of header sector written */
   32175   int ii;                             /* Loop counter */
   32176 
   32177   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
   32178 
   32179   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
   32180     nHeader = JOURNAL_HDR_SZ(pPager);
   32181   }
   32182 
   32183   /* If there are active savepoints and any of them were created
   32184   ** since the most recent journal header was written, update the
   32185   ** PagerSavepoint.iHdrOffset fields now.
   32186   */
   32187   for(ii=0; ii<pPager->nSavepoint; ii++){
   32188     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
   32189       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
   32190     }
   32191   }
   32192 
   32193   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
   32194 
   32195   /*
   32196   ** Write the nRec Field - the number of page records that follow this
   32197   ** journal header. Normally, zero is written to this value at this time.
   32198   ** After the records are added to the journal (and the journal synced,
   32199   ** if in full-sync mode), the zero is overwritten with the true number
   32200   ** of records (see syncJournal()).
   32201   **
   32202   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
   32203   ** reading the journal this value tells SQLite to assume that the
   32204   ** rest of the journal file contains valid page records. This assumption
   32205   ** is dangerous, as if a failure occurred whilst writing to the journal
   32206   ** file it may contain some garbage data. There are two scenarios
   32207   ** where this risk can be ignored:
   32208   **
   32209   **   * When the pager is in no-sync mode. Corruption can follow a
   32210   **     power failure in this case anyway.
   32211   **
   32212   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
   32213   **     that garbage data is never appended to the journal file.
   32214   */
   32215   assert( isOpen(pPager->fd) || pPager->noSync );
   32216   if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
   32217    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
   32218   ){
   32219     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
   32220     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
   32221   }else{
   32222     memset(zHeader, 0, sizeof(aJournalMagic)+4);
   32223   }
   32224 
   32225   /* The random check-hash initialiser */
   32226   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
   32227   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
   32228   /* The initial database size */
   32229   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
   32230   /* The assumed sector size for this process */
   32231   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
   32232 
   32233   /* The page size */
   32234   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
   32235 
   32236   /* Initializing the tail of the buffer is not necessary.  Everything
   32237   ** works find if the following memset() is omitted.  But initializing
   32238   ** the memory prevents valgrind from complaining, so we are willing to
   32239   ** take the performance hit.
   32240   */
   32241   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
   32242          nHeader-(sizeof(aJournalMagic)+20));
   32243 
   32244   /* In theory, it is only necessary to write the 28 bytes that the
   32245   ** journal header consumes to the journal file here. Then increment the
   32246   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
   32247   ** record is written to the following sector (leaving a gap in the file
   32248   ** that will be implicitly filled in by the OS).
   32249   **
   32250   ** However it has been discovered that on some systems this pattern can
   32251   ** be significantly slower than contiguously writing data to the file,
   32252   ** even if that means explicitly writing data to the block of
   32253   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
   32254   ** is done.
   32255   **
   32256   ** The loop is required here in case the sector-size is larger than the
   32257   ** database page size. Since the zHeader buffer is only Pager.pageSize
   32258   ** bytes in size, more than one call to sqlite3OsWrite() may be required
   32259   ** to populate the entire journal header sector.
   32260   */
   32261   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
   32262     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
   32263     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
   32264     pPager->journalOff += nHeader;
   32265   }
   32266 
   32267   return rc;
   32268 }
   32269 
   32270 /*
   32271 ** The journal file must be open when this is called. A journal header file
   32272 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
   32273 ** file. The current location in the journal file is given by
   32274 ** pPager->journalOff. See comments above function writeJournalHdr() for
   32275 ** a description of the journal header format.
   32276 **
   32277 ** If the header is read successfully, *pNRec is set to the number of
   32278 ** page records following this header and *pDbSize is set to the size of the
   32279 ** database before the transaction began, in pages. Also, pPager->cksumInit
   32280 ** is set to the value read from the journal header. SQLITE_OK is returned
   32281 ** in this case.
   32282 **
   32283 ** If the journal header file appears to be corrupted, SQLITE_DONE is
   32284 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
   32285 ** cannot be read from the journal file an error code is returned.
   32286 */
   32287 static int readJournalHdr(
   32288   Pager *pPager,               /* Pager object */
   32289   int isHot,
   32290   i64 journalSize,             /* Size of the open journal file in bytes */
   32291   u32 *pNRec,                  /* OUT: Value read from the nRec field */
   32292   u32 *pDbSize                 /* OUT: Value of original database size field */
   32293 ){
   32294   int rc;                      /* Return code */
   32295   unsigned char aMagic[8];     /* A buffer to hold the magic header */
   32296   i64 iHdrOff;                 /* Offset of journal header being read */
   32297 
   32298   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
   32299 
   32300   /* Advance Pager.journalOff to the start of the next sector. If the
   32301   ** journal file is too small for there to be a header stored at this
   32302   ** point, return SQLITE_DONE.
   32303   */
   32304   pPager->journalOff = journalHdrOffset(pPager);
   32305   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
   32306     return SQLITE_DONE;
   32307   }
   32308   iHdrOff = pPager->journalOff;
   32309 
   32310   /* Read in the first 8 bytes of the journal header. If they do not match
   32311   ** the  magic string found at the start of each journal header, return
   32312   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
   32313   ** proceed.
   32314   */
   32315   if( isHot || iHdrOff!=pPager->journalHdr ){
   32316     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
   32317     if( rc ){
   32318       return rc;
   32319     }
   32320     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
   32321       return SQLITE_DONE;
   32322     }
   32323   }
   32324 
   32325   /* Read the first three 32-bit fields of the journal header: The nRec
   32326   ** field, the checksum-initializer and the database size at the start
   32327   ** of the transaction. Return an error code if anything goes wrong.
   32328   */
   32329   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
   32330    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
   32331    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
   32332   ){
   32333     return rc;
   32334   }
   32335 
   32336   if( pPager->journalOff==0 ){
   32337     u32 iPageSize;               /* Page-size field of journal header */
   32338     u32 iSectorSize;             /* Sector-size field of journal header */
   32339     u16 iPageSize16;             /* Copy of iPageSize in 16-bit variable */
   32340 
   32341     /* Read the page-size and sector-size journal header fields. */
   32342     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
   32343      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
   32344     ){
   32345       return rc;
   32346     }
   32347 
   32348     /* Check that the values read from the page-size and sector-size fields
   32349     ** are within range. To be 'in range', both values need to be a power
   32350     ** of two greater than or equal to 512 or 32, and not greater than their
   32351     ** respective compile time maximum limits.
   32352     */
   32353     if( iPageSize<512                  || iSectorSize<32
   32354      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
   32355      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
   32356     ){
   32357       /* If the either the page-size or sector-size in the journal-header is
   32358       ** invalid, then the process that wrote the journal-header must have
   32359       ** crashed before the header was synced. In this case stop reading
   32360       ** the journal file here.
   32361       */
   32362       return SQLITE_DONE;
   32363     }
   32364 
   32365     /* Update the page-size to match the value read from the journal.
   32366     ** Use a testcase() macro to make sure that malloc failure within
   32367     ** PagerSetPagesize() is tested.
   32368     */
   32369     iPageSize16 = (u16)iPageSize;
   32370     rc = sqlite3PagerSetPagesize(pPager, &iPageSize16, -1);
   32371     testcase( rc!=SQLITE_OK );
   32372     assert( rc!=SQLITE_OK || iPageSize16==(u16)iPageSize );
   32373 
   32374     /* Update the assumed sector-size to match the value used by
   32375     ** the process that created this journal. If this journal was
   32376     ** created by a process other than this one, then this routine
   32377     ** is being called from within pager_playback(). The local value
   32378     ** of Pager.sectorSize is restored at the end of that routine.
   32379     */
   32380     pPager->sectorSize = iSectorSize;
   32381   }
   32382 
   32383   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
   32384   return rc;
   32385 }
   32386 
   32387 
   32388 /*
   32389 ** Write the supplied master journal name into the journal file for pager
   32390 ** pPager at the current location. The master journal name must be the last
   32391 ** thing written to a journal file. If the pager is in full-sync mode, the
   32392 ** journal file descriptor is advanced to the next sector boundary before
   32393 ** anything is written. The format is:
   32394 **
   32395 **   + 4 bytes: PAGER_MJ_PGNO.
   32396 **   + N bytes: Master journal filename in utf-8.
   32397 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
   32398 **   + 4 bytes: Master journal name checksum.
   32399 **   + 8 bytes: aJournalMagic[].
   32400 **
   32401 ** The master journal page checksum is the sum of the bytes in the master
   32402 ** journal name, where each byte is interpreted as a signed 8-bit integer.
   32403 **
   32404 ** If zMaster is a NULL pointer (occurs for a single database transaction),
   32405 ** this call is a no-op.
   32406 */
   32407 static int writeMasterJournal(Pager *pPager, const char *zMaster){
   32408   int rc;                          /* Return code */
   32409   int nMaster;                     /* Length of string zMaster */
   32410   i64 iHdrOff;                     /* Offset of header in journal file */
   32411   i64 jrnlSize;                    /* Size of journal file on disk */
   32412   u32 cksum = 0;                   /* Checksum of string zMaster */
   32413 
   32414   if( !zMaster || pPager->setMaster
   32415    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
   32416    || pPager->journalMode==PAGER_JOURNALMODE_OFF
   32417   ){
   32418     return SQLITE_OK;
   32419   }
   32420   pPager->setMaster = 1;
   32421   assert( isOpen(pPager->jfd) );
   32422 
   32423   /* Calculate the length in bytes and the checksum of zMaster */
   32424   for(nMaster=0; zMaster[nMaster]; nMaster++){
   32425     cksum += zMaster[nMaster];
   32426   }
   32427 
   32428   /* If in full-sync mode, advance to the next disk sector before writing
   32429   ** the master journal name. This is in case the previous page written to
   32430   ** the journal has already been synced.
   32431   */
   32432   if( pPager->fullSync ){
   32433     pPager->journalOff = journalHdrOffset(pPager);
   32434   }
   32435   iHdrOff = pPager->journalOff;
   32436 
   32437   /* Write the master journal data to the end of the journal file. If
   32438   ** an error occurs, return the error code to the caller.
   32439   */
   32440   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
   32441    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
   32442    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
   32443    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
   32444    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
   32445   ){
   32446     return rc;
   32447   }
   32448   pPager->journalOff += (nMaster+20);
   32449   pPager->needSync = !pPager->noSync;
   32450 
   32451   /* If the pager is in peristent-journal mode, then the physical
   32452   ** journal-file may extend past the end of the master-journal name
   32453   ** and 8 bytes of magic data just written to the file. This is
   32454   ** dangerous because the code to rollback a hot-journal file
   32455   ** will not be able to find the master-journal name to determine
   32456   ** whether or not the journal is hot.
   32457   **
   32458   ** Easiest thing to do in this scenario is to truncate the journal
   32459   ** file to the required size.
   32460   */
   32461   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
   32462    && jrnlSize>pPager->journalOff
   32463   ){
   32464     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
   32465   }
   32466   return rc;
   32467 }
   32468 
   32469 /*
   32470 ** Find a page in the hash table given its page number. Return
   32471 ** a pointer to the page or NULL if the requested page is not
   32472 ** already in memory.
   32473 */
   32474 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
   32475   PgHdr *p;                         /* Return value */
   32476 
   32477   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
   32478   ** fail, since no attempt to allocate dynamic memory will be made.
   32479   */
   32480   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
   32481   return p;
   32482 }
   32483 
   32484 /*
   32485 ** Unless the pager is in error-state, discard all in-memory pages. If
   32486 ** the pager is in error-state, then this call is a no-op.
   32487 **
   32488 ** TODO: Why can we not reset the pager while in error state?
   32489 */
   32490 static void pager_reset(Pager *pPager){
   32491   if( SQLITE_OK==pPager->errCode ){
   32492     sqlite3BackupRestart(pPager->pBackup);
   32493     sqlite3PcacheClear(pPager->pPCache);
   32494     pPager->dbSizeValid = 0;
   32495   }
   32496 }
   32497 
   32498 /*
   32499 ** Free all structures in the Pager.aSavepoint[] array and set both
   32500 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
   32501 ** if it is open and the pager is not in exclusive mode.
   32502 */
   32503 static void releaseAllSavepoints(Pager *pPager){
   32504   int ii;               /* Iterator for looping through Pager.aSavepoint */
   32505   for(ii=0; ii<pPager->nSavepoint; ii++){
   32506     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
   32507   }
   32508   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
   32509     sqlite3OsClose(pPager->sjfd);
   32510   }
   32511   sqlite3_free(pPager->aSavepoint);
   32512   pPager->aSavepoint = 0;
   32513   pPager->nSavepoint = 0;
   32514   pPager->nSubRec = 0;
   32515 }
   32516 
   32517 /*
   32518 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
   32519 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
   32520 ** or SQLITE_NOMEM if a malloc failure occurs.
   32521 */
   32522 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
   32523   int ii;                   /* Loop counter */
   32524   int rc = SQLITE_OK;       /* Result code */
   32525 
   32526   for(ii=0; ii<pPager->nSavepoint; ii++){
   32527     PagerSavepoint *p = &pPager->aSavepoint[ii];
   32528     if( pgno<=p->nOrig ){
   32529       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
   32530       testcase( rc==SQLITE_NOMEM );
   32531       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   32532     }
   32533   }
   32534   return rc;
   32535 }
   32536 
   32537 /*
   32538 ** Unlock the database file. This function is a no-op if the pager
   32539 ** is in exclusive mode.
   32540 **
   32541 ** If the pager is currently in error state, discard the contents of
   32542 ** the cache and reset the Pager structure internal state. If there is
   32543 ** an open journal-file, then the next time a shared-lock is obtained
   32544 ** on the pager file (by this or any other process), it will be
   32545 ** treated as a hot-journal and rolled back.
   32546 */
   32547 static void pager_unlock(Pager *pPager){
   32548   if( !pPager->exclusiveMode ){
   32549     int rc;                      /* Return code */
   32550 
   32551     /* Always close the journal file when dropping the database lock.
   32552     ** Otherwise, another connection with journal_mode=delete might
   32553     ** delete the file out from under us.
   32554     */
   32555     sqlite3OsClose(pPager->jfd);
   32556     sqlite3BitvecDestroy(pPager->pInJournal);
   32557     pPager->pInJournal = 0;
   32558     releaseAllSavepoints(pPager);
   32559 
   32560     /* If the file is unlocked, somebody else might change it. The
   32561     ** values stored in Pager.dbSize etc. might become invalid if
   32562     ** this happens. TODO: Really, this doesn't need to be cleared
   32563     ** until the change-counter check fails in PagerSharedLock().
   32564     */
   32565     pPager->dbSizeValid = 0;
   32566 
   32567     rc = osUnlock(pPager->fd, NO_LOCK);
   32568     if( rc ){
   32569       pPager->errCode = rc;
   32570     }
   32571     IOTRACE(("UNLOCK %p\n", pPager))
   32572 
   32573     /* If Pager.errCode is set, the contents of the pager cache cannot be
   32574     ** trusted. Now that the pager file is unlocked, the contents of the
   32575     ** cache can be discarded and the error code safely cleared.
   32576     */
   32577     if( pPager->errCode ){
   32578       if( rc==SQLITE_OK ){
   32579         pPager->errCode = SQLITE_OK;
   32580       }
   32581       pager_reset(pPager);
   32582     }
   32583 
   32584     pPager->changeCountDone = 0;
   32585     pPager->state = PAGER_UNLOCK;
   32586     pPager->dbModified = 0;
   32587   }
   32588 }
   32589 
   32590 /*
   32591 ** This function should be called when an IOERR, CORRUPT or FULL error
   32592 ** may have occurred. The first argument is a pointer to the pager
   32593 ** structure, the second the error-code about to be returned by a pager
   32594 ** API function. The value returned is a copy of the second argument
   32595 ** to this function.
   32596 **
   32597 ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
   32598 ** the error becomes persistent. Until the persisten error is cleared,
   32599 ** subsequent API calls on this Pager will immediately return the same
   32600 ** error code.
   32601 **
   32602 ** A persistent error indicates that the contents of the pager-cache
   32603 ** cannot be trusted. This state can be cleared by completely discarding
   32604 ** the contents of the pager-cache. If a transaction was active when
   32605 ** the persistent error occurred, then the rollback journal may need
   32606 ** to be replayed to restore the contents of the database file (as if
   32607 ** it were a hot-journal).
   32608 */
   32609 static int pager_error(Pager *pPager, int rc){
   32610   int rc2 = rc & 0xff;
   32611   assert( rc==SQLITE_OK || !MEMDB );
   32612   assert(
   32613        pPager->errCode==SQLITE_FULL ||
   32614        pPager->errCode==SQLITE_OK ||
   32615        (pPager->errCode & 0xff)==SQLITE_IOERR
   32616   );
   32617   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
   32618     pPager->errCode = rc;
   32619   }
   32620   return rc;
   32621 }
   32622 
   32623 /*
   32624 ** Execute a rollback if a transaction is active and unlock the
   32625 ** database file.
   32626 **
   32627 ** If the pager has already entered the error state, do not attempt
   32628 ** the rollback at this time. Instead, pager_unlock() is called. The
   32629 ** call to pager_unlock() will discard all in-memory pages, unlock
   32630 ** the database file and clear the error state. If this means that
   32631 ** there is a hot-journal left in the file-system, the next connection
   32632 ** to obtain a shared lock on the pager (which may be this one) will
   32633 ** roll it back.
   32634 **
   32635 ** If the pager has not already entered the error state, but an IO or
   32636 ** malloc error occurs during a rollback, then this will itself cause
   32637 ** the pager to enter the error state. Which will be cleared by the
   32638 ** call to pager_unlock(), as described above.
   32639 */
   32640 static void pagerUnlockAndRollback(Pager *pPager){
   32641   if( pPager->errCode==SQLITE_OK && pPager->state>=PAGER_RESERVED ){
   32642     sqlite3BeginBenignMalloc();
   32643     sqlite3PagerRollback(pPager);
   32644     sqlite3EndBenignMalloc();
   32645   }
   32646   pager_unlock(pPager);
   32647 }
   32648 
   32649 /*
   32650 ** This routine ends a transaction. A transaction is usually ended by
   32651 ** either a COMMIT or a ROLLBACK operation. This routine may be called
   32652 ** after rollback of a hot-journal, or if an error occurs while opening
   32653 ** the journal file or writing the very first journal-header of a
   32654 ** database transaction.
   32655 **
   32656 ** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this
   32657 ** routine is called, it is a no-op (returns SQLITE_OK).
   32658 **
   32659 ** Otherwise, any active savepoints are released.
   32660 **
   32661 ** If the journal file is open, then it is "finalized". Once a journal
   32662 ** file has been finalized it is not possible to use it to roll back a
   32663 ** transaction. Nor will it be considered to be a hot-journal by this
   32664 ** or any other database connection. Exactly how a journal is finalized
   32665 ** depends on whether or not the pager is running in exclusive mode and
   32666 ** the current journal-mode (Pager.journalMode value), as follows:
   32667 **
   32668 **   journalMode==MEMORY
   32669 **     Journal file descriptor is simply closed. This destroys an
   32670 **     in-memory journal.
   32671 **
   32672 **   journalMode==TRUNCATE
   32673 **     Journal file is truncated to zero bytes in size.
   32674 **
   32675 **   journalMode==PERSIST
   32676 **     The first 28 bytes of the journal file are zeroed. This invalidates
   32677 **     the first journal header in the file, and hence the entire journal
   32678 **     file. An invalid journal file cannot be rolled back.
   32679 **
   32680 **   journalMode==DELETE
   32681 **     The journal file is closed and deleted using sqlite3OsDelete().
   32682 **
   32683 **     If the pager is running in exclusive mode, this method of finalizing
   32684 **     the journal file is never used. Instead, if the journalMode is
   32685 **     DELETE and the pager is in exclusive mode, the method described under
   32686 **     journalMode==PERSIST is used instead.
   32687 **
   32688 ** After the journal is finalized, if running in non-exclusive mode, the
   32689 ** pager moves to PAGER_SHARED state (and downgrades the lock on the
   32690 ** database file accordingly).
   32691 **
   32692 ** If the pager is running in exclusive mode and is in PAGER_SYNCED state,
   32693 ** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in
   32694 ** exclusive mode.
   32695 **
   32696 ** SQLITE_OK is returned if no error occurs. If an error occurs during
   32697 ** any of the IO operations to finalize the journal file or unlock the
   32698 ** database then the IO error code is returned to the user. If the
   32699 ** operation to finalize the journal file fails, then the code still
   32700 ** tries to unlock the database file if not in exclusive mode. If the
   32701 ** unlock operation fails as well, then the first error code related
   32702 ** to the first error encountered (the journal finalization one) is
   32703 ** returned.
   32704 */
   32705 static int pager_end_transaction(Pager *pPager, int hasMaster){
   32706   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
   32707   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
   32708 
   32709   if( pPager->state<PAGER_RESERVED ){
   32710     return SQLITE_OK;
   32711   }
   32712   releaseAllSavepoints(pPager);
   32713 
   32714   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
   32715   if( isOpen(pPager->jfd) ){
   32716 
   32717     /* Finalize the journal file. */
   32718     if( sqlite3IsMemJournal(pPager->jfd) ){
   32719       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
   32720       sqlite3OsClose(pPager->jfd);
   32721     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
   32722       if( pPager->journalOff==0 ){
   32723         rc = SQLITE_OK;
   32724       }else{
   32725         rc = sqlite3OsTruncate(pPager->jfd, 0);
   32726       }
   32727       pPager->journalOff = 0;
   32728       pPager->journalStarted = 0;
   32729     }else if( pPager->exclusiveMode
   32730      || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
   32731     ){
   32732       rc = zeroJournalHdr(pPager, hasMaster);
   32733       pager_error(pPager, rc);
   32734       pPager->journalOff = 0;
   32735       pPager->journalStarted = 0;
   32736     }else{
   32737       /* This branch may be executed with Pager.journalMode==MEMORY if
   32738       ** a hot-journal was just rolled back. In this case the journal
   32739       ** file should be closed and deleted. If this connection writes to
   32740       ** the database file, it will do so using an in-memory journal.  */
   32741       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
   32742            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
   32743       );
   32744       sqlite3OsClose(pPager->jfd);
   32745       if( !pPager->tempFile ){
   32746         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   32747       }
   32748     }
   32749 
   32750 #ifdef SQLITE_CHECK_PAGES
   32751     sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
   32752 #endif
   32753 
   32754     sqlite3PcacheCleanAll(pPager->pPCache);
   32755     sqlite3BitvecDestroy(pPager->pInJournal);
   32756     pPager->pInJournal = 0;
   32757     pPager->nRec = 0;
   32758   }
   32759 
   32760   if( !pPager->exclusiveMode ){
   32761     rc2 = osUnlock(pPager->fd, SHARED_LOCK);
   32762     pPager->state = PAGER_SHARED;
   32763     pPager->changeCountDone = 0;
   32764   }else if( pPager->state==PAGER_SYNCED ){
   32765     pPager->state = PAGER_EXCLUSIVE;
   32766   }
   32767   pPager->setMaster = 0;
   32768   pPager->needSync = 0;
   32769   pPager->dbModified = 0;
   32770 
   32771   /* TODO: Is this optimal? Why is the db size invalidated here
   32772   ** when the database file is not unlocked? */
   32773   pPager->dbOrigSize = 0;
   32774   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
   32775   if( !MEMDB ){
   32776     pPager->dbSizeValid = 0;
   32777   }
   32778 
   32779   return (rc==SQLITE_OK?rc2:rc);
   32780 }
   32781 
   32782 /*
   32783 ** Parameter aData must point to a buffer of pPager->pageSize bytes
   32784 ** of data. Compute and return a checksum based ont the contents of the
   32785 ** page of data and the current value of pPager->cksumInit.
   32786 **
   32787 ** This is not a real checksum. It is really just the sum of the
   32788 ** random initial value (pPager->cksumInit) and every 200th byte
   32789 ** of the page data, starting with byte offset (pPager->pageSize%200).
   32790 ** Each byte is interpreted as an 8-bit unsigned integer.
   32791 **
   32792 ** Changing the formula used to compute this checksum results in an
   32793 ** incompatible journal file format.
   32794 **
   32795 ** If journal corruption occurs due to a power failure, the most likely
   32796 ** scenario is that one end or the other of the record will be changed.
   32797 ** It is much less likely that the two ends of the journal record will be
   32798 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
   32799 ** though fast and simple, catches the mostly likely kind of corruption.
   32800 */
   32801 static u32 pager_cksum(Pager *pPager, const u8 *aData){
   32802   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
   32803   int i = pPager->pageSize-200;          /* Loop counter */
   32804   while( i>0 ){
   32805     cksum += aData[i];
   32806     i -= 200;
   32807   }
   32808   return cksum;
   32809 }
   32810 
   32811 /*
   32812 ** Read a single page from either the journal file (if isMainJrnl==1) or
   32813 ** from the sub-journal (if isMainJrnl==0) and playback that page.
   32814 ** The page begins at offset *pOffset into the file. The *pOffset
   32815 ** value is increased to the start of the next page in the journal.
   32816 **
   32817 ** The isMainJrnl flag is true if this is the main rollback journal and
   32818 ** false for the statement journal.  The main rollback journal uses
   32819 ** checksums - the statement journal does not.
   32820 **
   32821 ** If the page number of the page record read from the (sub-)journal file
   32822 ** is greater than the current value of Pager.dbSize, then playback is
   32823 ** skipped and SQLITE_OK is returned.
   32824 **
   32825 ** If pDone is not NULL, then it is a record of pages that have already
   32826 ** been played back.  If the page at *pOffset has already been played back
   32827 ** (if the corresponding pDone bit is set) then skip the playback.
   32828 ** Make sure the pDone bit corresponding to the *pOffset page is set
   32829 ** prior to returning.
   32830 **
   32831 ** If the page record is successfully read from the (sub-)journal file
   32832 ** and played back, then SQLITE_OK is returned. If an IO error occurs
   32833 ** while reading the record from the (sub-)journal file or while writing
   32834 ** to the database file, then the IO error code is returned. If data
   32835 ** is successfully read from the (sub-)journal file but appears to be
   32836 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
   32837 ** two circumstances:
   32838 **
   32839 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
   32840 **   * If the record is being rolled back from the main journal file
   32841 **     and the checksum field does not match the record content.
   32842 **
   32843 ** Neither of these two scenarios are possible during a savepoint rollback.
   32844 **
   32845 ** If this is a savepoint rollback, then memory may have to be dynamically
   32846 ** allocated by this function. If this is the case and an allocation fails,
   32847 ** SQLITE_NOMEM is returned.
   32848 */
   32849 static int pager_playback_one_page(
   32850   Pager *pPager,                /* The pager being played back */
   32851   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
   32852   int isUnsync,                 /* True if reading from unsynced main journal */
   32853   i64 *pOffset,                 /* Offset of record to playback */
   32854   int isSavepnt,                /* True for a savepoint rollback */
   32855   Bitvec *pDone                 /* Bitvec of pages already played back */
   32856 ){
   32857   int rc;
   32858   PgHdr *pPg;                   /* An existing page in the cache */
   32859   Pgno pgno;                    /* The page number of a page in journal */
   32860   u32 cksum;                    /* Checksum used for sanity checking */
   32861   char *aData;                  /* Temporary storage for the page */
   32862   sqlite3_file *jfd;            /* The file descriptor for the journal file */
   32863 
   32864   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
   32865   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
   32866   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
   32867   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
   32868 
   32869   aData = pPager->pTmpSpace;
   32870   assert( aData );         /* Temp storage must have already been allocated */
   32871 
   32872   /* Read the page number and page data from the journal or sub-journal
   32873   ** file. Return an error code to the caller if an IO error occurs.
   32874   */
   32875   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
   32876   rc = read32bits(jfd, *pOffset, &pgno);
   32877   if( rc!=SQLITE_OK ) return rc;
   32878   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
   32879   if( rc!=SQLITE_OK ) return rc;
   32880   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
   32881 
   32882   /* Sanity checking on the page.  This is more important that I originally
   32883   ** thought.  If a power failure occurs while the journal is being written,
   32884   ** it could cause invalid data to be written into the journal.  We need to
   32885   ** detect this invalid data (with high probability) and ignore it.
   32886   */
   32887   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
   32888     assert( !isSavepnt );
   32889     return SQLITE_DONE;
   32890   }
   32891   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
   32892     return SQLITE_OK;
   32893   }
   32894   if( isMainJrnl ){
   32895     rc = read32bits(jfd, (*pOffset)-4, &cksum);
   32896     if( rc ) return rc;
   32897     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
   32898       return SQLITE_DONE;
   32899     }
   32900   }
   32901 
   32902   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
   32903     return rc;
   32904   }
   32905 
   32906   assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
   32907 
   32908   /* If the pager is in RESERVED state, then there must be a copy of this
   32909   ** page in the pager cache. In this case just update the pager cache,
   32910   ** not the database file. The page is left marked dirty in this case.
   32911   **
   32912   ** An exception to the above rule: If the database is in no-sync mode
   32913   ** and a page is moved during an incremental vacuum then the page may
   32914   ** not be in the pager cache. Later: if a malloc() or IO error occurs
   32915   ** during a Movepage() call, then the page may not be in the cache
   32916   ** either. So the condition described in the above paragraph is not
   32917   ** assert()able.
   32918   **
   32919   ** If in EXCLUSIVE state, then we update the pager cache if it exists
   32920   ** and the main file. The page is then marked not dirty.
   32921   **
   32922   ** Ticket #1171:  The statement journal might contain page content that is
   32923   ** different from the page content at the start of the transaction.
   32924   ** This occurs when a page is changed prior to the start of a statement
   32925   ** then changed again within the statement.  When rolling back such a
   32926   ** statement we must not write to the original database unless we know
   32927   ** for certain that original page contents are synced into the main rollback
   32928   ** journal.  Otherwise, a power loss might leave modified data in the
   32929   ** database file without an entry in the rollback journal that can
   32930   ** restore the database to its original form.  Two conditions must be
   32931   ** met before writing to the database files. (1) the database must be
   32932   ** locked.  (2) we know that the original page content is fully synced
   32933   ** in the main journal either because the page is not in cache or else
   32934   ** the page is marked as needSync==0.
   32935   **
   32936   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
   32937   ** is possible to fail a statement on a database that does not yet exist.
   32938   ** Do not attempt to write if database file has never been opened.
   32939   */
   32940   pPg = pager_lookup(pPager, pgno);
   32941   assert( pPg || !MEMDB );
   32942   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
   32943            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
   32944            (isMainJrnl?"main-journal":"sub-journal")
   32945   ));
   32946   if( (pPager->state>=PAGER_EXCLUSIVE)
   32947    && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
   32948    && isOpen(pPager->fd)
   32949    && !isUnsync
   32950   ){
   32951     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
   32952     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
   32953     if( pgno>pPager->dbFileSize ){
   32954       pPager->dbFileSize = pgno;
   32955     }
   32956     if( pPager->pBackup ){
   32957       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
   32958       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
   32959       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
   32960     }
   32961   }else if( !isMainJrnl && pPg==0 ){
   32962     /* If this is a rollback of a savepoint and data was not written to
   32963     ** the database and the page is not in-memory, there is a potential
   32964     ** problem. When the page is next fetched by the b-tree layer, it
   32965     ** will be read from the database file, which may or may not be
   32966     ** current.
   32967     **
   32968     ** There are a couple of different ways this can happen. All are quite
   32969     ** obscure. When running in synchronous mode, this can only happen
   32970     ** if the page is on the free-list at the start of the transaction, then
   32971     ** populated, then moved using sqlite3PagerMovepage().
   32972     **
   32973     ** The solution is to add an in-memory page to the cache containing
   32974     ** the data just read from the sub-journal. Mark the page as dirty
   32975     ** and if the pager requires a journal-sync, then mark the page as
   32976     ** requiring a journal-sync before it is written.
   32977     */
   32978     assert( isSavepnt );
   32979     if( (rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1))!=SQLITE_OK ){
   32980       return rc;
   32981     }
   32982     pPg->flags &= ~PGHDR_NEED_READ;
   32983     sqlite3PcacheMakeDirty(pPg);
   32984   }
   32985   if( pPg ){
   32986     /* No page should ever be explicitly rolled back that is in use, except
   32987     ** for page 1 which is held in use in order to keep the lock on the
   32988     ** database active. However such a page may be rolled back as a result
   32989     ** of an internal error resulting in an automatic call to
   32990     ** sqlite3PagerRollback().
   32991     */
   32992     void *pData;
   32993     pData = pPg->pData;
   32994     memcpy(pData, (u8*)aData, pPager->pageSize);
   32995     pPager->xReiniter(pPg);
   32996     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
   32997       /* If the contents of this page were just restored from the main
   32998       ** journal file, then its content must be as they were when the
   32999       ** transaction was first opened. In this case we can mark the page
   33000       ** as clean, since there will be no need to write it out to the.
   33001       **
   33002       ** There is one exception to this rule. If the page is being rolled
   33003       ** back as part of a savepoint (or statement) rollback from an
   33004       ** unsynced portion of the main journal file, then it is not safe
   33005       ** to mark the page as clean. This is because marking the page as
   33006       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
   33007       ** already in the journal file (recorded in Pager.pInJournal) and
   33008       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
   33009       ** again within this transaction, it will be marked as dirty but
   33010       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
   33011       ** be written out into the database file before its journal file
   33012       ** segment is synced. If a crash occurs during or following this,
   33013       ** database corruption may ensue.
   33014       */
   33015       sqlite3PcacheMakeClean(pPg);
   33016     }
   33017 #ifdef SQLITE_CHECK_PAGES
   33018     pPg->pageHash = pager_pagehash(pPg);
   33019 #endif
   33020     /* If this was page 1, then restore the value of Pager.dbFileVers.
   33021     ** Do this before any decoding. */
   33022     if( pgno==1 ){
   33023       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
   33024     }
   33025 
   33026     /* Decode the page just read from disk */
   33027     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
   33028     sqlite3PcacheRelease(pPg);
   33029   }
   33030   return rc;
   33031 }
   33032 
   33033 /*
   33034 ** Parameter zMaster is the name of a master journal file. A single journal
   33035 ** file that referred to the master journal file has just been rolled back.
   33036 ** This routine checks if it is possible to delete the master journal file,
   33037 ** and does so if it is.
   33038 **
   33039 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
   33040 ** available for use within this function.
   33041 **
   33042 ** When a master journal file is created, it is populated with the names
   33043 ** of all of its child journals, one after another, formatted as utf-8
   33044 ** encoded text. The end of each child journal file is marked with a
   33045 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
   33046 ** file for a transaction involving two databases might be:
   33047 **
   33048 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
   33049 **
   33050 ** A master journal file may only be deleted once all of its child
   33051 ** journals have been rolled back.
   33052 **
   33053 ** This function reads the contents of the master-journal file into
   33054 ** memory and loops through each of the child journal names. For
   33055 ** each child journal, it checks if:
   33056 **
   33057 **   * if the child journal exists, and if so
   33058 **   * if the child journal contains a reference to master journal
   33059 **     file zMaster
   33060 **
   33061 ** If a child journal can be found that matches both of the criteria
   33062 ** above, this function returns without doing anything. Otherwise, if
   33063 ** no such child journal can be found, file zMaster is deleted from
   33064 ** the file-system using sqlite3OsDelete().
   33065 **
   33066 ** If an IO error within this function, an error code is returned. This
   33067 ** function allocates memory by calling sqlite3Malloc(). If an allocation
   33068 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
   33069 ** occur, SQLITE_OK is returned.
   33070 **
   33071 ** TODO: This function allocates a single block of memory to load
   33072 ** the entire contents of the master journal file. This could be
   33073 ** a couple of kilobytes or so - potentially larger than the page
   33074 ** size.
   33075 */
   33076 static int pager_delmaster(Pager *pPager, const char *zMaster){
   33077   sqlite3_vfs *pVfs = pPager->pVfs;
   33078   int rc;                   /* Return code */
   33079   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
   33080   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
   33081   char *zMasterJournal = 0; /* Contents of master journal file */
   33082   i64 nMasterJournal;       /* Size of master journal file */
   33083 
   33084   /* Allocate space for both the pJournal and pMaster file descriptors.
   33085   ** If successful, open the master journal file for reading.
   33086   */
   33087   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
   33088   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
   33089   if( !pMaster ){
   33090     rc = SQLITE_NOMEM;
   33091   }else{
   33092     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
   33093     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
   33094   }
   33095   if( rc!=SQLITE_OK ) goto delmaster_out;
   33096 
   33097   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
   33098   if( rc!=SQLITE_OK ) goto delmaster_out;
   33099 
   33100   if( nMasterJournal>0 ){
   33101     char *zJournal;
   33102     char *zMasterPtr = 0;
   33103     int nMasterPtr = pVfs->mxPathname+1;
   33104 
   33105     /* Load the entire master journal file into space obtained from
   33106     ** sqlite3_malloc() and pointed to by zMasterJournal.
   33107     */
   33108     zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
   33109     if( !zMasterJournal ){
   33110       rc = SQLITE_NOMEM;
   33111       goto delmaster_out;
   33112     }
   33113     zMasterPtr = &zMasterJournal[nMasterJournal+1];
   33114     rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
   33115     if( rc!=SQLITE_OK ) goto delmaster_out;
   33116     zMasterJournal[nMasterJournal] = 0;
   33117 
   33118     zJournal = zMasterJournal;
   33119     while( (zJournal-zMasterJournal)<nMasterJournal ){
   33120       int exists;
   33121       rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
   33122       if( rc!=SQLITE_OK ){
   33123         goto delmaster_out;
   33124       }
   33125       if( exists ){
   33126         /* One of the journals pointed to by the master journal exists.
   33127         ** Open it and check if it points at the master journal. If
   33128         ** so, return without deleting the master journal file.
   33129         */
   33130         int c;
   33131         int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
   33132         rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
   33133         if( rc!=SQLITE_OK ){
   33134           goto delmaster_out;
   33135         }
   33136 
   33137         rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
   33138         sqlite3OsClose(pJournal);
   33139         if( rc!=SQLITE_OK ){
   33140           goto delmaster_out;
   33141         }
   33142 
   33143         c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
   33144         if( c ){
   33145           /* We have a match. Do not delete the master journal file. */
   33146           goto delmaster_out;
   33147         }
   33148       }
   33149       zJournal += (sqlite3Strlen30(zJournal)+1);
   33150     }
   33151   }
   33152 
   33153   rc = sqlite3OsDelete(pVfs, zMaster, 0);
   33154 
   33155 delmaster_out:
   33156   if( zMasterJournal ){
   33157     sqlite3_free(zMasterJournal);
   33158   }
   33159   if( pMaster ){
   33160     sqlite3OsClose(pMaster);
   33161     assert( !isOpen(pJournal) );
   33162   }
   33163   sqlite3_free(pMaster);
   33164   return rc;
   33165 }
   33166 
   33167 
   33168 /*
   33169 ** This function is used to change the actual size of the database
   33170 ** file in the file-system. This only happens when committing a transaction,
   33171 ** or rolling back a transaction (including rolling back a hot-journal).
   33172 **
   33173 ** If the main database file is not open, or an exclusive lock is not
   33174 ** held, this function is a no-op. Otherwise, the size of the file is
   33175 ** changed to nPage pages (nPage*pPager->pageSize bytes). If the file
   33176 ** on disk is currently larger than nPage pages, then use the VFS
   33177 ** xTruncate() method to truncate it.
   33178 **
   33179 ** Or, it might might be the case that the file on disk is smaller than
   33180 ** nPage pages. Some operating system implementations can get confused if
   33181 ** you try to truncate a file to some size that is larger than it
   33182 ** currently is, so detect this case and write a single zero byte to
   33183 ** the end of the new file instead.
   33184 **
   33185 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
   33186 ** the database file, return the error code to the caller.
   33187 */
   33188 static int pager_truncate(Pager *pPager, Pgno nPage){
   33189   int rc = SQLITE_OK;
   33190   if( pPager->state>=PAGER_EXCLUSIVE && isOpen(pPager->fd) ){
   33191     i64 currentSize, newSize;
   33192     /* TODO: Is it safe to use Pager.dbFileSize here? */
   33193     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
   33194     newSize = pPager->pageSize*(i64)nPage;
   33195     if( rc==SQLITE_OK && currentSize!=newSize ){
   33196       if( currentSize>newSize ){
   33197         rc = sqlite3OsTruncate(pPager->fd, newSize);
   33198       }else{
   33199         rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
   33200       }
   33201       if( rc==SQLITE_OK ){
   33202         pPager->dbFileSize = nPage;
   33203       }
   33204     }
   33205   }
   33206   return rc;
   33207 }
   33208 
   33209 /*
   33210 ** Set the value of the Pager.sectorSize variable for the given
   33211 ** pager based on the value returned by the xSectorSize method
   33212 ** of the open database file. The sector size will be used used
   33213 ** to determine the size and alignment of journal header and
   33214 ** master journal pointers within created journal files.
   33215 **
   33216 ** For temporary files the effective sector size is always 512 bytes.
   33217 **
   33218 ** Otherwise, for non-temporary files, the effective sector size is
   33219 ** the value returned by the xSectorSize() method rounded up to 32 if
   33220 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
   33221 ** is greater than MAX_SECTOR_SIZE.
   33222 */
   33223 static void setSectorSize(Pager *pPager){
   33224   assert( isOpen(pPager->fd) || pPager->tempFile );
   33225 
   33226   if( !pPager->tempFile ){
   33227     /* Sector size doesn't matter for temporary files. Also, the file
   33228     ** may not have been opened yet, in which case the OsSectorSize()
   33229     ** call will segfault.
   33230     */
   33231     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
   33232   }
   33233   if( pPager->sectorSize<32 ){
   33234     pPager->sectorSize = 512;
   33235   }
   33236   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
   33237     assert( MAX_SECTOR_SIZE>=512 );
   33238     pPager->sectorSize = MAX_SECTOR_SIZE;
   33239   }
   33240 }
   33241 
   33242 /*
   33243 ** Playback the journal and thus restore the database file to
   33244 ** the state it was in before we started making changes.
   33245 **
   33246 ** The journal file format is as follows:
   33247 **
   33248 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
   33249 **  (2)  4 byte big-endian integer which is the number of valid page records
   33250 **       in the journal.  If this value is 0xffffffff, then compute the
   33251 **       number of page records from the journal size.
   33252 **  (3)  4 byte big-endian integer which is the initial value for the
   33253 **       sanity checksum.
   33254 **  (4)  4 byte integer which is the number of pages to truncate the
   33255 **       database to during a rollback.
   33256 **  (5)  4 byte big-endian integer which is the sector size.  The header
   33257 **       is this many bytes in size.
   33258 **  (6)  4 byte big-endian integer which is the page size.
   33259 **  (7)  zero padding out to the next sector size.
   33260 **  (8)  Zero or more pages instances, each as follows:
   33261 **        +  4 byte page number.
   33262 **        +  pPager->pageSize bytes of data.
   33263 **        +  4 byte checksum
   33264 **
   33265 ** When we speak of the journal header, we mean the first 7 items above.
   33266 ** Each entry in the journal is an instance of the 8th item.
   33267 **
   33268 ** Call the value from the second bullet "nRec".  nRec is the number of
   33269 ** valid page entries in the journal.  In most cases, you can compute the
   33270 ** value of nRec from the size of the journal file.  But if a power
   33271 ** failure occurred while the journal was being written, it could be the
   33272 ** case that the size of the journal file had already been increased but
   33273 ** the extra entries had not yet made it safely to disk.  In such a case,
   33274 ** the value of nRec computed from the file size would be too large.  For
   33275 ** that reason, we always use the nRec value in the header.
   33276 **
   33277 ** If the nRec value is 0xffffffff it means that nRec should be computed
   33278 ** from the file size.  This value is used when the user selects the
   33279 ** no-sync option for the journal.  A power failure could lead to corruption
   33280 ** in this case.  But for things like temporary table (which will be
   33281 ** deleted when the power is restored) we don't care.
   33282 **
   33283 ** If the file opened as the journal file is not a well-formed
   33284 ** journal file then all pages up to the first corrupted page are rolled
   33285 ** back (or no pages if the journal header is corrupted). The journal file
   33286 ** is then deleted and SQLITE_OK returned, just as if no corruption had
   33287 ** been encountered.
   33288 **
   33289 ** If an I/O or malloc() error occurs, the journal-file is not deleted
   33290 ** and an error code is returned.
   33291 **
   33292 ** The isHot parameter indicates that we are trying to rollback a journal
   33293 ** that might be a hot journal.  Or, it could be that the journal is
   33294 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
   33295 ** If the journal really is hot, reset the pager cache prior rolling
   33296 ** back any content.  If the journal is merely persistent, no reset is
   33297 ** needed.
   33298 */
   33299 static int pager_playback(Pager *pPager, int isHot){
   33300   sqlite3_vfs *pVfs = pPager->pVfs;
   33301   i64 szJ;                 /* Size of the journal file in bytes */
   33302   u32 nRec;                /* Number of Records in the journal */
   33303   u32 u;                   /* Unsigned loop counter */
   33304   Pgno mxPg = 0;           /* Size of the original file in pages */
   33305   int rc;                  /* Result code of a subroutine */
   33306   int res = 1;             /* Value returned by sqlite3OsAccess() */
   33307   char *zMaster = 0;       /* Name of master journal file if any */
   33308   int needPagerReset;      /* True to reset page prior to first page rollback */
   33309 
   33310   /* Figure out how many records are in the journal.  Abort early if
   33311   ** the journal is empty.
   33312   */
   33313   assert( isOpen(pPager->jfd) );
   33314   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
   33315   if( rc!=SQLITE_OK || szJ==0 ){
   33316     goto end_playback;
   33317   }
   33318 
   33319   /* Read the master journal name from the journal, if it is present.
   33320   ** If a master journal file name is specified, but the file is not
   33321   ** present on disk, then the journal is not hot and does not need to be
   33322   ** played back.
   33323   **
   33324   ** TODO: Technically the following is an error because it assumes that
   33325   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
   33326   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
   33327   **  mxPathname is 512, which is the same as the minimum allowable value
   33328   ** for pageSize.
   33329   */
   33330   zMaster = pPager->pTmpSpace;
   33331   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
   33332   if( rc==SQLITE_OK && zMaster[0] ){
   33333     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
   33334   }
   33335   zMaster = 0;
   33336   if( rc!=SQLITE_OK || !res ){
   33337     goto end_playback;
   33338   }
   33339   pPager->journalOff = 0;
   33340   needPagerReset = isHot;
   33341 
   33342   /* This loop terminates either when a readJournalHdr() or
   33343   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
   33344   ** occurs.
   33345   */
   33346   while( 1 ){
   33347     int isUnsync = 0;
   33348 
   33349     /* Read the next journal header from the journal file.  If there are
   33350     ** not enough bytes left in the journal file for a complete header, or
   33351     ** it is corrupted, then a process must of failed while writing it.
   33352     ** This indicates nothing more needs to be rolled back.
   33353     */
   33354     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
   33355     if( rc!=SQLITE_OK ){
   33356       if( rc==SQLITE_DONE ){
   33357         rc = SQLITE_OK;
   33358       }
   33359       goto end_playback;
   33360     }
   33361 
   33362     /* If nRec is 0xffffffff, then this journal was created by a process
   33363     ** working in no-sync mode. This means that the rest of the journal
   33364     ** file consists of pages, there are no more journal headers. Compute
   33365     ** the value of nRec based on this assumption.
   33366     */
   33367     if( nRec==0xffffffff ){
   33368       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
   33369       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
   33370     }
   33371 
   33372     /* If nRec is 0 and this rollback is of a transaction created by this
   33373     ** process and if this is the final header in the journal, then it means
   33374     ** that this part of the journal was being filled but has not yet been
   33375     ** synced to disk.  Compute the number of pages based on the remaining
   33376     ** size of the file.
   33377     **
   33378     ** The third term of the test was added to fix ticket #2565.
   33379     ** When rolling back a hot journal, nRec==0 always means that the next
   33380     ** chunk of the journal contains zero pages to be rolled back.  But
   33381     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
   33382     ** the journal, it means that the journal might contain additional
   33383     ** pages that need to be rolled back and that the number of pages
   33384     ** should be computed based on the journal file size.
   33385     */
   33386     if( nRec==0 && !isHot &&
   33387         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
   33388       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
   33389       isUnsync = 1;
   33390     }
   33391 
   33392     /* If this is the first header read from the journal, truncate the
   33393     ** database file back to its original size.
   33394     */
   33395     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
   33396       rc = pager_truncate(pPager, mxPg);
   33397       if( rc!=SQLITE_OK ){
   33398         goto end_playback;
   33399       }
   33400       pPager->dbSize = mxPg;
   33401     }
   33402 
   33403     /* Copy original pages out of the journal and back into the
   33404     ** database file and/or page cache.
   33405     */
   33406     for(u=0; u<nRec; u++){
   33407       if( needPagerReset ){
   33408         pager_reset(pPager);
   33409         needPagerReset = 0;
   33410       }
   33411       rc = pager_playback_one_page(pPager,1,isUnsync,&pPager->journalOff,0,0);
   33412       if( rc!=SQLITE_OK ){
   33413         if( rc==SQLITE_DONE ){
   33414           rc = SQLITE_OK;
   33415           pPager->journalOff = szJ;
   33416           break;
   33417         }else{
   33418           /* If we are unable to rollback, quit and return the error
   33419           ** code.  This will cause the pager to enter the error state
   33420           ** so that no further harm will be done.  Perhaps the next
   33421           ** process to come along will be able to rollback the database.
   33422           */
   33423           goto end_playback;
   33424         }
   33425       }
   33426     }
   33427   }
   33428   /*NOTREACHED*/
   33429   assert( 0 );
   33430 
   33431 end_playback:
   33432   /* Following a rollback, the database file should be back in its original
   33433   ** state prior to the start of the transaction, so invoke the
   33434   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
   33435   ** assertion that the transaction counter was modified.
   33436   */
   33437   assert(
   33438     pPager->fd->pMethods==0 ||
   33439     sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
   33440   );
   33441 
   33442   /* If this playback is happening automatically as a result of an IO or
   33443   ** malloc error that occurred after the change-counter was updated but
   33444   ** before the transaction was committed, then the change-counter
   33445   ** modification may just have been reverted. If this happens in exclusive
   33446   ** mode, then subsequent transactions performed by the connection will not
   33447   ** update the change-counter at all. This may lead to cache inconsistency
   33448   ** problems for other processes at some point in the future. So, just
   33449   ** in case this has happened, clear the changeCountDone flag now.
   33450   */
   33451   pPager->changeCountDone = pPager->tempFile;
   33452 
   33453   if( rc==SQLITE_OK ){
   33454     zMaster = pPager->pTmpSpace;
   33455     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
   33456     testcase( rc!=SQLITE_OK );
   33457   }
   33458   if( rc==SQLITE_OK && pPager->noSync==0 && pPager->state>=PAGER_EXCLUSIVE ){
   33459     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
   33460   }
   33461   if( rc==SQLITE_OK ){
   33462     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
   33463     testcase( rc!=SQLITE_OK );
   33464   }
   33465   if( rc==SQLITE_OK && zMaster[0] && res ){
   33466     /* If there was a master journal and this routine will return success,
   33467     ** see if it is possible to delete the master journal.
   33468     */
   33469     rc = pager_delmaster(pPager, zMaster);
   33470     testcase( rc!=SQLITE_OK );
   33471   }
   33472 
   33473   /* The Pager.sectorSize variable may have been updated while rolling
   33474   ** back a journal created by a process with a different sector size
   33475   ** value. Reset it to the correct value for this process.
   33476   */
   33477   setSectorSize(pPager);
   33478   return rc;
   33479 }
   33480 
   33481 /*
   33482 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
   33483 ** the entire master journal file. The case pSavepoint==NULL occurs when
   33484 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
   33485 ** savepoint.
   33486 **
   33487 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
   33488 ** being rolled back), then the rollback consists of up to three stages,
   33489 ** performed in the order specified:
   33490 **
   33491 **   * Pages are played back from the main journal starting at byte
   33492 **     offset PagerSavepoint.iOffset and continuing to
   33493 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
   33494 **     file if PagerSavepoint.iHdrOffset is zero.
   33495 **
   33496 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
   33497 **     back starting from the journal header immediately following
   33498 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
   33499 **
   33500 **   * Pages are then played back from the sub-journal file, starting
   33501 **     with the PagerSavepoint.iSubRec and continuing to the end of
   33502 **     the journal file.
   33503 **
   33504 ** Throughout the rollback process, each time a page is rolled back, the
   33505 ** corresponding bit is set in a bitvec structure (variable pDone in the
   33506 ** implementation below). This is used to ensure that a page is only
   33507 ** rolled back the first time it is encountered in either journal.
   33508 **
   33509 ** If pSavepoint is NULL, then pages are only played back from the main
   33510 ** journal file. There is no need for a bitvec in this case.
   33511 **
   33512 ** In either case, before playback commences the Pager.dbSize variable
   33513 ** is reset to the value that it held at the start of the savepoint
   33514 ** (or transaction). No page with a page-number greater than this value
   33515 ** is played back. If one is encountered it is simply skipped.
   33516 */
   33517 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
   33518   i64 szJ;                 /* Effective size of the main journal */
   33519   i64 iHdrOff;             /* End of first segment of main-journal records */
   33520   int rc = SQLITE_OK;      /* Return code */
   33521   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
   33522 
   33523   assert( pPager->state>=PAGER_SHARED );
   33524 
   33525   /* Allocate a bitvec to use to store the set of pages rolled back */
   33526   if( pSavepoint ){
   33527     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
   33528     if( !pDone ){
   33529       return SQLITE_NOMEM;
   33530     }
   33531   }
   33532 
   33533   /* Set the database size back to the value it was before the savepoint
   33534   ** being reverted was opened.
   33535   */
   33536   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
   33537 
   33538   /* Use pPager->journalOff as the effective size of the main rollback
   33539   ** journal.  The actual file might be larger than this in
   33540   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
   33541   ** past pPager->journalOff is off-limits to us.
   33542   */
   33543   szJ = pPager->journalOff;
   33544 
   33545   /* Begin by rolling back records from the main journal starting at
   33546   ** PagerSavepoint.iOffset and continuing to the next journal header.
   33547   ** There might be records in the main journal that have a page number
   33548   ** greater than the current database size (pPager->dbSize) but those
   33549   ** will be skipped automatically.  Pages are added to pDone as they
   33550   ** are played back.
   33551   */
   33552   if( pSavepoint ){
   33553     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
   33554     pPager->journalOff = pSavepoint->iOffset;
   33555     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
   33556       rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
   33557     }
   33558     assert( rc!=SQLITE_DONE );
   33559   }else{
   33560     pPager->journalOff = 0;
   33561   }
   33562 
   33563   /* Continue rolling back records out of the main journal starting at
   33564   ** the first journal header seen and continuing until the effective end
   33565   ** of the main journal file.  Continue to skip out-of-range pages and
   33566   ** continue adding pages rolled back to pDone.
   33567   */
   33568   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
   33569     u32 ii;            /* Loop counter */
   33570     u32 nJRec = 0;     /* Number of Journal Records */
   33571     u32 dummy;
   33572     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
   33573     assert( rc!=SQLITE_DONE );
   33574 
   33575     /*
   33576     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
   33577     ** test is related to ticket #2565.  See the discussion in the
   33578     ** pager_playback() function for additional information.
   33579     */
   33580     if( nJRec==0
   33581      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
   33582     ){
   33583       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
   33584     }
   33585     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
   33586       rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
   33587     }
   33588     assert( rc!=SQLITE_DONE );
   33589   }
   33590   assert( rc!=SQLITE_OK || pPager->journalOff==szJ );
   33591 
   33592   /* Finally,  rollback pages from the sub-journal.  Page that were
   33593   ** previously rolled back out of the main journal (and are hence in pDone)
   33594   ** will be skipped.  Out-of-range pages are also skipped.
   33595   */
   33596   if( pSavepoint ){
   33597     u32 ii;            /* Loop counter */
   33598     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
   33599     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
   33600       assert( offset==ii*(4+pPager->pageSize) );
   33601       rc = pager_playback_one_page(pPager, 0, 0, &offset, 1, pDone);
   33602     }
   33603     assert( rc!=SQLITE_DONE );
   33604   }
   33605 
   33606   sqlite3BitvecDestroy(pDone);
   33607   if( rc==SQLITE_OK ){
   33608     pPager->journalOff = szJ;
   33609   }
   33610   return rc;
   33611 }
   33612 
   33613 /*
   33614 ** Change the maximum number of in-memory pages that are allowed.
   33615 */
   33616 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
   33617   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
   33618 }
   33619 
   33620 /*
   33621 ** Adjust the robustness of the database to damage due to OS crashes
   33622 ** or power failures by changing the number of syncs()s when writing
   33623 ** the rollback journal.  There are three levels:
   33624 **
   33625 **    OFF       sqlite3OsSync() is never called.  This is the default
   33626 **              for temporary and transient files.
   33627 **
   33628 **    NORMAL    The journal is synced once before writes begin on the
   33629 **              database.  This is normally adequate protection, but
   33630 **              it is theoretically possible, though very unlikely,
   33631 **              that an inopertune power failure could leave the journal
   33632 **              in a state which would cause damage to the database
   33633 **              when it is rolled back.
   33634 **
   33635 **    FULL      The journal is synced twice before writes begin on the
   33636 **              database (with some additional information - the nRec field
   33637 **              of the journal header - being written in between the two
   33638 **              syncs).  If we assume that writing a
   33639 **              single disk sector is atomic, then this mode provides
   33640 **              assurance that the journal will not be corrupted to the
   33641 **              point of causing damage to the database during rollback.
   33642 **
   33643 ** Numeric values associated with these states are OFF==1, NORMAL=2,
   33644 ** and FULL=3.
   33645 */
   33646 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   33647 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
   33648   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
   33649   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
   33650   pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
   33651   if( pPager->noSync ) pPager->needSync = 0;
   33652 }
   33653 #endif
   33654 
   33655 /*
   33656 ** The following global variable is incremented whenever the library
   33657 ** attempts to open a temporary file.  This information is used for
   33658 ** testing and analysis only.
   33659 */
   33660 #ifdef SQLITE_TEST
   33661 SQLITE_API int sqlite3_opentemp_count = 0;
   33662 #endif
   33663 
   33664 /*
   33665 ** Open a temporary file.
   33666 **
   33667 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
   33668 ** or some other error code if we fail. The OS will automatically
   33669 ** delete the temporary file when it is closed.
   33670 **
   33671 ** The flags passed to the VFS layer xOpen() call are those specified
   33672 ** by parameter vfsFlags ORed with the following:
   33673 **
   33674 **     SQLITE_OPEN_READWRITE
   33675 **     SQLITE_OPEN_CREATE
   33676 **     SQLITE_OPEN_EXCLUSIVE
   33677 **     SQLITE_OPEN_DELETEONCLOSE
   33678 */
   33679 static int pagerOpentemp(
   33680   Pager *pPager,        /* The pager object */
   33681   sqlite3_file *pFile,  /* Write the file descriptor here */
   33682   int vfsFlags          /* Flags passed through to the VFS */
   33683 ){
   33684   int rc;               /* Return code */
   33685 
   33686 #ifdef SQLITE_TEST
   33687   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
   33688 #endif
   33689 
   33690   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
   33691             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
   33692   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
   33693   assert( rc!=SQLITE_OK || isOpen(pFile) );
   33694   return rc;
   33695 }
   33696 
   33697 /*
   33698 ** Set the busy handler function.
   33699 **
   33700 ** The pager invokes the busy-handler if sqlite3OsLock() returns
   33701 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
   33702 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
   33703 ** lock. It does *not* invoke the busy handler when upgrading from
   33704 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
   33705 ** (which occurs during hot-journal rollback). Summary:
   33706 **
   33707 **   Transition                        | Invokes xBusyHandler
   33708 **   --------------------------------------------------------
   33709 **   NO_LOCK       -> SHARED_LOCK      | Yes
   33710 **   SHARED_LOCK   -> RESERVED_LOCK    | No
   33711 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
   33712 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
   33713 **
   33714 ** If the busy-handler callback returns non-zero, the lock is
   33715 ** retried. If it returns zero, then the SQLITE_BUSY error is
   33716 ** returned to the caller of the pager API function.
   33717 */
   33718 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
   33719   Pager *pPager,                       /* Pager object */
   33720   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
   33721   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
   33722 ){
   33723   pPager->xBusyHandler = xBusyHandler;
   33724   pPager->pBusyHandlerArg = pBusyHandlerArg;
   33725 }
   33726 
   33727 /*
   33728 ** Report the current page size and number of reserved bytes back
   33729 ** to the codec.
   33730 */
   33731 #ifdef SQLITE_HAS_CODEC
   33732 static void pagerReportSize(Pager *pPager){
   33733   if( pPager->xCodecSizeChng ){
   33734     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
   33735                            (int)pPager->nReserve);
   33736   }
   33737 }
   33738 #else
   33739 # define pagerReportSize(X)     /* No-op if we do not support a codec */
   33740 #endif
   33741 
   33742 /*
   33743 ** Change the page size used by the Pager object. The new page size
   33744 ** is passed in *pPageSize.
   33745 **
   33746 ** If the pager is in the error state when this function is called, it
   33747 ** is a no-op. The value returned is the error state error code (i.e.
   33748 ** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL).
   33749 **
   33750 ** Otherwise, if all of the following are true:
   33751 **
   33752 **   * the new page size (value of *pPageSize) is valid (a power
   33753 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
   33754 **
   33755 **   * there are no outstanding page references, and
   33756 **
   33757 **   * the database is either not an in-memory database or it is
   33758 **     an in-memory database that currently consists of zero pages.
   33759 **
   33760 ** then the pager object page size is set to *pPageSize.
   33761 **
   33762 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
   33763 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
   33764 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
   33765 ** In all other cases, SQLITE_OK is returned.
   33766 **
   33767 ** If the page size is not changed, either because one of the enumerated
   33768 ** conditions above is not true, the pager was in error state when this
   33769 ** function was called, or because the memory allocation attempt failed,
   33770 ** then *pPageSize is set to the old, retained page size before returning.
   33771 */
   33772 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize, int nReserve){
   33773   int rc = pPager->errCode;
   33774 
   33775   if( rc==SQLITE_OK ){
   33776     u16 pageSize = *pPageSize;
   33777     assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
   33778     if( (pPager->memDb==0 || pPager->dbSize==0)
   33779      && sqlite3PcacheRefCount(pPager->pPCache)==0
   33780      && pageSize && pageSize!=pPager->pageSize
   33781     ){
   33782       char *pNew = (char *)sqlite3PageMalloc(pageSize);
   33783       if( !pNew ){
   33784         rc = SQLITE_NOMEM;
   33785       }else{
   33786         pager_reset(pPager);
   33787         pPager->pageSize = pageSize;
   33788         sqlite3PageFree(pPager->pTmpSpace);
   33789         pPager->pTmpSpace = pNew;
   33790         sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
   33791       }
   33792     }
   33793     *pPageSize = (u16)pPager->pageSize;
   33794     if( nReserve<0 ) nReserve = pPager->nReserve;
   33795     assert( nReserve>=0 && nReserve<1000 );
   33796     pPager->nReserve = (i16)nReserve;
   33797     pagerReportSize(pPager);
   33798   }
   33799   return rc;
   33800 }
   33801 
   33802 /*
   33803 ** Return a pointer to the "temporary page" buffer held internally
   33804 ** by the pager.  This is a buffer that is big enough to hold the
   33805 ** entire content of a database page.  This buffer is used internally
   33806 ** during rollback and will be overwritten whenever a rollback
   33807 ** occurs.  But other modules are free to use it too, as long as
   33808 ** no rollbacks are happening.
   33809 */
   33810 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
   33811   return pPager->pTmpSpace;
   33812 }
   33813 
   33814 /*
   33815 ** Attempt to set the maximum database page count if mxPage is positive.
   33816 ** Make no changes if mxPage is zero or negative.  And never reduce the
   33817 ** maximum page count below the current size of the database.
   33818 **
   33819 ** Regardless of mxPage, return the current maximum page count.
   33820 */
   33821 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
   33822   if( mxPage>0 ){
   33823     pPager->mxPgno = mxPage;
   33824   }
   33825   sqlite3PagerPagecount(pPager, 0);
   33826   return pPager->mxPgno;
   33827 }
   33828 
   33829 /*
   33830 ** The following set of routines are used to disable the simulated
   33831 ** I/O error mechanism.  These routines are used to avoid simulated
   33832 ** errors in places where we do not care about errors.
   33833 **
   33834 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
   33835 ** and generate no code.
   33836 */
   33837 #ifdef SQLITE_TEST
   33838 SQLITE_API extern int sqlite3_io_error_pending;
   33839 SQLITE_API extern int sqlite3_io_error_hit;
   33840 static int saved_cnt;
   33841 void disable_simulated_io_errors(void){
   33842   saved_cnt = sqlite3_io_error_pending;
   33843   sqlite3_io_error_pending = -1;
   33844 }
   33845 void enable_simulated_io_errors(void){
   33846   sqlite3_io_error_pending = saved_cnt;
   33847 }
   33848 #else
   33849 # define disable_simulated_io_errors()
   33850 # define enable_simulated_io_errors()
   33851 #endif
   33852 
   33853 /*
   33854 ** Read the first N bytes from the beginning of the file into memory
   33855 ** that pDest points to.
   33856 **
   33857 ** If the pager was opened on a transient file (zFilename==""), or
   33858 ** opened on a file less than N bytes in size, the output buffer is
   33859 ** zeroed and SQLITE_OK returned. The rationale for this is that this
   33860 ** function is used to read database headers, and a new transient or
   33861 ** zero sized database has a header than consists entirely of zeroes.
   33862 **
   33863 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
   33864 ** the error code is returned to the caller and the contents of the
   33865 ** output buffer undefined.
   33866 */
   33867 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
   33868   int rc = SQLITE_OK;
   33869   memset(pDest, 0, N);
   33870   assert( isOpen(pPager->fd) || pPager->tempFile );
   33871   if( isOpen(pPager->fd) ){
   33872     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
   33873     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
   33874     if( rc==SQLITE_IOERR_SHORT_READ ){
   33875       rc = SQLITE_OK;
   33876     }
   33877   }
   33878   return rc;
   33879 }
   33880 
   33881 /*
   33882 ** Return the total number of pages in the database file associated
   33883 ** with pPager. Normally, this is calculated as (<db file size>/<page-size>).
   33884 ** However, if the file is between 1 and <page-size> bytes in size, then
   33885 ** this is considered a 1 page file.
   33886 **
   33887 ** If the pager is in error state when this function is called, then the
   33888 ** error state error code is returned and *pnPage left unchanged. Or,
   33889 ** if the file system has to be queried for the size of the file and
   33890 ** the query attempt returns an IO error, the IO error code is returned
   33891 ** and *pnPage is left unchanged.
   33892 **
   33893 ** Otherwise, if everything is successful, then SQLITE_OK is returned
   33894 ** and *pnPage is set to the number of pages in the database.
   33895 */
   33896 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
   33897   Pgno nPage;               /* Value to return via *pnPage */
   33898 
   33899   /* If the pager is already in the error state, return the error code. */
   33900   if( pPager->errCode ){
   33901     return pPager->errCode;
   33902   }
   33903 
   33904   /* Determine the number of pages in the file. Store this in nPage. */
   33905   if( pPager->dbSizeValid ){
   33906     nPage = pPager->dbSize;
   33907   }else{
   33908     int rc;                 /* Error returned by OsFileSize() */
   33909     i64 n = 0;              /* File size in bytes returned by OsFileSize() */
   33910 
   33911     assert( isOpen(pPager->fd) || pPager->tempFile );
   33912     if( isOpen(pPager->fd) && (0 != (rc = sqlite3OsFileSize(pPager->fd, &n))) ){
   33913       pager_error(pPager, rc);
   33914       return rc;
   33915     }
   33916     if( n>0 && n<pPager->pageSize ){
   33917       nPage = 1;
   33918     }else{
   33919       nPage = (Pgno)(n / pPager->pageSize);
   33920     }
   33921     if( pPager->state!=PAGER_UNLOCK ){
   33922       pPager->dbSize = nPage;
   33923       pPager->dbFileSize = nPage;
   33924       pPager->dbSizeValid = 1;
   33925     }
   33926   }
   33927 
   33928   /* If the current number of pages in the file is greater than the
   33929   ** configured maximum pager number, increase the allowed limit so
   33930   ** that the file can be read.
   33931   */
   33932   if( nPage>pPager->mxPgno ){
   33933     pPager->mxPgno = (Pgno)nPage;
   33934   }
   33935 
   33936   /* Set the output variable and return SQLITE_OK */
   33937   if( pnPage ){
   33938     *pnPage = nPage;
   33939   }
   33940   return SQLITE_OK;
   33941 }
   33942 
   33943 
   33944 /*
   33945 ** Try to obtain a lock of type locktype on the database file. If
   33946 ** a similar or greater lock is already held, this function is a no-op
   33947 ** (returning SQLITE_OK immediately).
   33948 **
   33949 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
   33950 ** the busy callback if the lock is currently not available. Repeat
   33951 ** until the busy callback returns false or until the attempt to
   33952 ** obtain the lock succeeds.
   33953 **
   33954 ** Return SQLITE_OK on success and an error code if we cannot obtain
   33955 ** the lock. If the lock is obtained successfully, set the Pager.state
   33956 ** variable to locktype before returning.
   33957 */
   33958 static int pager_wait_on_lock(Pager *pPager, int locktype){
   33959   int rc;                              /* Return code */
   33960 
   33961   /* The OS lock values must be the same as the Pager lock values */
   33962   assert( PAGER_SHARED==SHARED_LOCK );
   33963   assert( PAGER_RESERVED==RESERVED_LOCK );
   33964   assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
   33965 
   33966   /* If the file is currently unlocked then the size must be unknown. It
   33967   ** must not have been modified at this point.
   33968   */
   33969   assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );
   33970   assert( pPager->state>=PAGER_SHARED || pPager->dbModified==0 );
   33971 
   33972   /* Check that this is either a no-op (because the requested lock is
   33973   ** already held, or one of the transistions that the busy-handler
   33974   ** may be invoked during, according to the comment above
   33975   ** sqlite3PagerSetBusyhandler().
   33976   */
   33977   assert( (pPager->state>=locktype)
   33978        || (pPager->state==PAGER_UNLOCK && locktype==PAGER_SHARED)
   33979        || (pPager->state==PAGER_RESERVED && locktype==PAGER_EXCLUSIVE)
   33980   );
   33981 
   33982   if( pPager->state>=locktype ){
   33983     rc = SQLITE_OK;
   33984   }else{
   33985     do {
   33986       rc = sqlite3OsLock(pPager->fd, locktype);
   33987     }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
   33988     if( rc==SQLITE_OK ){
   33989       pPager->state = (u8)locktype;
   33990       IOTRACE(("LOCK %p %d\n", pPager, locktype))
   33991     }
   33992   }
   33993   return rc;
   33994 }
   33995 
   33996 /*
   33997 ** Function assertTruncateConstraint(pPager) checks that one of the
   33998 ** following is true for all dirty pages currently in the page-cache:
   33999 **
   34000 **   a) The page number is less than or equal to the size of the
   34001 **      current database image, in pages, OR
   34002 **
   34003 **   b) if the page content were written at this time, it would not
   34004 **      be necessary to write the current content out to the sub-journal
   34005 **      (as determined by function subjRequiresPage()).
   34006 **
   34007 ** If the condition asserted by this function were not true, and the
   34008 ** dirty page were to be discarded from the cache via the pagerStress()
   34009 ** routine, pagerStress() would not write the current page content to
   34010 ** the database file. If a savepoint transaction were rolled back after
   34011 ** this happened, the correct behaviour would be to restore the current
   34012 ** content of the page. However, since this content is not present in either
   34013 ** the database file or the portion of the rollback journal and
   34014 ** sub-journal rolled back the content could not be restored and the
   34015 ** database image would become corrupt. It is therefore fortunate that
   34016 ** this circumstance cannot arise.
   34017 */
   34018 #if defined(SQLITE_DEBUG)
   34019 static void assertTruncateConstraintCb(PgHdr *pPg){
   34020   assert( pPg->flags&PGHDR_DIRTY );
   34021   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
   34022 }
   34023 static void assertTruncateConstraint(Pager *pPager){
   34024   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
   34025 }
   34026 #else
   34027 # define assertTruncateConstraint(pPager)
   34028 #endif
   34029 
   34030 /*
   34031 ** Truncate the in-memory database file image to nPage pages. This
   34032 ** function does not actually modify the database file on disk. It
   34033 ** just sets the internal state of the pager object so that the
   34034 ** truncation will be done when the current transaction is committed.
   34035 */
   34036 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
   34037   assert( pPager->dbSizeValid );
   34038   assert( pPager->dbSize>=nPage );
   34039   assert( pPager->state>=PAGER_RESERVED );
   34040   pPager->dbSize = nPage;
   34041   assertTruncateConstraint(pPager);
   34042 }
   34043 
   34044 /*
   34045 ** Shutdown the page cache.  Free all memory and close all files.
   34046 **
   34047 ** If a transaction was in progress when this routine is called, that
   34048 ** transaction is rolled back.  All outstanding pages are invalidated
   34049 ** and their memory is freed.  Any attempt to use a page associated
   34050 ** with this page cache after this function returns will likely
   34051 ** result in a coredump.
   34052 **
   34053 ** This function always succeeds. If a transaction is active an attempt
   34054 ** is made to roll it back. If an error occurs during the rollback
   34055 ** a hot journal may be left in the filesystem but no error is returned
   34056 ** to the caller.
   34057 */
   34058 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
   34059   disable_simulated_io_errors();
   34060   sqlite3BeginBenignMalloc();
   34061   pPager->errCode = 0;
   34062   pPager->exclusiveMode = 0;
   34063   pager_reset(pPager);
   34064   if( MEMDB ){
   34065     pager_unlock(pPager);
   34066   }else{
   34067     /* Set Pager.journalHdr to -1 for the benefit of the pager_playback()
   34068     ** call which may be made from within pagerUnlockAndRollback(). If it
   34069     ** is not -1, then the unsynced portion of an open journal file may
   34070     ** be played back into the database. If a power failure occurs while
   34071     ** this is happening, the database may become corrupt.
   34072     */
   34073     pPager->journalHdr = -1;
   34074     pagerUnlockAndRollback(pPager);
   34075   }
   34076   sqlite3EndBenignMalloc();
   34077   enable_simulated_io_errors();
   34078   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
   34079   IOTRACE(("CLOSE %p\n", pPager))
   34080   sqlite3OsClose(pPager->fd);
   34081   sqlite3PageFree(pPager->pTmpSpace);
   34082   sqlite3PcacheClose(pPager->pPCache);
   34083 
   34084 #ifdef SQLITE_HAS_CODEC
   34085   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
   34086 #endif
   34087 
   34088   assert( !pPager->aSavepoint && !pPager->pInJournal );
   34089   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
   34090 
   34091   sqlite3_free(pPager);
   34092   return SQLITE_OK;
   34093 }
   34094 
   34095 #if !defined(NDEBUG) || defined(SQLITE_TEST)
   34096 /*
   34097 ** Return the page number for page pPg.
   34098 */
   34099 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
   34100   return pPg->pgno;
   34101 }
   34102 #endif
   34103 
   34104 /*
   34105 ** Increment the reference count for page pPg.
   34106 */
   34107 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
   34108   sqlite3PcacheRef(pPg);
   34109 }
   34110 
   34111 /*
   34112 ** Sync the journal. In other words, make sure all the pages that have
   34113 ** been written to the journal have actually reached the surface of the
   34114 ** disk and can be restored in the event of a hot-journal rollback.
   34115 **
   34116 ** If the Pager.needSync flag is not set, then this function is a
   34117 ** no-op. Otherwise, the actions required depend on the journal-mode
   34118 ** and the device characteristics of the the file-system, as follows:
   34119 **
   34120 **   * If the journal file is an in-memory journal file, no action need
   34121 **     be taken.
   34122 **
   34123 **   * Otherwise, if the device does not support the SAFE_APPEND property,
   34124 **     then the nRec field of the most recently written journal header
   34125 **     is updated to contain the number of journal records that have
   34126 **     been written following it. If the pager is operating in full-sync
   34127 **     mode, then the journal file is synced before this field is updated.
   34128 **
   34129 **   * If the device does not support the SEQUENTIAL property, then
   34130 **     journal file is synced.
   34131 **
   34132 ** Or, in pseudo-code:
   34133 **
   34134 **   if( NOT <in-memory journal> ){
   34135 **     if( NOT SAFE_APPEND ){
   34136 **       if( <full-sync mode> ) xSync(<journal file>);
   34137 **       <update nRec field>
   34138 **     }
   34139 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
   34140 **   }
   34141 **
   34142 ** The Pager.needSync flag is never be set for temporary files, or any
   34143 ** file operating in no-sync mode (Pager.noSync set to non-zero).
   34144 **
   34145 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
   34146 ** page currently held in memory before returning SQLITE_OK. If an IO
   34147 ** error is encountered, then the IO error code is returned to the caller.
   34148 */
   34149 static int syncJournal(Pager *pPager){
   34150   if( pPager->needSync ){
   34151     assert( !pPager->tempFile );
   34152     if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
   34153       int rc;                              /* Return code */
   34154       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
   34155       assert( isOpen(pPager->jfd) );
   34156 
   34157       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
   34158         /* This block deals with an obscure problem. If the last connection
   34159         ** that wrote to this database was operating in persistent-journal
   34160         ** mode, then the journal file may at this point actually be larger
   34161         ** than Pager.journalOff bytes. If the next thing in the journal
   34162         ** file happens to be a journal-header (written as part of the
   34163         ** previous connections transaction), and a crash or power-failure
   34164         ** occurs after nRec is updated but before this connection writes
   34165         ** anything else to the journal file (or commits/rolls back its
   34166         ** transaction), then SQLite may become confused when doing the
   34167         ** hot-journal rollback following recovery. It may roll back all
   34168         ** of this connections data, then proceed to rolling back the old,
   34169         ** out-of-date data that follows it. Database corruption.
   34170         **
   34171         ** To work around this, if the journal file does appear to contain
   34172         ** a valid header following Pager.journalOff, then write a 0x00
   34173         ** byte to the start of it to prevent it from being recognized.
   34174         **
   34175         ** Variable iNextHdrOffset is set to the offset at which this
   34176         ** problematic header will occur, if it exists. aMagic is used
   34177         ** as a temporary buffer to inspect the first couple of bytes of
   34178         ** the potential journal header.
   34179         */
   34180         i64 iNextHdrOffset;
   34181         u8 aMagic[8];
   34182 	u8 zHeader[sizeof(aJournalMagic)+4];
   34183 
   34184 	memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
   34185 	put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
   34186 
   34187         iNextHdrOffset = journalHdrOffset(pPager);
   34188         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
   34189         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
   34190           static const u8 zerobyte = 0;
   34191           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
   34192         }
   34193         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
   34194           return rc;
   34195         }
   34196 
   34197         /* Write the nRec value into the journal file header. If in
   34198         ** full-synchronous mode, sync the journal first. This ensures that
   34199         ** all data has really hit the disk before nRec is updated to mark
   34200         ** it as a candidate for rollback.
   34201         **
   34202         ** This is not required if the persistent media supports the
   34203         ** SAFE_APPEND property. Because in this case it is not possible
   34204         ** for garbage data to be appended to the file, the nRec field
   34205         ** is populated with 0xFFFFFFFF when the journal header is written
   34206         ** and never needs to be updated.
   34207         */
   34208         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
   34209           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
   34210           IOTRACE(("JSYNC %p\n", pPager))
   34211           rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
   34212           if( rc!=SQLITE_OK ) return rc;
   34213         }
   34214         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
   34215         rc = sqlite3OsWrite(
   34216             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
   34217 	);
   34218         if( rc!=SQLITE_OK ) return rc;
   34219       }
   34220       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
   34221         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
   34222         IOTRACE(("JSYNC %p\n", pPager))
   34223         rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags|
   34224           (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
   34225         );
   34226         if( rc!=SQLITE_OK ) return rc;
   34227       }
   34228     }
   34229 
   34230     /* The journal file was just successfully synced. Set Pager.needSync
   34231     ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess.
   34232     */
   34233     pPager->needSync = 0;
   34234     pPager->journalStarted = 1;
   34235     sqlite3PcacheClearSyncFlags(pPager->pPCache);
   34236   }
   34237 
   34238   return SQLITE_OK;
   34239 }
   34240 
   34241 /*
   34242 ** The argument is the first in a linked list of dirty pages connected
   34243 ** by the PgHdr.pDirty pointer. This function writes each one of the
   34244 ** in-memory pages in the list to the database file. The argument may
   34245 ** be NULL, representing an empty list. In this case this function is
   34246 ** a no-op.
   34247 **
   34248 ** The pager must hold at least a RESERVED lock when this function
   34249 ** is called. Before writing anything to the database file, this lock
   34250 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
   34251 ** SQLITE_BUSY is returned and no data is written to the database file.
   34252 **
   34253 ** If the pager is a temp-file pager and the actual file-system file
   34254 ** is not yet open, it is created and opened before any data is
   34255 ** written out.
   34256 **
   34257 ** Once the lock has been upgraded and, if necessary, the file opened,
   34258 ** the pages are written out to the database file in list order. Writing
   34259 ** a page is skipped if it meets either of the following criteria:
   34260 **
   34261 **   * The page number is greater than Pager.dbSize, or
   34262 **   * The PGHDR_DONT_WRITE flag is set on the page.
   34263 **
   34264 ** If writing out a page causes the database file to grow, Pager.dbFileSize
   34265 ** is updated accordingly. If page 1 is written out, then the value cached
   34266 ** in Pager.dbFileVers[] is updated to match the new value stored in
   34267 ** the database file.
   34268 **
   34269 ** If everything is successful, SQLITE_OK is returned. If an IO error
   34270 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
   34271 ** be obtained, SQLITE_BUSY is returned.
   34272 */
   34273 static int pager_write_pagelist(PgHdr *pList){
   34274   Pager *pPager;                       /* Pager object */
   34275   int rc;                              /* Return code */
   34276 
   34277   if( NEVER(pList==0) ) return SQLITE_OK;
   34278   pPager = pList->pPager;
   34279 
   34280   /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
   34281   ** database file. If there is already an EXCLUSIVE lock, the following
   34282   ** call is a no-op.
   34283   **
   34284   ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
   34285   ** through an intermediate state PENDING.   A PENDING lock prevents new
   34286   ** readers from attaching to the database but is unsufficient for us to
   34287   ** write.  The idea of a PENDING lock is to prevent new readers from
   34288   ** coming in while we wait for existing readers to clear.
   34289   **
   34290   ** While the pager is in the RESERVED state, the original database file
   34291   ** is unchanged and we can rollback without having to playback the
   34292   ** journal into the original database file.  Once we transition to
   34293   ** EXCLUSIVE, it means the database file has been changed and any rollback
   34294   ** will require a journal playback.
   34295   */
   34296   assert( pPager->state>=PAGER_RESERVED );
   34297   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
   34298 
   34299   /* If the file is a temp-file has not yet been opened, open it now. It
   34300   ** is not possible for rc to be other than SQLITE_OK if this branch
   34301   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
   34302   */
   34303   if( !isOpen(pPager->fd) ){
   34304     assert( pPager->tempFile && rc==SQLITE_OK );
   34305     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
   34306   }
   34307 
   34308   while( rc==SQLITE_OK && pList ){
   34309     Pgno pgno = pList->pgno;
   34310 
   34311     /* If there are dirty pages in the page cache with page numbers greater
   34312     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
   34313     ** make the file smaller (presumably by auto-vacuum code). Do not write
   34314     ** any such pages to the file.
   34315     **
   34316     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
   34317     ** set (set by sqlite3PagerDontWrite()).  Note that if compiled with
   34318     ** SQLITE_SECURE_DELETE the PGHDR_DONT_WRITE bit is never set and so
   34319     ** the second test is always true.
   34320     */
   34321     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
   34322       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
   34323       char *pData;                                   /* Data to write */
   34324 
   34325       /* Encode the database */
   34326       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
   34327 
   34328       /* Write out the page data. */
   34329       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
   34330 
   34331       /* If page 1 was just written, update Pager.dbFileVers to match
   34332       ** the value now stored in the database file. If writing this
   34333       ** page caused the database file to grow, update dbFileSize.
   34334       */
   34335       if( pgno==1 ){
   34336         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
   34337       }
   34338       if( pgno>pPager->dbFileSize ){
   34339         pPager->dbFileSize = pgno;
   34340       }
   34341 
   34342       /* Update any backup objects copying the contents of this pager. */
   34343       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
   34344 
   34345       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
   34346                    PAGERID(pPager), pgno, pager_pagehash(pList)));
   34347       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
   34348       PAGER_INCR(sqlite3_pager_writedb_count);
   34349       PAGER_INCR(pPager->nWrite);
   34350     }else{
   34351       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
   34352     }
   34353 #ifdef SQLITE_CHECK_PAGES
   34354     pList->pageHash = pager_pagehash(pList);
   34355 #endif
   34356     pList = pList->pDirty;
   34357   }
   34358 
   34359   return rc;
   34360 }
   34361 
   34362 /*
   34363 ** Append a record of the current state of page pPg to the sub-journal.
   34364 ** It is the callers responsibility to use subjRequiresPage() to check
   34365 ** that it is really required before calling this function.
   34366 **
   34367 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
   34368 ** for all open savepoints before returning.
   34369 **
   34370 ** This function returns SQLITE_OK if everything is successful, an IO
   34371 ** error code if the attempt to write to the sub-journal fails, or
   34372 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
   34373 ** bitvec.
   34374 */
   34375 static int subjournalPage(PgHdr *pPg){
   34376   int rc = SQLITE_OK;
   34377   Pager *pPager = pPg->pPager;
   34378   if( isOpen(pPager->sjfd) ){
   34379     void *pData = pPg->pData;
   34380     i64 offset = pPager->nSubRec*(4+pPager->pageSize);
   34381     char *pData2;
   34382 
   34383     CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
   34384     PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
   34385 
   34386     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
   34387     rc = write32bits(pPager->sjfd, offset, pPg->pgno);
   34388     if( rc==SQLITE_OK ){
   34389       rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
   34390     }
   34391   }
   34392   if( rc==SQLITE_OK ){
   34393     pPager->nSubRec++;
   34394     assert( pPager->nSavepoint>0 );
   34395     rc = addToSavepointBitvecs(pPager, pPg->pgno);
   34396   }
   34397   return rc;
   34398 }
   34399 
   34400 
   34401 /*
   34402 ** This function is called by the pcache layer when it has reached some
   34403 ** soft memory limit. The first argument is a pointer to a Pager object
   34404 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
   34405 ** database). The second argument is a reference to a page that is
   34406 ** currently dirty but has no outstanding references. The page
   34407 ** is always associated with the Pager object passed as the first
   34408 ** argument.
   34409 **
   34410 ** The job of this function is to make pPg clean by writing its contents
   34411 ** out to the database file, if possible. This may involve syncing the
   34412 ** journal file.
   34413 **
   34414 ** If successful, sqlite3PcacheMakeClean() is called on the page and
   34415 ** SQLITE_OK returned. If an IO error occurs while trying to make the
   34416 ** page clean, the IO error code is returned. If the page cannot be
   34417 ** made clean for some other reason, but no error occurs, then SQLITE_OK
   34418 ** is returned by sqlite3PcacheMakeClean() is not called.
   34419 */
   34420 static int pagerStress(void *p, PgHdr *pPg){
   34421   Pager *pPager = (Pager *)p;
   34422   int rc = SQLITE_OK;
   34423 
   34424   assert( pPg->pPager==pPager );
   34425   assert( pPg->flags&PGHDR_DIRTY );
   34426 
   34427   /* The doNotSync flag is set by the sqlite3PagerWrite() function while it
   34428   ** is journalling a set of two or more database pages that are stored
   34429   ** on the same disk sector. Syncing the journal is not allowed while
   34430   ** this is happening as it is important that all members of such a
   34431   ** set of pages are synced to disk together. So, if the page this function
   34432   ** is trying to make clean will require a journal sync and the doNotSync
   34433   ** flag is set, return without doing anything. The pcache layer will
   34434   ** just have to go ahead and allocate a new page buffer instead of
   34435   ** reusing pPg.
   34436   **
   34437   ** Similarly, if the pager has already entered the error state, do not
   34438   ** try to write the contents of pPg to disk.
   34439   */
   34440   if( NEVER(pPager->errCode)
   34441    || (pPager->doNotSync && pPg->flags&PGHDR_NEED_SYNC)
   34442   ){
   34443     return SQLITE_OK;
   34444   }
   34445 
   34446   /* Sync the journal file if required. */
   34447   if( pPg->flags&PGHDR_NEED_SYNC ){
   34448     rc = syncJournal(pPager);
   34449     if( rc==SQLITE_OK && pPager->fullSync &&
   34450       !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
   34451       !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
   34452     ){
   34453       pPager->nRec = 0;
   34454       rc = writeJournalHdr(pPager);
   34455     }
   34456   }
   34457 
   34458   /* If the page number of this page is larger than the current size of
   34459   ** the database image, it may need to be written to the sub-journal.
   34460   ** This is because the call to pager_write_pagelist() below will not
   34461   ** actually write data to the file in this case.
   34462   **
   34463   ** Consider the following sequence of events:
   34464   **
   34465   **   BEGIN;
   34466   **     <journal page X>
   34467   **     <modify page X>
   34468   **     SAVEPOINT sp;
   34469   **       <shrink database file to Y pages>
   34470   **       pagerStress(page X)
   34471   **     ROLLBACK TO sp;
   34472   **
   34473   ** If (X>Y), then when pagerStress is called page X will not be written
   34474   ** out to the database file, but will be dropped from the cache. Then,
   34475   ** following the "ROLLBACK TO sp" statement, reading page X will read
   34476   ** data from the database file. This will be the copy of page X as it
   34477   ** was when the transaction started, not as it was when "SAVEPOINT sp"
   34478   ** was executed.
   34479   **
   34480   ** The solution is to write the current data for page X into the
   34481   ** sub-journal file now (if it is not already there), so that it will
   34482   ** be restored to its current value when the "ROLLBACK TO sp" is
   34483   ** executed.
   34484   */
   34485   if( NEVER(
   34486       rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
   34487   ) ){
   34488     rc = subjournalPage(pPg);
   34489   }
   34490 
   34491   /* Write the contents of the page out to the database file. */
   34492   if( rc==SQLITE_OK ){
   34493     pPg->pDirty = 0;
   34494     rc = pager_write_pagelist(pPg);
   34495   }
   34496 
   34497   /* Mark the page as clean. */
   34498   if( rc==SQLITE_OK ){
   34499     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
   34500     sqlite3PcacheMakeClean(pPg);
   34501   }
   34502 
   34503   return pager_error(pPager, rc);
   34504 }
   34505 
   34506 
   34507 /*
   34508 ** Allocate and initialize a new Pager object and put a pointer to it
   34509 ** in *ppPager. The pager should eventually be freed by passing it
   34510 ** to sqlite3PagerClose().
   34511 **
   34512 ** The zFilename argument is the path to the database file to open.
   34513 ** If zFilename is NULL then a randomly-named temporary file is created
   34514 ** and used as the file to be cached. Temporary files are be deleted
   34515 ** automatically when they are closed. If zFilename is ":memory:" then
   34516 ** all information is held in cache. It is never written to disk.
   34517 ** This can be used to implement an in-memory database.
   34518 **
   34519 ** The nExtra parameter specifies the number of bytes of space allocated
   34520 ** along with each page reference. This space is available to the user
   34521 ** via the sqlite3PagerGetExtra() API.
   34522 **
   34523 ** The flags argument is used to specify properties that affect the
   34524 ** operation of the pager. It should be passed some bitwise combination
   34525 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
   34526 **
   34527 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
   34528 ** of the xOpen() method of the supplied VFS when opening files.
   34529 **
   34530 ** If the pager object is allocated and the specified file opened
   34531 ** successfully, SQLITE_OK is returned and *ppPager set to point to
   34532 ** the new pager object. If an error occurs, *ppPager is set to NULL
   34533 ** and error code returned. This function may return SQLITE_NOMEM
   34534 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
   34535 ** various SQLITE_IO_XXX errors.
   34536 */
   34537 SQLITE_PRIVATE int sqlite3PagerOpen(
   34538   sqlite3_vfs *pVfs,       /* The virtual file system to use */
   34539   Pager **ppPager,         /* OUT: Return the Pager structure here */
   34540   const char *zFilename,   /* Name of the database file to open */
   34541   int nExtra,              /* Extra bytes append to each in-memory page */
   34542   int flags,               /* flags controlling this file */
   34543   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
   34544   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
   34545 ){
   34546   u8 *pPtr;
   34547   Pager *pPager = 0;       /* Pager object to allocate and return */
   34548   int rc = SQLITE_OK;      /* Return code */
   34549   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
   34550   int memDb = 0;           /* True if this is an in-memory file */
   34551   int readOnly = 0;        /* True if this is a read-only file */
   34552   int journalFileSize;     /* Bytes to allocate for each journal fd */
   34553   char *zPathname = 0;     /* Full path to database file */
   34554   int nPathname = 0;       /* Number of bytes in zPathname */
   34555   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
   34556   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
   34557   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
   34558   u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
   34559 
   34560   /* Figure out how much space is required for each journal file-handle
   34561   ** (there are two of them, the main journal and the sub-journal). This
   34562   ** is the maximum space required for an in-memory journal file handle
   34563   ** and a regular journal file-handle. Note that a "regular journal-handle"
   34564   ** may be a wrapper capable of caching the first portion of the journal
   34565   ** file in memory to implement the atomic-write optimization (see
   34566   ** source file journal.c).
   34567   */
   34568   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
   34569     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
   34570   }else{
   34571     journalFileSize = ROUND8(sqlite3MemJournalSize());
   34572   }
   34573 
   34574   /* Set the output variable to NULL in case an error occurs. */
   34575   *ppPager = 0;
   34576 
   34577   /* Compute and store the full pathname in an allocated buffer pointed
   34578   ** to by zPathname, length nPathname. Or, if this is a temporary file,
   34579   ** leave both nPathname and zPathname set to 0.
   34580   */
   34581   if( zFilename && zFilename[0] ){
   34582     nPathname = pVfs->mxPathname+1;
   34583     zPathname = sqlite3Malloc(nPathname*2);
   34584     if( zPathname==0 ){
   34585       return SQLITE_NOMEM;
   34586     }
   34587 #ifndef SQLITE_OMIT_MEMORYDB
   34588     if( strcmp(zFilename,":memory:")==0 ){
   34589       memDb = 1;
   34590       zPathname[0] = 0;
   34591     }else
   34592 #endif
   34593     {
   34594       zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
   34595       rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
   34596     }
   34597 
   34598     nPathname = sqlite3Strlen30(zPathname);
   34599     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
   34600       /* This branch is taken when the journal path required by
   34601       ** the database being opened will be more than pVfs->mxPathname
   34602       ** bytes in length. This means the database cannot be opened,
   34603       ** as it will not be possible to open the journal file or even
   34604       ** check for a hot-journal before reading.
   34605       */
   34606       rc = SQLITE_CANTOPEN_BKPT;
   34607     }
   34608     if( rc!=SQLITE_OK ){
   34609       sqlite3_free(zPathname);
   34610       return rc;
   34611     }
   34612   }
   34613 
   34614   /* Allocate memory for the Pager structure, PCache object, the
   34615   ** three file descriptors, the database file name and the journal
   34616   ** file name. The layout in memory is as follows:
   34617   **
   34618   **     Pager object                    (sizeof(Pager) bytes)
   34619   **     PCache object                   (sqlite3PcacheSize() bytes)
   34620   **     Database file handle            (pVfs->szOsFile bytes)
   34621   **     Sub-journal file handle         (journalFileSize bytes)
   34622   **     Main journal file handle        (journalFileSize bytes)
   34623   **     Database file name              (nPathname+1 bytes)
   34624   **     Journal file name               (nPathname+8+1 bytes)
   34625   */
   34626   pPtr = (u8 *)sqlite3MallocZero(
   34627     ROUND8(sizeof(*pPager)) +      /* Pager structure */
   34628     ROUND8(pcacheSize) +           /* PCache object */
   34629     ROUND8(pVfs->szOsFile) +       /* The main db file */
   34630     journalFileSize * 2 +          /* The two journal files */
   34631     nPathname + 1 +                /* zFilename */
   34632     nPathname + 8 + 1              /* zJournal */
   34633   );
   34634   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
   34635   if( !pPtr ){
   34636     sqlite3_free(zPathname);
   34637     return SQLITE_NOMEM;
   34638   }
   34639   pPager =              (Pager*)(pPtr);
   34640   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
   34641   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
   34642   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
   34643   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
   34644   pPager->zFilename =    (char*)(pPtr += journalFileSize);
   34645   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
   34646 
   34647   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
   34648   if( zPathname ){
   34649     pPager->zJournal =   (char*)(pPtr += nPathname + 1);
   34650     memcpy(pPager->zFilename, zPathname, nPathname);
   34651     memcpy(pPager->zJournal, zPathname, nPathname);
   34652     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
   34653     if( pPager->zFilename[0]==0 ) pPager->zJournal[0] = 0;
   34654     sqlite3_free(zPathname);
   34655   }
   34656   pPager->pVfs = pVfs;
   34657   pPager->vfsFlags = vfsFlags;
   34658 
   34659   /* Open the pager file.
   34660   */
   34661   if( zFilename && zFilename[0] && !memDb ){
   34662     int fout = 0;                    /* VFS flags returned by xOpen() */
   34663     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
   34664     readOnly = (fout&SQLITE_OPEN_READONLY);
   34665 
   34666     /* If the file was successfully opened for read/write access,
   34667     ** choose a default page size in case we have to create the
   34668     ** database file. The default page size is the maximum of:
   34669     **
   34670     **    + SQLITE_DEFAULT_PAGE_SIZE,
   34671     **    + The value returned by sqlite3OsSectorSize()
   34672     **    + The largest page size that can be written atomically.
   34673     */
   34674     if( rc==SQLITE_OK && !readOnly ){
   34675       setSectorSize(pPager);
   34676       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
   34677       if( szPageDflt<pPager->sectorSize ){
   34678         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
   34679           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
   34680         }else{
   34681           szPageDflt = (u16)pPager->sectorSize;
   34682         }
   34683       }
   34684 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   34685       {
   34686         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
   34687         int ii;
   34688         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
   34689         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
   34690         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
   34691         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
   34692           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
   34693             szPageDflt = ii;
   34694           }
   34695         }
   34696       }
   34697 #endif
   34698     }
   34699   }else{
   34700     /* If a temporary file is requested, it is not opened immediately.
   34701     ** In this case we accept the default page size and delay actually
   34702     ** opening the file until the first call to OsWrite().
   34703     **
   34704     ** This branch is also run for an in-memory database. An in-memory
   34705     ** database is the same as a temp-file that is never written out to
   34706     ** disk and uses an in-memory rollback journal.
   34707     */
   34708     tempFile = 1;
   34709     pPager->state = PAGER_EXCLUSIVE;
   34710     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
   34711   }
   34712 
   34713   /* The following call to PagerSetPagesize() serves to set the value of
   34714   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
   34715   */
   34716   if( rc==SQLITE_OK ){
   34717     assert( pPager->memDb==0 );
   34718     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
   34719     testcase( rc!=SQLITE_OK );
   34720   }
   34721 
   34722   /* If an error occurred in either of the blocks above, free the
   34723   ** Pager structure and close the file.
   34724   */
   34725   if( rc!=SQLITE_OK ){
   34726     assert( !pPager->pTmpSpace );
   34727     sqlite3OsClose(pPager->fd);
   34728     sqlite3_free(pPager);
   34729     return rc;
   34730   }
   34731 
   34732   /* Initialize the PCache object. */
   34733   assert( nExtra<1000 );
   34734   nExtra = ROUND8(nExtra);
   34735   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
   34736                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
   34737 
   34738   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
   34739   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
   34740 
   34741   pPager->useJournal = (u8)useJournal;
   34742   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
   34743   /* pPager->stmtOpen = 0; */
   34744   /* pPager->stmtInUse = 0; */
   34745   /* pPager->nRef = 0; */
   34746   pPager->dbSizeValid = (u8)memDb;
   34747   /* pPager->stmtSize = 0; */
   34748   /* pPager->stmtJSize = 0; */
   34749   /* pPager->nPage = 0; */
   34750   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
   34751   /* pPager->state = PAGER_UNLOCK; */
   34752   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
   34753   /* pPager->errMask = 0; */
   34754   pPager->tempFile = (u8)tempFile;
   34755   assert( tempFile==PAGER_LOCKINGMODE_NORMAL
   34756           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
   34757   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
   34758   pPager->exclusiveMode = (u8)tempFile;
   34759   pPager->changeCountDone = pPager->tempFile;
   34760   pPager->memDb = (u8)memDb;
   34761   pPager->readOnly = (u8)readOnly;
   34762   /* pPager->needSync = 0; */
   34763   assert( useJournal || pPager->tempFile );
   34764   pPager->noSync = pPager->tempFile;
   34765   pPager->fullSync = pPager->noSync ?0:1;
   34766   pPager->sync_flags = SQLITE_SYNC_NORMAL;
   34767   /* pPager->pFirst = 0; */
   34768   /* pPager->pFirstSynced = 0; */
   34769   /* pPager->pLast = 0; */
   34770   pPager->nExtra = (u16)nExtra;
   34771   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
   34772   assert( isOpen(pPager->fd) || tempFile );
   34773   setSectorSize(pPager);
   34774   if( !useJournal ){
   34775     pPager->journalMode = PAGER_JOURNALMODE_OFF;
   34776   }else if( memDb ){
   34777     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
   34778   }
   34779   /* pPager->xBusyHandler = 0; */
   34780   /* pPager->pBusyHandlerArg = 0; */
   34781   pPager->xReiniter = xReinit;
   34782   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
   34783   *ppPager = pPager;
   34784   return SQLITE_OK;
   34785 }
   34786 
   34787 
   34788 
   34789 /*
   34790 ** This function is called after transitioning from PAGER_UNLOCK to
   34791 ** PAGER_SHARED state. It tests if there is a hot journal present in
   34792 ** the file-system for the given pager. A hot journal is one that
   34793 ** needs to be played back. According to this function, a hot-journal
   34794 ** file exists if the following criteria are met:
   34795 **
   34796 **   * The journal file exists in the file system, and
   34797 **   * No process holds a RESERVED or greater lock on the database file, and
   34798 **   * The database file itself is greater than 0 bytes in size, and
   34799 **   * The first byte of the journal file exists and is not 0x00.
   34800 **
   34801 ** If the current size of the database file is 0 but a journal file
   34802 ** exists, that is probably an old journal left over from a prior
   34803 ** database with the same name. In this case the journal file is
   34804 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
   34805 ** is returned.
   34806 **
   34807 ** This routine does not check if there is a master journal filename
   34808 ** at the end of the file. If there is, and that master journal file
   34809 ** does not exist, then the journal file is not really hot. In this
   34810 ** case this routine will return a false-positive. The pager_playback()
   34811 ** routine will discover that the journal file is not really hot and
   34812 ** will not roll it back.
   34813 **
   34814 ** If a hot-journal file is found to exist, *pExists is set to 1 and
   34815 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
   34816 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
   34817 ** to determine whether or not a hot-journal file exists, the IO error
   34818 ** code is returned and the value of *pExists is undefined.
   34819 */
   34820 static int hasHotJournal(Pager *pPager, int *pExists){
   34821   sqlite3_vfs * const pVfs = pPager->pVfs;
   34822   int rc;                       /* Return code */
   34823   int exists;                   /* True if a journal file is present */
   34824 
   34825   assert( pPager!=0 );
   34826   assert( pPager->useJournal );
   34827   assert( isOpen(pPager->fd) );
   34828   assert( !isOpen(pPager->jfd) );
   34829   assert( pPager->state <= PAGER_SHARED );
   34830 
   34831   *pExists = 0;
   34832   rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
   34833   if( rc==SQLITE_OK && exists ){
   34834     int locked;                 /* True if some process holds a RESERVED lock */
   34835 
   34836     /* Race condition here:  Another process might have been holding the
   34837     ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
   34838     ** call above, but then delete the journal and drop the lock before
   34839     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
   34840     ** is the case, this routine might think there is a hot journal when
   34841     ** in fact there is none.  This results in a false-positive which will
   34842     ** be dealt with by the playback routine.  Ticket #3883.
   34843     */
   34844     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
   34845     if( rc==SQLITE_OK && !locked ){
   34846       int nPage;
   34847 
   34848       /* Check the size of the database file. If it consists of 0 pages,
   34849       ** then delete the journal file. See the header comment above for
   34850       ** the reasoning here.  Delete the obsolete journal file under
   34851       ** a RESERVED lock to avoid race conditions and to avoid violating
   34852       ** [H33020].
   34853       */
   34854       rc = sqlite3PagerPagecount(pPager, &nPage);
   34855       if( rc==SQLITE_OK ){
   34856         if( nPage==0 ){
   34857           sqlite3BeginBenignMalloc();
   34858           if( sqlite3OsLock(pPager->fd, RESERVED_LOCK)==SQLITE_OK ){
   34859             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
   34860             sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
   34861           }
   34862           sqlite3EndBenignMalloc();
   34863         }else{
   34864           /* The journal file exists and no other connection has a reserved
   34865           ** or greater lock on the database file. Now check that there is
   34866           ** at least one non-zero bytes at the start of the journal file.
   34867           ** If there is, then we consider this journal to be hot. If not,
   34868           ** it can be ignored.
   34869           */
   34870           int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
   34871           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
   34872           if( rc==SQLITE_OK ){
   34873             u8 first = 0;
   34874             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
   34875             if( rc==SQLITE_IOERR_SHORT_READ ){
   34876               rc = SQLITE_OK;
   34877             }
   34878             sqlite3OsClose(pPager->jfd);
   34879             *pExists = (first!=0);
   34880           }else if( rc==SQLITE_CANTOPEN ){
   34881             /* If we cannot open the rollback journal file in order to see if
   34882             ** its has a zero header, that might be due to an I/O error, or
   34883             ** it might be due to the race condition described above and in
   34884             ** ticket #3883.  Either way, assume that the journal is hot.
   34885             ** This might be a false positive.  But if it is, then the
   34886             ** automatic journal playback and recovery mechanism will deal
   34887             ** with it under an EXCLUSIVE lock where we do not need to
   34888             ** worry so much with race conditions.
   34889             */
   34890             *pExists = 1;
   34891             rc = SQLITE_OK;
   34892           }
   34893         }
   34894       }
   34895     }
   34896   }
   34897 
   34898   return rc;
   34899 }
   34900 
   34901 /*
   34902 ** Read the content for page pPg out of the database file and into
   34903 ** pPg->pData. A shared lock or greater must be held on the database
   34904 ** file before this function is called.
   34905 **
   34906 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
   34907 ** the value read from the database file.
   34908 **
   34909 ** If an IO error occurs, then the IO error is returned to the caller.
   34910 ** Otherwise, SQLITE_OK is returned.
   34911 */
   34912 static int readDbPage(PgHdr *pPg){
   34913   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
   34914   Pgno pgno = pPg->pgno;       /* Page number to read */
   34915   int rc;                      /* Return code */
   34916   i64 iOffset;                 /* Byte offset of file to read from */
   34917 
   34918   assert( pPager->state>=PAGER_SHARED && !MEMDB );
   34919   assert( isOpen(pPager->fd) );
   34920 
   34921   if( NEVER(!isOpen(pPager->fd)) ){
   34922     assert( pPager->tempFile );
   34923     memset(pPg->pData, 0, pPager->pageSize);
   34924     return SQLITE_OK;
   34925   }
   34926   iOffset = (pgno-1)*(i64)pPager->pageSize;
   34927   rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
   34928   if( rc==SQLITE_IOERR_SHORT_READ ){
   34929     rc = SQLITE_OK;
   34930   }
   34931   if( pgno==1 ){
   34932     u8 *dbFileVers = &((u8*)pPg->pData)[24];
   34933     memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
   34934   }
   34935   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
   34936 
   34937   PAGER_INCR(sqlite3_pager_readdb_count);
   34938   PAGER_INCR(pPager->nRead);
   34939   IOTRACE(("PGIN %p %d\n", pPager, pgno));
   34940   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
   34941                PAGERID(pPager), pgno, pager_pagehash(pPg)));
   34942 
   34943   return rc;
   34944 }
   34945 
   34946 /*
   34947 ** This function is called to obtain a shared lock on the database file.
   34948 ** It is illegal to call sqlite3PagerAcquire() until after this function
   34949 ** has been successfully called. If a shared-lock is already held when
   34950 ** this function is called, it is a no-op.
   34951 **
   34952 ** The following operations are also performed by this function.
   34953 **
   34954 **   1) If the pager is currently in PAGER_UNLOCK state (no lock held
   34955 **      on the database file), then an attempt is made to obtain a
   34956 **      SHARED lock on the database file. Immediately after obtaining
   34957 **      the SHARED lock, the file-system is checked for a hot-journal,
   34958 **      which is played back if present. Following any hot-journal
   34959 **      rollback, the contents of the cache are validated by checking
   34960 **      the 'change-counter' field of the database file header and
   34961 **      discarded if they are found to be invalid.
   34962 **
   34963 **   2) If the pager is running in exclusive-mode, and there are currently
   34964 **      no outstanding references to any pages, and is in the error state,
   34965 **      then an attempt is made to clear the error state by discarding
   34966 **      the contents of the page cache and rolling back any open journal
   34967 **      file.
   34968 **
   34969 ** If the operation described by (2) above is not attempted, and if the
   34970 ** pager is in an error state other than SQLITE_FULL when this is called,
   34971 ** the error state error code is returned. It is permitted to read the
   34972 ** database when in SQLITE_FULL error state.
   34973 **
   34974 ** Otherwise, if everything is successful, SQLITE_OK is returned. If an
   34975 ** IO error occurs while locking the database, checking for a hot-journal
   34976 ** file or rolling back a journal file, the IO error code is returned.
   34977 */
   34978 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
   34979   int rc = SQLITE_OK;                /* Return code */
   34980   int isErrorReset = 0;              /* True if recovering from error state */
   34981 
   34982   /* This routine is only called from b-tree and only when there are no
   34983   ** outstanding pages */
   34984   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
   34985   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
   34986 
   34987   /* If this database is in an error-state, now is a chance to clear
   34988   ** the error. Discard the contents of the pager-cache and rollback
   34989   ** any hot journal in the file-system.
   34990   */
   34991   if( pPager->errCode ){
   34992     if( isOpen(pPager->jfd) || pPager->zJournal ){
   34993       isErrorReset = 1;
   34994     }
   34995     pPager->errCode = SQLITE_OK;
   34996     pager_reset(pPager);
   34997   }
   34998 
   34999   if( pPager->state==PAGER_UNLOCK || isErrorReset ){
   35000     sqlite3_vfs * const pVfs = pPager->pVfs;
   35001     int isHotJournal = 0;
   35002     assert( !MEMDB );
   35003     assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
   35004     if( pPager->noReadlock ){
   35005       assert( pPager->readOnly );
   35006       pPager->state = PAGER_SHARED;
   35007     }else{
   35008       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
   35009       if( rc!=SQLITE_OK ){
   35010         assert( pPager->state==PAGER_UNLOCK );
   35011         return pager_error(pPager, rc);
   35012       }
   35013     }
   35014     assert( pPager->state>=SHARED_LOCK );
   35015 
   35016     /* If a journal file exists, and there is no RESERVED lock on the
   35017     ** database file, then it either needs to be played back or deleted.
   35018     */
   35019     if( !isErrorReset ){
   35020       assert( pPager->state <= PAGER_SHARED );
   35021       rc = hasHotJournal(pPager, &isHotJournal);
   35022       if( rc!=SQLITE_OK ){
   35023         goto failed;
   35024       }
   35025     }
   35026     if( isErrorReset || isHotJournal ){
   35027       /* Get an EXCLUSIVE lock on the database file. At this point it is
   35028       ** important that a RESERVED lock is not obtained on the way to the
   35029       ** EXCLUSIVE lock. If it were, another process might open the
   35030       ** database file, detect the RESERVED lock, and conclude that the
   35031       ** database is safe to read while this process is still rolling the
   35032       ** hot-journal back.
   35033       **
   35034       ** Because the intermediate RESERVED lock is not requested, any
   35035       ** other process attempting to access the database file will get to
   35036       ** this point in the code and fail to obtain its own EXCLUSIVE lock
   35037       ** on the database file.
   35038       */
   35039       if( pPager->state<EXCLUSIVE_LOCK ){
   35040         rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
   35041         if( rc!=SQLITE_OK ){
   35042           rc = pager_error(pPager, rc);
   35043           goto failed;
   35044         }
   35045         pPager->state = PAGER_EXCLUSIVE;
   35046       }
   35047 
   35048       /* Open the journal for read/write access. This is because in
   35049       ** exclusive-access mode the file descriptor will be kept open and
   35050       ** possibly used for a transaction later on. On some systems, the
   35051       ** OsTruncate() call used in exclusive-access mode also requires
   35052       ** a read/write file handle.
   35053       */
   35054       if( !isOpen(pPager->jfd) ){
   35055         int res;
   35056         rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
   35057         if( rc==SQLITE_OK ){
   35058           if( res ){
   35059             int fout = 0;
   35060             int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
   35061             assert( !pPager->tempFile );
   35062             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
   35063             assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
   35064             if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
   35065               rc = SQLITE_CANTOPEN_BKPT;
   35066               sqlite3OsClose(pPager->jfd);
   35067             }
   35068           }else{
   35069             /* If the journal does not exist, it usually means that some
   35070             ** other connection managed to get in and roll it back before
   35071             ** this connection obtained the exclusive lock above. Or, it
   35072             ** may mean that the pager was in the error-state when this
   35073             ** function was called and the journal file does not exist.  */
   35074             rc = pager_end_transaction(pPager, 0);
   35075           }
   35076         }
   35077       }
   35078       if( rc!=SQLITE_OK ){
   35079         goto failed;
   35080       }
   35081 
   35082       /* TODO: Why are these cleared here? Is it necessary? */
   35083       pPager->journalStarted = 0;
   35084       pPager->journalOff = 0;
   35085       pPager->setMaster = 0;
   35086       pPager->journalHdr = 0;
   35087 
   35088       /* Playback and delete the journal.  Drop the database write
   35089       ** lock and reacquire the read lock. Purge the cache before
   35090       ** playing back the hot-journal so that we don't end up with
   35091       ** an inconsistent cache.
   35092       */
   35093       if( isOpen(pPager->jfd) ){
   35094         rc = pager_playback(pPager, 1);
   35095         if( rc!=SQLITE_OK ){
   35096           rc = pager_error(pPager, rc);
   35097           goto failed;
   35098         }
   35099       }
   35100       assert( (pPager->state==PAGER_SHARED)
   35101            || (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
   35102       );
   35103     }
   35104 
   35105     if( pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0 ){
   35106       /* The shared-lock has just been acquired on the database file
   35107       ** and there are already pages in the cache (from a previous
   35108       ** read or write transaction).  Check to see if the database
   35109       ** has been modified.  If the database has changed, flush the
   35110       ** cache.
   35111       **
   35112       ** Database changes is detected by looking at 15 bytes beginning
   35113       ** at offset 24 into the file.  The first 4 of these 16 bytes are
   35114       ** a 32-bit counter that is incremented with each change.  The
   35115       ** other bytes change randomly with each file change when
   35116       ** a codec is in use.
   35117       **
   35118       ** There is a vanishingly small chance that a change will not be
   35119       ** detected.  The chance of an undetected change is so small that
   35120       ** it can be neglected.
   35121       */
   35122       char dbFileVers[sizeof(pPager->dbFileVers)];
   35123       sqlite3PagerPagecount(pPager, 0);
   35124 
   35125       if( pPager->errCode ){
   35126         rc = pPager->errCode;
   35127         goto failed;
   35128       }
   35129 
   35130       assert( pPager->dbSizeValid );
   35131       if( pPager->dbSize>0 ){
   35132         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
   35133         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
   35134         if( rc!=SQLITE_OK ){
   35135           goto failed;
   35136         }
   35137       }else{
   35138         memset(dbFileVers, 0, sizeof(dbFileVers));
   35139       }
   35140 
   35141       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
   35142         pager_reset(pPager);
   35143       }
   35144     }
   35145     assert( pPager->exclusiveMode || pPager->state==PAGER_SHARED );
   35146   }
   35147 
   35148  failed:
   35149   if( rc!=SQLITE_OK ){
   35150     /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
   35151     pager_unlock(pPager);
   35152   }
   35153   return rc;
   35154 }
   35155 
   35156 /*
   35157 ** If the reference count has reached zero, rollback any active
   35158 ** transaction and unlock the pager.
   35159 **
   35160 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
   35161 ** the rollback journal, the unlock is not performed and there is
   35162 ** nothing to rollback, so this routine is a no-op.
   35163 */
   35164 static void pagerUnlockIfUnused(Pager *pPager){
   35165   if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
   35166    && (!pPager->exclusiveMode || pPager->journalOff>0)
   35167   ){
   35168     pagerUnlockAndRollback(pPager);
   35169   }
   35170 }
   35171 
   35172 /*
   35173 ** Acquire a reference to page number pgno in pager pPager (a page
   35174 ** reference has type DbPage*). If the requested reference is
   35175 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
   35176 **
   35177 ** If the requested page is already in the cache, it is returned.
   35178 ** Otherwise, a new page object is allocated and populated with data
   35179 ** read from the database file. In some cases, the pcache module may
   35180 ** choose not to allocate a new page object and may reuse an existing
   35181 ** object with no outstanding references.
   35182 **
   35183 ** The extra data appended to a page is always initialized to zeros the
   35184 ** first time a page is loaded into memory. If the page requested is
   35185 ** already in the cache when this function is called, then the extra
   35186 ** data is left as it was when the page object was last used.
   35187 **
   35188 ** If the database image is smaller than the requested page or if a
   35189 ** non-zero value is passed as the noContent parameter and the
   35190 ** requested page is not already stored in the cache, then no
   35191 ** actual disk read occurs. In this case the memory image of the
   35192 ** page is initialized to all zeros.
   35193 **
   35194 ** If noContent is true, it means that we do not care about the contents
   35195 ** of the page. This occurs in two seperate scenarios:
   35196 **
   35197 **   a) When reading a free-list leaf page from the database, and
   35198 **
   35199 **   b) When a savepoint is being rolled back and we need to load
   35200 **      a new page into the cache to populate with the data read
   35201 **      from the savepoint journal.
   35202 **
   35203 ** If noContent is true, then the data returned is zeroed instead of
   35204 ** being read from the database. Additionally, the bits corresponding
   35205 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
   35206 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
   35207 ** savepoints are set. This means if the page is made writable at any
   35208 ** point in the future, using a call to sqlite3PagerWrite(), its contents
   35209 ** will not be journaled. This saves IO.
   35210 **
   35211 ** The acquisition might fail for several reasons.  In all cases,
   35212 ** an appropriate error code is returned and *ppPage is set to NULL.
   35213 **
   35214 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
   35215 ** to find a page in the in-memory cache first.  If the page is not already
   35216 ** in memory, this routine goes to disk to read it in whereas Lookup()
   35217 ** just returns 0.  This routine acquires a read-lock the first time it
   35218 ** has to go to disk, and could also playback an old journal if necessary.
   35219 ** Since Lookup() never goes to disk, it never has to deal with locks
   35220 ** or journal files.
   35221 */
   35222 SQLITE_PRIVATE int sqlite3PagerAcquire(
   35223   Pager *pPager,      /* The pager open on the database file */
   35224   Pgno pgno,          /* Page number to fetch */
   35225   DbPage **ppPage,    /* Write a pointer to the page here */
   35226   int noContent       /* Do not bother reading content from disk if true */
   35227 ){
   35228   int rc;
   35229   PgHdr *pPg;
   35230 
   35231   assert( assert_pager_state(pPager) );
   35232   assert( pPager->state>PAGER_UNLOCK );
   35233 
   35234   if( pgno==0 ){
   35235     return SQLITE_CORRUPT_BKPT;
   35236   }
   35237 
   35238   /* If the pager is in the error state, return an error immediately.
   35239   ** Otherwise, request the page from the PCache layer. */
   35240   if( pPager->errCode!=SQLITE_OK && pPager->errCode!=SQLITE_FULL ){
   35241     rc = pPager->errCode;
   35242   }else{
   35243     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
   35244   }
   35245 
   35246   if( rc!=SQLITE_OK ){
   35247     /* Either the call to sqlite3PcacheFetch() returned an error or the
   35248     ** pager was already in the error-state when this function was called.
   35249     ** Set pPg to 0 and jump to the exception handler.  */
   35250     pPg = 0;
   35251     goto pager_acquire_err;
   35252   }
   35253   assert( (*ppPage)->pgno==pgno );
   35254   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
   35255 
   35256   if( (*ppPage)->pPager ){
   35257     /* In this case the pcache already contains an initialized copy of
   35258     ** the page. Return without further ado.  */
   35259     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
   35260     PAGER_INCR(pPager->nHit);
   35261     return SQLITE_OK;
   35262 
   35263   }else{
   35264     /* The pager cache has created a new page. Its content needs to
   35265     ** be initialized.  */
   35266     int nMax;
   35267 
   35268     PAGER_INCR(pPager->nMiss);
   35269     pPg = *ppPage;
   35270     pPg->pPager = pPager;
   35271 
   35272     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
   35273     ** number greater than this, or the unused locking-page, is requested. */
   35274     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
   35275       rc = SQLITE_CORRUPT_BKPT;
   35276       goto pager_acquire_err;
   35277     }
   35278 
   35279     rc = sqlite3PagerPagecount(pPager, &nMax);
   35280     if( rc!=SQLITE_OK ){
   35281       goto pager_acquire_err;
   35282     }
   35283 
   35284     if( MEMDB || nMax<(int)pgno || noContent || !isOpen(pPager->fd) ){
   35285       if( pgno>pPager->mxPgno ){
   35286 	rc = SQLITE_FULL;
   35287 	goto pager_acquire_err;
   35288       }
   35289       if( noContent ){
   35290         /* Failure to set the bits in the InJournal bit-vectors is benign.
   35291         ** It merely means that we might do some extra work to journal a
   35292         ** page that does not need to be journaled.  Nevertheless, be sure
   35293         ** to test the case where a malloc error occurs while trying to set
   35294         ** a bit in a bit vector.
   35295         */
   35296         sqlite3BeginBenignMalloc();
   35297         if( pgno<=pPager->dbOrigSize ){
   35298           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
   35299           testcase( rc==SQLITE_NOMEM );
   35300         }
   35301         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
   35302         testcase( rc==SQLITE_NOMEM );
   35303         sqlite3EndBenignMalloc();
   35304       }
   35305       memset(pPg->pData, 0, pPager->pageSize);
   35306       IOTRACE(("ZERO %p %d\n", pPager, pgno));
   35307     }else{
   35308       assert( pPg->pPager==pPager );
   35309       rc = readDbPage(pPg);
   35310       if( rc!=SQLITE_OK ){
   35311         goto pager_acquire_err;
   35312       }
   35313     }
   35314 #ifdef SQLITE_CHECK_PAGES
   35315     pPg->pageHash = pager_pagehash(pPg);
   35316 #endif
   35317   }
   35318 
   35319   return SQLITE_OK;
   35320 
   35321 pager_acquire_err:
   35322   assert( rc!=SQLITE_OK );
   35323   if( pPg ){
   35324     sqlite3PcacheDrop(pPg);
   35325   }
   35326   pagerUnlockIfUnused(pPager);
   35327 
   35328   *ppPage = 0;
   35329   return rc;
   35330 }
   35331 
   35332 /*
   35333 ** Acquire a page if it is already in the in-memory cache.  Do
   35334 ** not read the page from disk.  Return a pointer to the page,
   35335 ** or 0 if the page is not in cache. Also, return 0 if the
   35336 ** pager is in PAGER_UNLOCK state when this function is called,
   35337 ** or if the pager is in an error state other than SQLITE_FULL.
   35338 **
   35339 ** See also sqlite3PagerGet().  The difference between this routine
   35340 ** and sqlite3PagerGet() is that _get() will go to the disk and read
   35341 ** in the page if the page is not already in cache.  This routine
   35342 ** returns NULL if the page is not in cache or if a disk I/O error
   35343 ** has ever happened.
   35344 */
   35345 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
   35346   PgHdr *pPg = 0;
   35347   assert( pPager!=0 );
   35348   assert( pgno!=0 );
   35349   assert( pPager->pPCache!=0 );
   35350   assert( pPager->state > PAGER_UNLOCK );
   35351   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
   35352   return pPg;
   35353 }
   35354 
   35355 /*
   35356 ** Release a page reference.
   35357 **
   35358 ** If the number of references to the page drop to zero, then the
   35359 ** page is added to the LRU list.  When all references to all pages
   35360 ** are released, a rollback occurs and the lock on the database is
   35361 ** removed.
   35362 */
   35363 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
   35364   if( pPg ){
   35365     Pager *pPager = pPg->pPager;
   35366     sqlite3PcacheRelease(pPg);
   35367     pagerUnlockIfUnused(pPager);
   35368   }
   35369 }
   35370 
   35371 /*
   35372 ** If the main journal file has already been opened, ensure that the
   35373 ** sub-journal file is open too. If the main journal is not open,
   35374 ** this function is a no-op.
   35375 **
   35376 ** SQLITE_OK is returned if everything goes according to plan.
   35377 ** An SQLITE_IOERR_XXX error code is returned if a call to
   35378 ** sqlite3OsOpen() fails.
   35379 */
   35380 static int openSubJournal(Pager *pPager){
   35381   int rc = SQLITE_OK;
   35382   if( isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ){
   35383     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
   35384       sqlite3MemJournalOpen(pPager->sjfd);
   35385     }else{
   35386       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
   35387     }
   35388   }
   35389   return rc;
   35390 }
   35391 
   35392 /*
   35393 ** This function is called at the start of every write transaction.
   35394 ** There must already be a RESERVED or EXCLUSIVE lock on the database
   35395 ** file when this routine is called.
   35396 **
   35397 ** Open the journal file for pager pPager and write a journal header
   35398 ** to the start of it. If there are active savepoints, open the sub-journal
   35399 ** as well. This function is only used when the journal file is being
   35400 ** opened to write a rollback log for a transaction. It is not used
   35401 ** when opening a hot journal file to roll it back.
   35402 **
   35403 ** If the journal file is already open (as it may be in exclusive mode),
   35404 ** then this function just writes a journal header to the start of the
   35405 ** already open file.
   35406 **
   35407 ** Whether or not the journal file is opened by this function, the
   35408 ** Pager.pInJournal bitvec structure is allocated.
   35409 **
   35410 ** Return SQLITE_OK if everything is successful. Otherwise, return
   35411 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
   35412 ** an IO error code if opening or writing the journal file fails.
   35413 */
   35414 static int pager_open_journal(Pager *pPager){
   35415   int rc = SQLITE_OK;                        /* Return code */
   35416   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
   35417 
   35418   assert( pPager->state>=PAGER_RESERVED );
   35419   assert( pPager->useJournal );
   35420   assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF );
   35421   assert( pPager->pInJournal==0 );
   35422 
   35423   /* If already in the error state, this function is a no-op.  But on
   35424   ** the other hand, this routine is never called if we are already in
   35425   ** an error state. */
   35426   if( NEVER(pPager->errCode) ) return pPager->errCode;
   35427 
   35428   /* TODO: Is it really possible to get here with dbSizeValid==0? If not,
   35429   ** the call to PagerPagecount() can be removed.
   35430   */
   35431   testcase( pPager->dbSizeValid==0 );
   35432   sqlite3PagerPagecount(pPager, 0);
   35433 
   35434   pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
   35435   if( pPager->pInJournal==0 ){
   35436     return SQLITE_NOMEM;
   35437   }
   35438 
   35439   /* Open the journal file if it is not already open. */
   35440   if( !isOpen(pPager->jfd) ){
   35441     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
   35442       sqlite3MemJournalOpen(pPager->jfd);
   35443     }else{
   35444       const int flags =                   /* VFS flags to open journal file */
   35445         SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
   35446         (pPager->tempFile ?
   35447           (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
   35448           (SQLITE_OPEN_MAIN_JOURNAL)
   35449         );
   35450 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   35451       rc = sqlite3JournalOpen(
   35452           pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
   35453       );
   35454 #else
   35455       rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
   35456 #endif
   35457     }
   35458     assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
   35459   }
   35460 
   35461 
   35462   /* Write the first journal header to the journal file and open
   35463   ** the sub-journal if necessary.
   35464   */
   35465   if( rc==SQLITE_OK ){
   35466     /* TODO: Check if all of these are really required. */
   35467     pPager->dbOrigSize = pPager->dbSize;
   35468     pPager->journalStarted = 0;
   35469     pPager->needSync = 0;
   35470     pPager->nRec = 0;
   35471     pPager->journalOff = 0;
   35472     pPager->setMaster = 0;
   35473     pPager->journalHdr = 0;
   35474     rc = writeJournalHdr(pPager);
   35475   }
   35476   if( rc==SQLITE_OK && pPager->nSavepoint ){
   35477     rc = openSubJournal(pPager);
   35478   }
   35479 
   35480   if( rc!=SQLITE_OK ){
   35481     sqlite3BitvecDestroy(pPager->pInJournal);
   35482     pPager->pInJournal = 0;
   35483   }
   35484   return rc;
   35485 }
   35486 
   35487 /*
   35488 ** Begin a write-transaction on the specified pager object. If a
   35489 ** write-transaction has already been opened, this function is a no-op.
   35490 **
   35491 ** If the exFlag argument is false, then acquire at least a RESERVED
   35492 ** lock on the database file. If exFlag is true, then acquire at least
   35493 ** an EXCLUSIVE lock. If such a lock is already held, no locking
   35494 ** functions need be called.
   35495 **
   35496 ** If this is not a temporary or in-memory file and, the journal file is
   35497 ** opened if it has not been already. For a temporary file, the opening
   35498 ** of the journal file is deferred until there is an actual need to
   35499 ** write to the journal. TODO: Why handle temporary files differently?
   35500 **
   35501 ** If the journal file is opened (or if it is already open), then a
   35502 ** journal-header is written to the start of it.
   35503 **
   35504 ** If the subjInMemory argument is non-zero, then any sub-journal opened
   35505 ** within this transaction will be opened as an in-memory file. This
   35506 ** has no effect if the sub-journal is already opened (as it may be when
   35507 ** running in exclusive mode) or if the transaction does not require a
   35508 ** sub-journal. If the subjInMemory argument is zero, then any required
   35509 ** sub-journal is implemented in-memory if pPager is an in-memory database,
   35510 ** or using a temporary file otherwise.
   35511 */
   35512 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
   35513   int rc = SQLITE_OK;
   35514   assert( pPager->state!=PAGER_UNLOCK );
   35515   pPager->subjInMemory = (u8)subjInMemory;
   35516   if( pPager->state==PAGER_SHARED ){
   35517     assert( pPager->pInJournal==0 );
   35518     assert( !MEMDB && !pPager->tempFile );
   35519 
   35520     /* Obtain a RESERVED lock on the database file. If the exFlag parameter
   35521     ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
   35522     ** busy-handler callback can be used when upgrading to the EXCLUSIVE
   35523     ** lock, but not when obtaining the RESERVED lock.
   35524     */
   35525     rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
   35526     if( rc==SQLITE_OK ){
   35527       pPager->state = PAGER_RESERVED;
   35528       if( exFlag ){
   35529         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
   35530       }
   35531     }
   35532 
   35533     /* If the required locks were successfully obtained, open the journal
   35534     ** file and write the first journal-header to it.
   35535     */
   35536     if( rc==SQLITE_OK && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
   35537       rc = pager_open_journal(pPager);
   35538     }
   35539   }else if( isOpen(pPager->jfd) && pPager->journalOff==0 ){
   35540     /* This happens when the pager was in exclusive-access mode the last
   35541     ** time a (read or write) transaction was successfully concluded
   35542     ** by this connection. Instead of deleting the journal file it was
   35543     ** kept open and either was truncated to 0 bytes or its header was
   35544     ** overwritten with zeros.
   35545     */
   35546     assert( pPager->nRec==0 );
   35547     assert( pPager->dbOrigSize==0 );
   35548     assert( pPager->pInJournal==0 );
   35549     rc = pager_open_journal(pPager);
   35550   }
   35551 
   35552   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
   35553   assert( !isOpen(pPager->jfd) || pPager->journalOff>0 || rc!=SQLITE_OK );
   35554   if( rc!=SQLITE_OK ){
   35555     assert( !pPager->dbModified );
   35556     /* Ignore any IO error that occurs within pager_end_transaction(). The
   35557     ** purpose of this call is to reset the internal state of the pager
   35558     ** sub-system. It doesn't matter if the journal-file is not properly
   35559     ** finalized at this point (since it is not a valid journal file anyway).
   35560     */
   35561     pager_end_transaction(pPager, 0);
   35562   }
   35563   return rc;
   35564 }
   35565 
   35566 /*
   35567 ** Mark a single data page as writeable. The page is written into the
   35568 ** main journal or sub-journal as required. If the page is written into
   35569 ** one of the journals, the corresponding bit is set in the
   35570 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
   35571 ** of any open savepoints as appropriate.
   35572 */
   35573 static int pager_write(PgHdr *pPg){
   35574   void *pData = pPg->pData;
   35575   Pager *pPager = pPg->pPager;
   35576   int rc = SQLITE_OK;
   35577 
   35578   /* This routine is not called unless a transaction has already been
   35579   ** started.
   35580   */
   35581   assert( pPager->state>=PAGER_RESERVED );
   35582 
   35583   /* If an error has been previously detected, we should not be
   35584   ** calling this routine.  Repeat the error for robustness.
   35585   */
   35586   if( NEVER(pPager->errCode) )  return pPager->errCode;
   35587 
   35588   /* Higher-level routines never call this function if database is not
   35589   ** writable.  But check anyway, just for robustness. */
   35590   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
   35591 
   35592   assert( !pPager->setMaster );
   35593 
   35594   CHECK_PAGE(pPg);
   35595 
   35596   /* Mark the page as dirty.  If the page has already been written
   35597   ** to the journal then we can return right away.
   35598   */
   35599   sqlite3PcacheMakeDirty(pPg);
   35600   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
   35601     pPager->dbModified = 1;
   35602   }else{
   35603 
   35604     /* If we get this far, it means that the page needs to be
   35605     ** written to the transaction journal or the ckeckpoint journal
   35606     ** or both.
   35607     **
   35608     ** Higher level routines should have already started a transaction,
   35609     ** which means they have acquired the necessary locks and opened
   35610     ** a rollback journal.  Double-check to makes sure this is the case.
   35611     */
   35612     rc = sqlite3PagerBegin(pPager, 0, pPager->subjInMemory);
   35613     if( NEVER(rc!=SQLITE_OK) ){
   35614       return rc;
   35615     }
   35616     if( !isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
   35617       assert( pPager->useJournal );
   35618       rc = pager_open_journal(pPager);
   35619       if( rc!=SQLITE_OK ) return rc;
   35620     }
   35621     pPager->dbModified = 1;
   35622 
   35623     /* The transaction journal now exists and we have a RESERVED or an
   35624     ** EXCLUSIVE lock on the main database file.  Write the current page to
   35625     ** the transaction journal if it is not there already.
   35626     */
   35627     if( !pageInJournal(pPg) && isOpen(pPager->jfd) ){
   35628       if( pPg->pgno<=pPager->dbOrigSize ){
   35629         u32 cksum;
   35630         char *pData2;
   35631 
   35632         /* We should never write to the journal file the page that
   35633         ** contains the database locks.  The following assert verifies
   35634         ** that we do not. */
   35635         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
   35636         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
   35637         cksum = pager_cksum(pPager, (u8*)pData2);
   35638         rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
   35639         if( rc==SQLITE_OK ){
   35640           rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
   35641                               pPager->journalOff + 4);
   35642           pPager->journalOff += pPager->pageSize+4;
   35643         }
   35644         if( rc==SQLITE_OK ){
   35645           rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
   35646           pPager->journalOff += 4;
   35647         }
   35648         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
   35649                  pPager->journalOff, pPager->pageSize));
   35650         PAGER_INCR(sqlite3_pager_writej_count);
   35651         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
   35652              PAGERID(pPager), pPg->pgno,
   35653              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
   35654 
   35655         /* Even if an IO or diskfull error occurred while journalling the
   35656         ** page in the block above, set the need-sync flag for the page.
   35657         ** Otherwise, when the transaction is rolled back, the logic in
   35658         ** playback_one_page() will think that the page needs to be restored
   35659         ** in the database file. And if an IO error occurs while doing so,
   35660         ** then corruption may follow.
   35661         */
   35662         if( !pPager->noSync ){
   35663           pPg->flags |= PGHDR_NEED_SYNC;
   35664           pPager->needSync = 1;
   35665         }
   35666 
   35667         /* An error has occurred writing to the journal file. The
   35668         ** transaction will be rolled back by the layer above.
   35669         */
   35670         if( rc!=SQLITE_OK ){
   35671           return rc;
   35672         }
   35673 
   35674         pPager->nRec++;
   35675         assert( pPager->pInJournal!=0 );
   35676         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
   35677         testcase( rc==SQLITE_NOMEM );
   35678         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   35679         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
   35680         if( rc!=SQLITE_OK ){
   35681           assert( rc==SQLITE_NOMEM );
   35682           return rc;
   35683         }
   35684       }else{
   35685         if( !pPager->journalStarted && !pPager->noSync ){
   35686           pPg->flags |= PGHDR_NEED_SYNC;
   35687           pPager->needSync = 1;
   35688         }
   35689         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
   35690                 PAGERID(pPager), pPg->pgno,
   35691                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
   35692       }
   35693     }
   35694 
   35695     /* If the statement journal is open and the page is not in it,
   35696     ** then write the current page to the statement journal.  Note that
   35697     ** the statement journal format differs from the standard journal format
   35698     ** in that it omits the checksums and the header.
   35699     */
   35700     if( subjRequiresPage(pPg) ){
   35701       rc = subjournalPage(pPg);
   35702     }
   35703   }
   35704 
   35705   /* Update the database size and return.
   35706   */
   35707   assert( pPager->state>=PAGER_SHARED );
   35708   if( pPager->dbSize<pPg->pgno ){
   35709     pPager->dbSize = pPg->pgno;
   35710   }
   35711   return rc;
   35712 }
   35713 
   35714 /*
   35715 ** Mark a data page as writeable. This routine must be called before
   35716 ** making changes to a page. The caller must check the return value
   35717 ** of this function and be careful not to change any page data unless
   35718 ** this routine returns SQLITE_OK.
   35719 **
   35720 ** The difference between this function and pager_write() is that this
   35721 ** function also deals with the special case where 2 or more pages
   35722 ** fit on a single disk sector. In this case all co-resident pages
   35723 ** must have been written to the journal file before returning.
   35724 **
   35725 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
   35726 ** as appropriate. Otherwise, SQLITE_OK.
   35727 */
   35728 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
   35729   int rc = SQLITE_OK;
   35730 
   35731   PgHdr *pPg = pDbPage;
   35732   Pager *pPager = pPg->pPager;
   35733   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
   35734 
   35735   if( nPagePerSector>1 ){
   35736     Pgno nPageCount;          /* Total number of pages in database file */
   35737     Pgno pg1;                 /* First page of the sector pPg is located on. */
   35738     int nPage;                /* Number of pages starting at pg1 to journal */
   35739     int ii;                   /* Loop counter */
   35740     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
   35741 
   35742     /* Set the doNotSync flag to 1. This is because we cannot allow a journal
   35743     ** header to be written between the pages journaled by this function.
   35744     */
   35745     assert( !MEMDB );
   35746     assert( pPager->doNotSync==0 );
   35747     pPager->doNotSync = 1;
   35748 
   35749     /* This trick assumes that both the page-size and sector-size are
   35750     ** an integer power of 2. It sets variable pg1 to the identifier
   35751     ** of the first page of the sector pPg is located on.
   35752     */
   35753     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
   35754 
   35755     sqlite3PagerPagecount(pPager, (int *)&nPageCount);
   35756     if( pPg->pgno>nPageCount ){
   35757       nPage = (pPg->pgno - pg1)+1;
   35758     }else if( (pg1+nPagePerSector-1)>nPageCount ){
   35759       nPage = nPageCount+1-pg1;
   35760     }else{
   35761       nPage = nPagePerSector;
   35762     }
   35763     assert(nPage>0);
   35764     assert(pg1<=pPg->pgno);
   35765     assert((pg1+nPage)>pPg->pgno);
   35766 
   35767     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
   35768       Pgno pg = pg1+ii;
   35769       PgHdr *pPage;
   35770       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
   35771         if( pg!=PAGER_MJ_PGNO(pPager) ){
   35772           rc = sqlite3PagerGet(pPager, pg, &pPage);
   35773           if( rc==SQLITE_OK ){
   35774             rc = pager_write(pPage);
   35775             if( pPage->flags&PGHDR_NEED_SYNC ){
   35776               needSync = 1;
   35777               assert(pPager->needSync);
   35778             }
   35779             sqlite3PagerUnref(pPage);
   35780           }
   35781         }
   35782       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
   35783         if( pPage->flags&PGHDR_NEED_SYNC ){
   35784           needSync = 1;
   35785         }
   35786         sqlite3PagerUnref(pPage);
   35787       }
   35788     }
   35789 
   35790     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
   35791     ** starting at pg1, then it needs to be set for all of them. Because
   35792     ** writing to any of these nPage pages may damage the others, the
   35793     ** journal file must contain sync()ed copies of all of them
   35794     ** before any of them can be written out to the database file.
   35795     */
   35796     if( rc==SQLITE_OK && needSync ){
   35797       assert( !MEMDB && pPager->noSync==0 );
   35798       for(ii=0; ii<nPage; ii++){
   35799         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
   35800         if( pPage ){
   35801           pPage->flags |= PGHDR_NEED_SYNC;
   35802           sqlite3PagerUnref(pPage);
   35803         }
   35804       }
   35805       assert(pPager->needSync);
   35806     }
   35807 
   35808     assert( pPager->doNotSync==1 );
   35809     pPager->doNotSync = 0;
   35810   }else{
   35811     rc = pager_write(pDbPage);
   35812   }
   35813   return rc;
   35814 }
   35815 
   35816 /*
   35817 ** Return TRUE if the page given in the argument was previously passed
   35818 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
   35819 ** to change the content of the page.
   35820 */
   35821 #ifndef NDEBUG
   35822 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
   35823   return pPg->flags&PGHDR_DIRTY;
   35824 }
   35825 #endif
   35826 
   35827 #ifndef SQLITE_SECURE_DELETE
   35828 /*
   35829 ** A call to this routine tells the pager that it is not necessary to
   35830 ** write the information on page pPg back to the disk, even though
   35831 ** that page might be marked as dirty.  This happens, for example, when
   35832 ** the page has been added as a leaf of the freelist and so its
   35833 ** content no longer matters.
   35834 **
   35835 ** The overlying software layer calls this routine when all of the data
   35836 ** on the given page is unused. The pager marks the page as clean so
   35837 ** that it does not get written to disk.
   35838 **
   35839 ** Tests show that this optimization can quadruple the speed of large
   35840 ** DELETE operations.
   35841 */
   35842 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
   35843   Pager *pPager = pPg->pPager;
   35844   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
   35845     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
   35846     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
   35847     pPg->flags |= PGHDR_DONT_WRITE;
   35848 #ifdef SQLITE_CHECK_PAGES
   35849     pPg->pageHash = pager_pagehash(pPg);
   35850 #endif
   35851   }
   35852 }
   35853 #endif /* !defined(SQLITE_SECURE_DELETE) */
   35854 
   35855 /*
   35856 ** This routine is called to increment the value of the database file
   35857 ** change-counter, stored as a 4-byte big-endian integer starting at
   35858 ** byte offset 24 of the pager file.
   35859 **
   35860 ** If the isDirectMode flag is zero, then this is done by calling
   35861 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
   35862 ** page data. In this case the file will be updated when the current
   35863 ** transaction is committed.
   35864 **
   35865 ** The isDirectMode flag may only be non-zero if the library was compiled
   35866 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
   35867 ** if isDirect is non-zero, then the database file is updated directly
   35868 ** by writing an updated version of page 1 using a call to the
   35869 ** sqlite3OsWrite() function.
   35870 */
   35871 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
   35872   int rc = SQLITE_OK;
   35873 
   35874   /* Declare and initialize constant integer 'isDirect'. If the
   35875   ** atomic-write optimization is enabled in this build, then isDirect
   35876   ** is initialized to the value passed as the isDirectMode parameter
   35877   ** to this function. Otherwise, it is always set to zero.
   35878   **
   35879   ** The idea is that if the atomic-write optimization is not
   35880   ** enabled at compile time, the compiler can omit the tests of
   35881   ** 'isDirect' below, as well as the block enclosed in the
   35882   ** "if( isDirect )" condition.
   35883   */
   35884 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
   35885 # define DIRECT_MODE 0
   35886   assert( isDirectMode==0 );
   35887   UNUSED_PARAMETER(isDirectMode);
   35888 #else
   35889 # define DIRECT_MODE isDirectMode
   35890 #endif
   35891 
   35892   assert( pPager->state>=PAGER_RESERVED );
   35893   if( !pPager->changeCountDone && pPager->dbSize>0 ){
   35894     PgHdr *pPgHdr;                /* Reference to page 1 */
   35895     u32 change_counter;           /* Initial value of change-counter field */
   35896 
   35897     assert( !pPager->tempFile && isOpen(pPager->fd) );
   35898 
   35899     /* Open page 1 of the file for writing. */
   35900     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
   35901     assert( pPgHdr==0 || rc==SQLITE_OK );
   35902 
   35903     /* If page one was fetched successfully, and this function is not
   35904     ** operating in direct-mode, make page 1 writable.  When not in
   35905     ** direct mode, page 1 is always held in cache and hence the PagerGet()
   35906     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
   35907     */
   35908     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
   35909       rc = sqlite3PagerWrite(pPgHdr);
   35910     }
   35911 
   35912     if( rc==SQLITE_OK ){
   35913       /* Increment the value just read and write it back to byte 24. */
   35914       change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
   35915       change_counter++;
   35916       put32bits(((char*)pPgHdr->pData)+24, change_counter);
   35917 
   35918       /* If running in direct mode, write the contents of page 1 to the file. */
   35919       if( DIRECT_MODE ){
   35920         const void *zBuf = pPgHdr->pData;
   35921         assert( pPager->dbFileSize>0 );
   35922         rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
   35923         if( rc==SQLITE_OK ){
   35924           pPager->changeCountDone = 1;
   35925         }
   35926       }else{
   35927         pPager->changeCountDone = 1;
   35928       }
   35929     }
   35930 
   35931     /* Release the page reference. */
   35932     sqlite3PagerUnref(pPgHdr);
   35933   }
   35934   return rc;
   35935 }
   35936 
   35937 /*
   35938 ** Sync the pager file to disk. This is a no-op for in-memory files
   35939 ** or pages with the Pager.noSync flag set.
   35940 **
   35941 ** If successful, or called on a pager for which it is a no-op, this
   35942 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
   35943 */
   35944 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
   35945   int rc;                              /* Return code */
   35946   assert( !MEMDB );
   35947   if( pPager->noSync ){
   35948     rc = SQLITE_OK;
   35949   }else{
   35950     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
   35951   }
   35952   return rc;
   35953 }
   35954 
   35955 /*
   35956 ** Sync the database file for the pager pPager. zMaster points to the name
   35957 ** of a master journal file that should be written into the individual
   35958 ** journal file. zMaster may be NULL, which is interpreted as no master
   35959 ** journal (a single database transaction).
   35960 **
   35961 ** This routine ensures that:
   35962 **
   35963 **   * The database file change-counter is updated,
   35964 **   * the journal is synced (unless the atomic-write optimization is used),
   35965 **   * all dirty pages are written to the database file,
   35966 **   * the database file is truncated (if required), and
   35967 **   * the database file synced.
   35968 **
   35969 ** The only thing that remains to commit the transaction is to finalize
   35970 ** (delete, truncate or zero the first part of) the journal file (or
   35971 ** delete the master journal file if specified).
   35972 **
   35973 ** Note that if zMaster==NULL, this does not overwrite a previous value
   35974 ** passed to an sqlite3PagerCommitPhaseOne() call.
   35975 **
   35976 ** If the final parameter - noSync - is true, then the database file itself
   35977 ** is not synced. The caller must call sqlite3PagerSync() directly to
   35978 ** sync the database file before calling CommitPhaseTwo() to delete the
   35979 ** journal file in this case.
   35980 */
   35981 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
   35982   Pager *pPager,                  /* Pager object */
   35983   const char *zMaster,            /* If not NULL, the master journal name */
   35984   int noSync                      /* True to omit the xSync on the db file */
   35985 ){
   35986   int rc = SQLITE_OK;             /* Return code */
   35987 
   35988   /* The dbOrigSize is never set if journal_mode=OFF */
   35989   assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF || pPager->dbOrigSize==0 );
   35990 
   35991   /* If a prior error occurred, this routine should not be called.  ROLLBACK
   35992   ** is the appropriate response to an error, not COMMIT.  Guard against
   35993   ** coding errors by repeating the prior error. */
   35994   if( NEVER(pPager->errCode) ) return pPager->errCode;
   35995 
   35996   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
   35997       pPager->zFilename, zMaster, pPager->dbSize));
   35998 
   35999   if( MEMDB && pPager->dbModified ){
   36000     /* If this is an in-memory db, or no pages have been written to, or this
   36001     ** function has already been called, it is mostly a no-op.  However, any
   36002     ** backup in progress needs to be restarted.
   36003     */
   36004     sqlite3BackupRestart(pPager->pBackup);
   36005   }else if( pPager->state!=PAGER_SYNCED && pPager->dbModified ){
   36006 
   36007     /* The following block updates the change-counter. Exactly how it
   36008     ** does this depends on whether or not the atomic-update optimization
   36009     ** was enabled at compile time, and if this transaction meets the
   36010     ** runtime criteria to use the operation:
   36011     **
   36012     **    * The file-system supports the atomic-write property for
   36013     **      blocks of size page-size, and
   36014     **    * This commit is not part of a multi-file transaction, and
   36015     **    * Exactly one page has been modified and store in the journal file.
   36016     **
   36017     ** If the optimization was not enabled at compile time, then the
   36018     ** pager_incr_changecounter() function is called to update the change
   36019     ** counter in 'indirect-mode'. If the optimization is compiled in but
   36020     ** is not applicable to this transaction, call sqlite3JournalCreate()
   36021     ** to make sure the journal file has actually been created, then call
   36022     ** pager_incr_changecounter() to update the change-counter in indirect
   36023     ** mode.
   36024     **
   36025     ** Otherwise, if the optimization is both enabled and applicable,
   36026     ** then call pager_incr_changecounter() to update the change-counter
   36027     ** in 'direct' mode. In this case the journal file will never be
   36028     ** created for this transaction.
   36029     */
   36030 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   36031     PgHdr *pPg;
   36032     assert( isOpen(pPager->jfd) || pPager->journalMode==PAGER_JOURNALMODE_OFF );
   36033     if( !zMaster && isOpen(pPager->jfd)
   36034      && pPager->journalOff==jrnlBufferSize(pPager)
   36035      && pPager->dbSize>=pPager->dbFileSize
   36036      && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
   36037     ){
   36038       /* Update the db file change counter via the direct-write method. The
   36039       ** following call will modify the in-memory representation of page 1
   36040       ** to include the updated change counter and then write page 1
   36041       ** directly to the database file. Because of the atomic-write
   36042       ** property of the host file-system, this is safe.
   36043       */
   36044       rc = pager_incr_changecounter(pPager, 1);
   36045     }else{
   36046       rc = sqlite3JournalCreate(pPager->jfd);
   36047       if( rc==SQLITE_OK ){
   36048         rc = pager_incr_changecounter(pPager, 0);
   36049       }
   36050     }
   36051 #else
   36052     rc = pager_incr_changecounter(pPager, 0);
   36053 #endif
   36054     if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   36055 
   36056     /* If this transaction has made the database smaller, then all pages
   36057     ** being discarded by the truncation must be written to the journal
   36058     ** file. This can only happen in auto-vacuum mode.
   36059     **
   36060     ** Before reading the pages with page numbers larger than the
   36061     ** current value of Pager.dbSize, set dbSize back to the value
   36062     ** that it took at the start of the transaction. Otherwise, the
   36063     ** calls to sqlite3PagerGet() return zeroed pages instead of
   36064     ** reading data from the database file.
   36065     **
   36066     ** When journal_mode==OFF the dbOrigSize is always zero, so this
   36067     ** block never runs if journal_mode=OFF.
   36068     */
   36069 #ifndef SQLITE_OMIT_AUTOVACUUM
   36070     if( pPager->dbSize<pPager->dbOrigSize
   36071      && ALWAYS(pPager->journalMode!=PAGER_JOURNALMODE_OFF)
   36072     ){
   36073       Pgno i;                                   /* Iterator variable */
   36074       const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
   36075       const Pgno dbSize = pPager->dbSize;       /* Database image size */
   36076       pPager->dbSize = pPager->dbOrigSize;
   36077       for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
   36078         if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
   36079           PgHdr *pPage;             /* Page to journal */
   36080           rc = sqlite3PagerGet(pPager, i, &pPage);
   36081           if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   36082           rc = sqlite3PagerWrite(pPage);
   36083           sqlite3PagerUnref(pPage);
   36084           if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   36085         }
   36086       }
   36087       pPager->dbSize = dbSize;
   36088     }
   36089 #endif
   36090 
   36091     /* Write the master journal name into the journal file. If a master
   36092     ** journal file name has already been written to the journal file,
   36093     ** or if zMaster is NULL (no master journal), then this call is a no-op.
   36094     */
   36095     rc = writeMasterJournal(pPager, zMaster);
   36096     if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   36097 
   36098     /* Sync the journal file. If the atomic-update optimization is being
   36099     ** used, this call will not create the journal file or perform any
   36100     ** real IO.
   36101     */
   36102     rc = syncJournal(pPager);
   36103     if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   36104 
   36105     /* Write all dirty pages to the database file. */
   36106     rc = pager_write_pagelist(sqlite3PcacheDirtyList(pPager->pPCache));
   36107     if( rc!=SQLITE_OK ){
   36108       assert( rc!=SQLITE_IOERR_BLOCKED );
   36109       goto commit_phase_one_exit;
   36110     }
   36111     sqlite3PcacheCleanAll(pPager->pPCache);
   36112 
   36113     /* If the file on disk is not the same size as the database image,
   36114     ** then use pager_truncate to grow or shrink the file here.
   36115     */
   36116     if( pPager->dbSize!=pPager->dbFileSize ){
   36117       Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
   36118       assert( pPager->state>=PAGER_EXCLUSIVE );
   36119       rc = pager_truncate(pPager, nNew);
   36120       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   36121     }
   36122 
   36123     /* Finally, sync the database file. */
   36124     if( !pPager->noSync && !noSync ){
   36125       rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
   36126     }
   36127     IOTRACE(("DBSYNC %p\n", pPager))
   36128 
   36129     pPager->state = PAGER_SYNCED;
   36130   }
   36131 
   36132 commit_phase_one_exit:
   36133   return rc;
   36134 }
   36135 
   36136 
   36137 /*
   36138 ** When this function is called, the database file has been completely
   36139 ** updated to reflect the changes made by the current transaction and
   36140 ** synced to disk. The journal file still exists in the file-system
   36141 ** though, and if a failure occurs at this point it will eventually
   36142 ** be used as a hot-journal and the current transaction rolled back.
   36143 **
   36144 ** This function finalizes the journal file, either by deleting,
   36145 ** truncating or partially zeroing it, so that it cannot be used
   36146 ** for hot-journal rollback. Once this is done the transaction is
   36147 ** irrevocably committed.
   36148 **
   36149 ** If an error occurs, an IO error code is returned and the pager
   36150 ** moves into the error state. Otherwise, SQLITE_OK is returned.
   36151 */
   36152 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
   36153   int rc = SQLITE_OK;                  /* Return code */
   36154 
   36155   /* This routine should not be called if a prior error has occurred.
   36156   ** But if (due to a coding error elsewhere in the system) it does get
   36157   ** called, just return the same error code without doing anything. */
   36158   if( NEVER(pPager->errCode) ) return pPager->errCode;
   36159 
   36160   /* This function should not be called if the pager is not in at least
   36161   ** PAGER_RESERVED state. And indeed SQLite never does this. But it is
   36162   ** nice to have this defensive test here anyway.
   36163   */
   36164   if( NEVER(pPager->state<PAGER_RESERVED) ) return SQLITE_ERROR;
   36165 
   36166   /* An optimization. If the database was not actually modified during
   36167   ** this transaction, the pager is running in exclusive-mode and is
   36168   ** using persistent journals, then this function is a no-op.
   36169   **
   36170   ** The start of the journal file currently contains a single journal
   36171   ** header with the nRec field set to 0. If such a journal is used as
   36172   ** a hot-journal during hot-journal rollback, 0 changes will be made
   36173   ** to the database file. So there is no need to zero the journal
   36174   ** header. Since the pager is in exclusive mode, there is no need
   36175   ** to drop any locks either.
   36176   */
   36177   if( pPager->dbModified==0 && pPager->exclusiveMode
   36178    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
   36179   ){
   36180     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
   36181     return SQLITE_OK;
   36182   }
   36183 
   36184   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
   36185   assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dbModified );
   36186   rc = pager_end_transaction(pPager, pPager->setMaster);
   36187   return pager_error(pPager, rc);
   36188 }
   36189 
   36190 /*
   36191 ** Rollback all changes. The database falls back to PAGER_SHARED mode.
   36192 **
   36193 ** This function performs two tasks:
   36194 **
   36195 **   1) It rolls back the journal file, restoring all database file and
   36196 **      in-memory cache pages to the state they were in when the transaction
   36197 **      was opened, and
   36198 **   2) It finalizes the journal file, so that it is not used for hot
   36199 **      rollback at any point in the future.
   36200 **
   36201 ** subject to the following qualifications:
   36202 **
   36203 ** * If the journal file is not yet open when this function is called,
   36204 **   then only (2) is performed. In this case there is no journal file
   36205 **   to roll back.
   36206 **
   36207 ** * If in an error state other than SQLITE_FULL, then task (1) is
   36208 **   performed. If successful, task (2). Regardless of the outcome
   36209 **   of either, the error state error code is returned to the caller
   36210 **   (i.e. either SQLITE_IOERR or SQLITE_CORRUPT).
   36211 **
   36212 ** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether
   36213 **   or not (1) is succussful, also attempt (2). If successful, return
   36214 **   SQLITE_OK. Otherwise, enter the error state and return the first
   36215 **   error code encountered.
   36216 **
   36217 **   In this case there is no chance that the database was written to.
   36218 **   So is safe to finalize the journal file even if the playback
   36219 **   (operation 1) failed. However the pager must enter the error state
   36220 **   as the contents of the in-memory cache are now suspect.
   36221 **
   36222 ** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only
   36223 **   attempt (2) if (1) is successful. Return SQLITE_OK if successful,
   36224 **   otherwise enter the error state and return the error code from the
   36225 **   failing operation.
   36226 **
   36227 **   In this case the database file may have been written to. So if the
   36228 **   playback operation did not succeed it would not be safe to finalize
   36229 **   the journal file. It needs to be left in the file-system so that
   36230 **   some other process can use it to restore the database state (by
   36231 **   hot-journal rollback).
   36232 */
   36233 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
   36234   int rc = SQLITE_OK;                  /* Return code */
   36235   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
   36236   if( !pPager->dbModified || !isOpen(pPager->jfd) ){
   36237     rc = pager_end_transaction(pPager, pPager->setMaster);
   36238   }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
   36239     if( pPager->state>=PAGER_EXCLUSIVE ){
   36240       pager_playback(pPager, 0);
   36241     }
   36242     rc = pPager->errCode;
   36243   }else{
   36244     if( pPager->state==PAGER_RESERVED ){
   36245       int rc2;
   36246       rc = pager_playback(pPager, 0);
   36247       rc2 = pager_end_transaction(pPager, pPager->setMaster);
   36248       if( rc==SQLITE_OK ){
   36249         rc = rc2;
   36250       }
   36251     }else{
   36252       rc = pager_playback(pPager, 0);
   36253     }
   36254 
   36255     if( !MEMDB ){
   36256       pPager->dbSizeValid = 0;
   36257     }
   36258 
   36259     /* If an error occurs during a ROLLBACK, we can no longer trust the pager
   36260     ** cache. So call pager_error() on the way out to make any error
   36261     ** persistent.
   36262     */
   36263     rc = pager_error(pPager, rc);
   36264   }
   36265   return rc;
   36266 }
   36267 
   36268 /*
   36269 ** Return TRUE if the database file is opened read-only.  Return FALSE
   36270 ** if the database is (in theory) writable.
   36271 */
   36272 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
   36273   return pPager->readOnly;
   36274 }
   36275 
   36276 /*
   36277 ** Return the number of references to the pager.
   36278 */
   36279 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
   36280   return sqlite3PcacheRefCount(pPager->pPCache);
   36281 }
   36282 
   36283 /*
   36284 ** Return the number of references to the specified page.
   36285 */
   36286 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
   36287   return sqlite3PcachePageRefcount(pPage);
   36288 }
   36289 
   36290 #ifdef SQLITE_TEST
   36291 /*
   36292 ** This routine is used for testing and analysis only.
   36293 */
   36294 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
   36295   static int a[11];
   36296   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
   36297   a[1] = sqlite3PcachePagecount(pPager->pPCache);
   36298   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
   36299   a[3] = pPager->dbSizeValid ? (int) pPager->dbSize : -1;
   36300   a[4] = pPager->state;
   36301   a[5] = pPager->errCode;
   36302   a[6] = pPager->nHit;
   36303   a[7] = pPager->nMiss;
   36304   a[8] = 0;  /* Used to be pPager->nOvfl */
   36305   a[9] = pPager->nRead;
   36306   a[10] = pPager->nWrite;
   36307   return a;
   36308 }
   36309 #endif
   36310 
   36311 /*
   36312 ** Return true if this is an in-memory pager.
   36313 */
   36314 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
   36315   return MEMDB;
   36316 }
   36317 
   36318 /*
   36319 ** Check that there are at least nSavepoint savepoints open. If there are
   36320 ** currently less than nSavepoints open, then open one or more savepoints
   36321 ** to make up the difference. If the number of savepoints is already
   36322 ** equal to nSavepoint, then this function is a no-op.
   36323 **
   36324 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
   36325 ** occurs while opening the sub-journal file, then an IO error code is
   36326 ** returned. Otherwise, SQLITE_OK.
   36327 */
   36328 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
   36329   int rc = SQLITE_OK;                       /* Return code */
   36330   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
   36331 
   36332   if( nSavepoint>nCurrent && pPager->useJournal ){
   36333     int ii;                                 /* Iterator variable */
   36334     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
   36335 
   36336     /* Either there is no active journal or the sub-journal is open or
   36337     ** the journal is always stored in memory */
   36338     assert( pPager->nSavepoint==0 || isOpen(pPager->sjfd) ||
   36339             pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
   36340 
   36341     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
   36342     ** if the allocation fails. Otherwise, zero the new portion in case a
   36343     ** malloc failure occurs while populating it in the for(...) loop below.
   36344     */
   36345     aNew = (PagerSavepoint *)sqlite3Realloc(
   36346         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
   36347     );
   36348     if( !aNew ){
   36349       return SQLITE_NOMEM;
   36350     }
   36351     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
   36352     pPager->aSavepoint = aNew;
   36353     pPager->nSavepoint = nSavepoint;
   36354 
   36355     /* Populate the PagerSavepoint structures just allocated. */
   36356     for(ii=nCurrent; ii<nSavepoint; ii++){
   36357       assert( pPager->dbSizeValid );
   36358       aNew[ii].nOrig = pPager->dbSize;
   36359       if( isOpen(pPager->jfd) && ALWAYS(pPager->journalOff>0) ){
   36360         aNew[ii].iOffset = pPager->journalOff;
   36361       }else{
   36362         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
   36363       }
   36364       aNew[ii].iSubRec = pPager->nSubRec;
   36365       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
   36366       if( !aNew[ii].pInSavepoint ){
   36367         return SQLITE_NOMEM;
   36368       }
   36369     }
   36370 
   36371     /* Open the sub-journal, if it is not already opened. */
   36372     rc = openSubJournal(pPager);
   36373     assertTruncateConstraint(pPager);
   36374   }
   36375 
   36376   return rc;
   36377 }
   36378 
   36379 /*
   36380 ** This function is called to rollback or release (commit) a savepoint.
   36381 ** The savepoint to release or rollback need not be the most recently
   36382 ** created savepoint.
   36383 **
   36384 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
   36385 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
   36386 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
   36387 ** that have occurred since the specified savepoint was created.
   36388 **
   36389 ** The savepoint to rollback or release is identified by parameter
   36390 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
   36391 ** (the first created). A value of (Pager.nSavepoint-1) means operate
   36392 ** on the most recently created savepoint. If iSavepoint is greater than
   36393 ** (Pager.nSavepoint-1), then this function is a no-op.
   36394 **
   36395 ** If a negative value is passed to this function, then the current
   36396 ** transaction is rolled back. This is different to calling
   36397 ** sqlite3PagerRollback() because this function does not terminate
   36398 ** the transaction or unlock the database, it just restores the
   36399 ** contents of the database to its original state.
   36400 **
   36401 ** In any case, all savepoints with an index greater than iSavepoint
   36402 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
   36403 ** then savepoint iSavepoint is also destroyed.
   36404 **
   36405 ** This function may return SQLITE_NOMEM if a memory allocation fails,
   36406 ** or an IO error code if an IO error occurs while rolling back a
   36407 ** savepoint. If no errors occur, SQLITE_OK is returned.
   36408 */
   36409 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
   36410   int rc = SQLITE_OK;
   36411 
   36412   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
   36413   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
   36414 
   36415   if( iSavepoint<pPager->nSavepoint ){
   36416     int ii;            /* Iterator variable */
   36417     int nNew;          /* Number of remaining savepoints after this op. */
   36418 
   36419     /* Figure out how many savepoints will still be active after this
   36420     ** operation. Store this value in nNew. Then free resources associated
   36421     ** with any savepoints that are destroyed by this operation.
   36422     */
   36423     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
   36424     for(ii=nNew; ii<pPager->nSavepoint; ii++){
   36425       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
   36426     }
   36427     pPager->nSavepoint = nNew;
   36428 
   36429     /* If this is a release of the outermost savepoint, truncate
   36430     ** the sub-journal to zero bytes in size. */
   36431     if( op==SAVEPOINT_RELEASE ){
   36432       if( nNew==0 && isOpen(pPager->sjfd) ){
   36433         /* Only truncate if it is an in-memory sub-journal. */
   36434         if( sqlite3IsMemJournal(pPager->sjfd) ){
   36435           rc = sqlite3OsTruncate(pPager->sjfd, 0);
   36436         }
   36437         pPager->nSubRec = 0;
   36438       }
   36439     }
   36440     /* Else this is a rollback operation, playback the specified savepoint.
   36441     ** If this is a temp-file, it is possible that the journal file has
   36442     ** not yet been opened. In this case there have been no changes to
   36443     ** the database file, so the playback operation can be skipped.
   36444     */
   36445     else if( isOpen(pPager->jfd) ){
   36446       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
   36447       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
   36448       assert(rc!=SQLITE_DONE);
   36449     }
   36450 
   36451   }
   36452   return rc;
   36453 }
   36454 
   36455 /*
   36456 ** Return the full pathname of the database file.
   36457 */
   36458 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
   36459   return pPager->zFilename;
   36460 }
   36461 
   36462 /*
   36463 ** Return the VFS structure for the pager.
   36464 */
   36465 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
   36466   return pPager->pVfs;
   36467 }
   36468 
   36469 /*
   36470 ** Return the file handle for the database file associated
   36471 ** with the pager.  This might return NULL if the file has
   36472 ** not yet been opened.
   36473 */
   36474 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
   36475   return pPager->fd;
   36476 }
   36477 
   36478 /*
   36479 ** Return the full pathname of the journal file.
   36480 */
   36481 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
   36482   return pPager->zJournal;
   36483 }
   36484 
   36485 /*
   36486 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
   36487 ** if fsync()s are executed normally.
   36488 */
   36489 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
   36490   return pPager->noSync;
   36491 }
   36492 
   36493 #ifdef SQLITE_HAS_CODEC
   36494 /*
   36495 ** Set or retrieve the codec for this pager
   36496 */
   36497 static void sqlite3PagerSetCodec(
   36498   Pager *pPager,
   36499   void *(*xCodec)(void*,void*,Pgno,int),
   36500   void (*xCodecSizeChng)(void*,int,int),
   36501   void (*xCodecFree)(void*),
   36502   void *pCodec
   36503 ){
   36504   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
   36505   pPager->xCodec = pPager->memDb ? 0 : xCodec;
   36506   pPager->xCodecSizeChng = xCodecSizeChng;
   36507   pPager->xCodecFree = xCodecFree;
   36508   pPager->pCodec = pCodec;
   36509   pagerReportSize(pPager);
   36510 }
   36511 static void *sqlite3PagerGetCodec(Pager *pPager){
   36512   return pPager->pCodec;
   36513 }
   36514 #endif
   36515 
   36516 #ifndef SQLITE_OMIT_AUTOVACUUM
   36517 /*
   36518 ** Move the page pPg to location pgno in the file.
   36519 **
   36520 ** There must be no references to the page previously located at
   36521 ** pgno (which we call pPgOld) though that page is allowed to be
   36522 ** in cache.  If the page previously located at pgno is not already
   36523 ** in the rollback journal, it is not put there by by this routine.
   36524 **
   36525 ** References to the page pPg remain valid. Updating any
   36526 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
   36527 ** allocated along with the page) is the responsibility of the caller.
   36528 **
   36529 ** A transaction must be active when this routine is called. It used to be
   36530 ** required that a statement transaction was not active, but this restriction
   36531 ** has been removed (CREATE INDEX needs to move a page when a statement
   36532 ** transaction is active).
   36533 **
   36534 ** If the fourth argument, isCommit, is non-zero, then this page is being
   36535 ** moved as part of a database reorganization just before the transaction
   36536 ** is being committed. In this case, it is guaranteed that the database page
   36537 ** pPg refers to will not be written to again within this transaction.
   36538 **
   36539 ** This function may return SQLITE_NOMEM or an IO error code if an error
   36540 ** occurs. Otherwise, it returns SQLITE_OK.
   36541 */
   36542 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
   36543   PgHdr *pPgOld;               /* The page being overwritten. */
   36544   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
   36545   int rc;                      /* Return code */
   36546   Pgno origPgno;               /* The original page number */
   36547 
   36548   assert( pPg->nRef>0 );
   36549 
   36550   /* In order to be able to rollback, an in-memory database must journal
   36551   ** the page we are moving from.
   36552   */
   36553   if( MEMDB ){
   36554     rc = sqlite3PagerWrite(pPg);
   36555     if( rc ) return rc;
   36556   }
   36557 
   36558   /* If the page being moved is dirty and has not been saved by the latest
   36559   ** savepoint, then save the current contents of the page into the
   36560   ** sub-journal now. This is required to handle the following scenario:
   36561   **
   36562   **   BEGIN;
   36563   **     <journal page X, then modify it in memory>
   36564   **     SAVEPOINT one;
   36565   **       <Move page X to location Y>
   36566   **     ROLLBACK TO one;
   36567   **
   36568   ** If page X were not written to the sub-journal here, it would not
   36569   ** be possible to restore its contents when the "ROLLBACK TO one"
   36570   ** statement were is processed.
   36571   **
   36572   ** subjournalPage() may need to allocate space to store pPg->pgno into
   36573   ** one or more savepoint bitvecs. This is the reason this function
   36574   ** may return SQLITE_NOMEM.
   36575   */
   36576   if( pPg->flags&PGHDR_DIRTY
   36577    && subjRequiresPage(pPg)
   36578    && SQLITE_OK!=(rc = subjournalPage(pPg))
   36579   ){
   36580     return rc;
   36581   }
   36582 
   36583   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
   36584       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
   36585   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
   36586 
   36587   /* If the journal needs to be sync()ed before page pPg->pgno can
   36588   ** be written to, store pPg->pgno in local variable needSyncPgno.
   36589   **
   36590   ** If the isCommit flag is set, there is no need to remember that
   36591   ** the journal needs to be sync()ed before database page pPg->pgno
   36592   ** can be written to. The caller has already promised not to write to it.
   36593   */
   36594   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
   36595     needSyncPgno = pPg->pgno;
   36596     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
   36597     assert( pPg->flags&PGHDR_DIRTY );
   36598     assert( pPager->needSync );
   36599   }
   36600 
   36601   /* If the cache contains a page with page-number pgno, remove it
   36602   ** from its hash chain. Also, if the PgHdr.needSync was set for
   36603   ** page pgno before the 'move' operation, it needs to be retained
   36604   ** for the page moved there.
   36605   */
   36606   pPg->flags &= ~PGHDR_NEED_SYNC;
   36607   pPgOld = pager_lookup(pPager, pgno);
   36608   assert( !pPgOld || pPgOld->nRef==1 );
   36609   if( pPgOld ){
   36610     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
   36611     if( MEMDB ){
   36612       /* Do not discard pages from an in-memory database since we might
   36613       ** need to rollback later.  Just move the page out of the way. */
   36614       assert( pPager->dbSizeValid );
   36615       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
   36616     }else{
   36617       sqlite3PcacheDrop(pPgOld);
   36618     }
   36619   }
   36620 
   36621   origPgno = pPg->pgno;
   36622   sqlite3PcacheMove(pPg, pgno);
   36623   sqlite3PcacheMakeDirty(pPg);
   36624   pPager->dbModified = 1;
   36625 
   36626   if( needSyncPgno ){
   36627     /* If needSyncPgno is non-zero, then the journal file needs to be
   36628     ** sync()ed before any data is written to database file page needSyncPgno.
   36629     ** Currently, no such page exists in the page-cache and the
   36630     ** "is journaled" bitvec flag has been set. This needs to be remedied by
   36631     ** loading the page into the pager-cache and setting the PgHdr.needSync
   36632     ** flag.
   36633     **
   36634     ** If the attempt to load the page into the page-cache fails, (due
   36635     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
   36636     ** array. Otherwise, if the page is loaded and written again in
   36637     ** this transaction, it may be written to the database file before
   36638     ** it is synced into the journal file. This way, it may end up in
   36639     ** the journal file twice, but that is not a problem.
   36640     **
   36641     ** The sqlite3PagerGet() call may cause the journal to sync. So make
   36642     ** sure the Pager.needSync flag is set too.
   36643     */
   36644     PgHdr *pPgHdr;
   36645     assert( pPager->needSync );
   36646     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
   36647     if( rc!=SQLITE_OK ){
   36648       if( needSyncPgno<=pPager->dbOrigSize ){
   36649         assert( pPager->pTmpSpace!=0 );
   36650         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
   36651       }
   36652       return rc;
   36653     }
   36654     pPager->needSync = 1;
   36655     assert( pPager->noSync==0 && !MEMDB );
   36656     pPgHdr->flags |= PGHDR_NEED_SYNC;
   36657     sqlite3PcacheMakeDirty(pPgHdr);
   36658     sqlite3PagerUnref(pPgHdr);
   36659   }
   36660 
   36661   /*
   36662   ** For an in-memory database, make sure the original page continues
   36663   ** to exist, in case the transaction needs to roll back.  Use pPgOld
   36664   ** as the original page since it has already been allocated.
   36665   */
   36666   if( MEMDB ){
   36667     sqlite3PcacheMove(pPgOld, origPgno);
   36668     sqlite3PagerUnref(pPgOld);
   36669   }
   36670 
   36671   return SQLITE_OK;
   36672 }
   36673 #endif
   36674 
   36675 /*
   36676 ** Return a pointer to the data for the specified page.
   36677 */
   36678 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
   36679   assert( pPg->nRef>0 || pPg->pPager->memDb );
   36680   return pPg->pData;
   36681 }
   36682 
   36683 /*
   36684 ** Return a pointer to the Pager.nExtra bytes of "extra" space
   36685 ** allocated along with the specified page.
   36686 */
   36687 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
   36688   return pPg->pExtra;
   36689 }
   36690 
   36691 /*
   36692 ** Get/set the locking-mode for this pager. Parameter eMode must be one
   36693 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
   36694 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
   36695 ** the locking-mode is set to the value specified.
   36696 **
   36697 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
   36698 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
   36699 ** locking-mode.
   36700 */
   36701 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
   36702   assert( eMode==PAGER_LOCKINGMODE_QUERY
   36703             || eMode==PAGER_LOCKINGMODE_NORMAL
   36704             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
   36705   assert( PAGER_LOCKINGMODE_QUERY<0 );
   36706   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
   36707   if( eMode>=0 && !pPager->tempFile ){
   36708     pPager->exclusiveMode = (u8)eMode;
   36709   }
   36710   return (int)pPager->exclusiveMode;
   36711 }
   36712 
   36713 /*
   36714 ** Get/set the journal-mode for this pager. Parameter eMode must be one of:
   36715 **
   36716 **    PAGER_JOURNALMODE_QUERY
   36717 **    PAGER_JOURNALMODE_DELETE
   36718 **    PAGER_JOURNALMODE_TRUNCATE
   36719 **    PAGER_JOURNALMODE_PERSIST
   36720 **    PAGER_JOURNALMODE_OFF
   36721 **    PAGER_JOURNALMODE_MEMORY
   36722 **
   36723 ** If the parameter is not _QUERY, then the journal_mode is set to the
   36724 ** value specified if the change is allowed.  The change is disallowed
   36725 ** for the following reasons:
   36726 **
   36727 **   *  An in-memory database can only have its journal_mode set to _OFF
   36728 **      or _MEMORY.
   36729 **
   36730 **   *  The journal mode may not be changed while a transaction is active.
   36731 **
   36732 ** The returned indicate the current (possibly updated) journal-mode.
   36733 */
   36734 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
   36735   assert( eMode==PAGER_JOURNALMODE_QUERY
   36736             || eMode==PAGER_JOURNALMODE_DELETE
   36737             || eMode==PAGER_JOURNALMODE_TRUNCATE
   36738             || eMode==PAGER_JOURNALMODE_PERSIST
   36739             || eMode==PAGER_JOURNALMODE_OFF
   36740             || eMode==PAGER_JOURNALMODE_MEMORY );
   36741   assert( PAGER_JOURNALMODE_QUERY<0 );
   36742   if( eMode>=0
   36743    && (!MEMDB || eMode==PAGER_JOURNALMODE_MEMORY
   36744               || eMode==PAGER_JOURNALMODE_OFF)
   36745    && !pPager->dbModified
   36746    && (!isOpen(pPager->jfd) || 0==pPager->journalOff)
   36747   ){
   36748     if( isOpen(pPager->jfd) ){
   36749       sqlite3OsClose(pPager->jfd);
   36750     }
   36751     pPager->journalMode = (u8)eMode;
   36752   }
   36753   return (int)pPager->journalMode;
   36754 }
   36755 
   36756 /*
   36757 ** Get/set the size-limit used for persistent journal files.
   36758 **
   36759 ** Setting the size limit to -1 means no limit is enforced.
   36760 ** An attempt to set a limit smaller than -1 is a no-op.
   36761 */
   36762 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
   36763   if( iLimit>=-1 ){
   36764     pPager->journalSizeLimit = iLimit;
   36765   }
   36766   return pPager->journalSizeLimit;
   36767 }
   36768 
   36769 /*
   36770 ** Return a pointer to the pPager->pBackup variable. The backup module
   36771 ** in backup.c maintains the content of this variable. This module
   36772 ** uses it opaquely as an argument to sqlite3BackupRestart() and
   36773 ** sqlite3BackupUpdate() only.
   36774 */
   36775 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
   36776   return &pPager->pBackup;
   36777 }
   36778 
   36779 #endif /* SQLITE_OMIT_DISKIO */
   36780 
   36781 /************** End of pager.c ***********************************************/
   36782 /************** Begin file btmutex.c *****************************************/
   36783 /*
   36784 ** 2007 August 27
   36785 **
   36786 ** The author disclaims copyright to this source code.  In place of
   36787 ** a legal notice, here is a blessing:
   36788 **
   36789 **    May you do good and not evil.
   36790 **    May you find forgiveness for yourself and forgive others.
   36791 **    May you share freely, never taking more than you give.
   36792 **
   36793 *************************************************************************
   36794 **
   36795 ** This file contains code used to implement mutexes on Btree objects.
   36796 ** This code really belongs in btree.c.  But btree.c is getting too
   36797 ** big and we want to break it down some.  This packaged seemed like
   36798 ** a good breakout.
   36799 */
   36800 /************** Include btreeInt.h in the middle of btmutex.c ****************/
   36801 /************** Begin file btreeInt.h ****************************************/
   36802 /*
   36803 ** 2004 April 6
   36804 **
   36805 ** The author disclaims copyright to this source code.  In place of
   36806 ** a legal notice, here is a blessing:
   36807 **
   36808 **    May you do good and not evil.
   36809 **    May you find forgiveness for yourself and forgive others.
   36810 **    May you share freely, never taking more than you give.
   36811 **
   36812 *************************************************************************
   36813 ** This file implements a external (disk-based) database using BTrees.
   36814 ** For a detailed discussion of BTrees, refer to
   36815 **
   36816 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
   36817 **     "Sorting And Searching", pages 473-480. Addison-Wesley
   36818 **     Publishing Company, Reading, Massachusetts.
   36819 **
   36820 ** The basic idea is that each page of the file contains N database
   36821 ** entries and N+1 pointers to subpages.
   36822 **
   36823 **   ----------------------------------------------------------------
   36824 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
   36825 **   ----------------------------------------------------------------
   36826 **
   36827 ** All of the keys on the page that Ptr(0) points to have values less
   36828 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
   36829 ** values greater than Key(0) and less than Key(1).  All of the keys
   36830 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
   36831 ** so forth.
   36832 **
   36833 ** Finding a particular key requires reading O(log(M)) pages from the
   36834 ** disk where M is the number of entries in the tree.
   36835 **
   36836 ** In this implementation, a single file can hold one or more separate
   36837 ** BTrees.  Each BTree is identified by the index of its root page.  The
   36838 ** key and data for any entry are combined to form the "payload".  A
   36839 ** fixed amount of payload can be carried directly on the database
   36840 ** page.  If the payload is larger than the preset amount then surplus
   36841 ** bytes are stored on overflow pages.  The payload for an entry
   36842 ** and the preceding pointer are combined to form a "Cell".  Each
   36843 ** page has a small header which contains the Ptr(N) pointer and other
   36844 ** information such as the size of key and data.
   36845 **
   36846 ** FORMAT DETAILS
   36847 **
   36848 ** The file is divided into pages.  The first page is called page 1,
   36849 ** the second is page 2, and so forth.  A page number of zero indicates
   36850 ** "no such page".  The page size can be any power of 2 between 512 and 32768.
   36851 ** Each page can be either a btree page, a freelist page, an overflow
   36852 ** page, or a pointer-map page.
   36853 **
   36854 ** The first page is always a btree page.  The first 100 bytes of the first
   36855 ** page contain a special header (the "file header") that describes the file.
   36856 ** The format of the file header is as follows:
   36857 **
   36858 **   OFFSET   SIZE    DESCRIPTION
   36859 **      0      16     Header string: "SQLite format 3\000"
   36860 **     16       2     Page size in bytes.
   36861 **     18       1     File format write version
   36862 **     19       1     File format read version
   36863 **     20       1     Bytes of unused space at the end of each page
   36864 **     21       1     Max embedded payload fraction
   36865 **     22       1     Min embedded payload fraction
   36866 **     23       1     Min leaf payload fraction
   36867 **     24       4     File change counter
   36868 **     28       4     Reserved for future use
   36869 **     32       4     First freelist page
   36870 **     36       4     Number of freelist pages in the file
   36871 **     40      60     15 4-byte meta values passed to higher layers
   36872 **
   36873 **     40       4     Schema cookie
   36874 **     44       4     File format of schema layer
   36875 **     48       4     Size of page cache
   36876 **     52       4     Largest root-page (auto/incr_vacuum)
   36877 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
   36878 **     60       4     User version
   36879 **     64       4     Incremental vacuum mode
   36880 **     68       4     unused
   36881 **     72       4     unused
   36882 **     76       4     unused
   36883 **
   36884 ** All of the integer values are big-endian (most significant byte first).
   36885 **
   36886 ** The file change counter is incremented when the database is changed
   36887 ** This counter allows other processes to know when the file has changed
   36888 ** and thus when they need to flush their cache.
   36889 **
   36890 ** The max embedded payload fraction is the amount of the total usable
   36891 ** space in a page that can be consumed by a single cell for standard
   36892 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
   36893 ** is to limit the maximum cell size so that at least 4 cells will fit
   36894 ** on one page.  Thus the default max embedded payload fraction is 64.
   36895 **
   36896 ** If the payload for a cell is larger than the max payload, then extra
   36897 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
   36898 ** as many bytes as possible are moved into the overflow pages without letting
   36899 ** the cell size drop below the min embedded payload fraction.
   36900 **
   36901 ** The min leaf payload fraction is like the min embedded payload fraction
   36902 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
   36903 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
   36904 ** not specified in the header.
   36905 **
   36906 ** Each btree pages is divided into three sections:  The header, the
   36907 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
   36908 ** file header that occurs before the page header.
   36909 **
   36910 **      |----------------|
   36911 **      | file header    |   100 bytes.  Page 1 only.
   36912 **      |----------------|
   36913 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
   36914 **      |----------------|
   36915 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
   36916 **      | array          |   |  Grows downward
   36917 **      |                |   v
   36918 **      |----------------|
   36919 **      | unallocated    |
   36920 **      | space          |
   36921 **      |----------------|   ^  Grows upwards
   36922 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
   36923 **      | area           |   |  and free space fragments.
   36924 **      |----------------|
   36925 **
   36926 ** The page headers looks like this:
   36927 **
   36928 **   OFFSET   SIZE     DESCRIPTION
   36929 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
   36930 **      1       2      byte offset to the first freeblock
   36931 **      3       2      number of cells on this page
   36932 **      5       2      first byte of the cell content area
   36933 **      7       1      number of fragmented free bytes
   36934 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
   36935 **
   36936 ** The flags define the format of this btree page.  The leaf flag means that
   36937 ** this page has no children.  The zerodata flag means that this page carries
   36938 ** only keys and no data.  The intkey flag means that the key is a integer
   36939 ** which is stored in the key size entry of the cell header rather than in
   36940 ** the payload area.
   36941 **
   36942 ** The cell pointer array begins on the first byte after the page header.
   36943 ** The cell pointer array contains zero or more 2-byte numbers which are
   36944 ** offsets from the beginning of the page to the cell content in the cell
   36945 ** content area.  The cell pointers occur in sorted order.  The system strives
   36946 ** to keep free space after the last cell pointer so that new cells can
   36947 ** be easily added without having to defragment the page.
   36948 **
   36949 ** Cell content is stored at the very end of the page and grows toward the
   36950 ** beginning of the page.
   36951 **
   36952 ** Unused space within the cell content area is collected into a linked list of
   36953 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
   36954 ** to the first freeblock is given in the header.  Freeblocks occur in
   36955 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
   36956 ** any group of 3 or fewer unused bytes in the cell content area cannot
   36957 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
   36958 ** a fragment.  The total number of bytes in all fragments is recorded.
   36959 ** in the page header at offset 7.
   36960 **
   36961 **    SIZE    DESCRIPTION
   36962 **      2     Byte offset of the next freeblock
   36963 **      2     Bytes in this freeblock
   36964 **
   36965 ** Cells are of variable length.  Cells are stored in the cell content area at
   36966 ** the end of the page.  Pointers to the cells are in the cell pointer array
   36967 ** that immediately follows the page header.  Cells is not necessarily
   36968 ** contiguous or in order, but cell pointers are contiguous and in order.
   36969 **
   36970 ** Cell content makes use of variable length integers.  A variable
   36971 ** length integer is 1 to 9 bytes where the lower 7 bits of each
   36972 ** byte are used.  The integer consists of all bytes that have bit 8 set and
   36973 ** the first byte with bit 8 clear.  The most significant byte of the integer
   36974 ** appears first.  A variable-length integer may not be more than 9 bytes long.
   36975 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
   36976 ** allows a 64-bit integer to be encoded in 9 bytes.
   36977 **
   36978 **    0x00                      becomes  0x00000000
   36979 **    0x7f                      becomes  0x0000007f
   36980 **    0x81 0x00                 becomes  0x00000080
   36981 **    0x82 0x00                 becomes  0x00000100
   36982 **    0x80 0x7f                 becomes  0x0000007f
   36983 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
   36984 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
   36985 **
   36986 ** Variable length integers are used for rowids and to hold the number of
   36987 ** bytes of key and data in a btree cell.
   36988 **
   36989 ** The content of a cell looks like this:
   36990 **
   36991 **    SIZE    DESCRIPTION
   36992 **      4     Page number of the left child. Omitted if leaf flag is set.
   36993 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
   36994 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
   36995 **      *     Payload
   36996 **      4     First page of the overflow chain.  Omitted if no overflow
   36997 **
   36998 ** Overflow pages form a linked list.  Each page except the last is completely
   36999 ** filled with data (pagesize - 4 bytes).  The last page can have as little
   37000 ** as 1 byte of data.
   37001 **
   37002 **    SIZE    DESCRIPTION
   37003 **      4     Page number of next overflow page
   37004 **      *     Data
   37005 **
   37006 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
   37007 ** file header points to the first in a linked list of trunk page.  Each trunk
   37008 ** page points to multiple leaf pages.  The content of a leaf page is
   37009 ** unspecified.  A trunk page looks like this:
   37010 **
   37011 **    SIZE    DESCRIPTION
   37012 **      4     Page number of next trunk page
   37013 **      4     Number of leaf pointers on this page
   37014 **      *     zero or more pages numbers of leaves
   37015 */
   37016 
   37017 
   37018 /* The following value is the maximum cell size assuming a maximum page
   37019 ** size give above.
   37020 */
   37021 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
   37022 
   37023 /* The maximum number of cells on a single page of the database.  This
   37024 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
   37025 ** plus 2 bytes for the index to the cell in the page header).  Such
   37026 ** small cells will be rare, but they are possible.
   37027 */
   37028 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
   37029 
   37030 /* Forward declarations */
   37031 typedef struct MemPage MemPage;
   37032 typedef struct BtLock BtLock;
   37033 
   37034 /*
   37035 ** This is a magic string that appears at the beginning of every
   37036 ** SQLite database in order to identify the file as a real database.
   37037 **
   37038 ** You can change this value at compile-time by specifying a
   37039 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
   37040 ** header must be exactly 16 bytes including the zero-terminator so
   37041 ** the string itself should be 15 characters long.  If you change
   37042 ** the header, then your custom library will not be able to read
   37043 ** databases generated by the standard tools and the standard tools
   37044 ** will not be able to read databases created by your custom library.
   37045 */
   37046 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
   37047 #  define SQLITE_FILE_HEADER "SQLite format 3"
   37048 #endif
   37049 
   37050 /*
   37051 ** Page type flags.  An ORed combination of these flags appear as the
   37052 ** first byte of on-disk image of every BTree page.
   37053 */
   37054 #define PTF_INTKEY    0x01
   37055 #define PTF_ZERODATA  0x02
   37056 #define PTF_LEAFDATA  0x04
   37057 #define PTF_LEAF      0x08
   37058 
   37059 /*
   37060 ** As each page of the file is loaded into memory, an instance of the following
   37061 ** structure is appended and initialized to zero.  This structure stores
   37062 ** information about the page that is decoded from the raw file page.
   37063 **
   37064 ** The pParent field points back to the parent page.  This allows us to
   37065 ** walk up the BTree from any leaf to the root.  Care must be taken to
   37066 ** unref() the parent page pointer when this page is no longer referenced.
   37067 ** The pageDestructor() routine handles that chore.
   37068 **
   37069 ** Access to all fields of this structure is controlled by the mutex
   37070 ** stored in MemPage.pBt->mutex.
   37071 */
   37072 struct MemPage {
   37073   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
   37074   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
   37075   u8 intKey;           /* True if intkey flag is set */
   37076   u8 leaf;             /* True if leaf flag is set */
   37077   u8 hasData;          /* True if this page stores data */
   37078   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
   37079   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
   37080   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
   37081   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
   37082   u16 cellOffset;      /* Index in aData of first cell pointer */
   37083   u16 nFree;           /* Number of free bytes on the page */
   37084   u16 nCell;           /* Number of cells on this page, local and ovfl */
   37085   u16 maskPage;        /* Mask for page offset */
   37086   struct _OvflCell {   /* Cells that will not fit on aData[] */
   37087     u8 *pCell;          /* Pointers to the body of the overflow cell */
   37088     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
   37089   } aOvfl[5];
   37090   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
   37091   u8 *aData;           /* Pointer to disk image of the page data */
   37092   DbPage *pDbPage;     /* Pager page handle */
   37093   Pgno pgno;           /* Page number for this page */
   37094 };
   37095 
   37096 /*
   37097 ** The in-memory image of a disk page has the auxiliary information appended
   37098 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
   37099 ** that extra information.
   37100 */
   37101 #define EXTRA_SIZE sizeof(MemPage)
   37102 
   37103 /*
   37104 ** A linked list of the following structures is stored at BtShared.pLock.
   37105 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
   37106 ** is opened on the table with root page BtShared.iTable. Locks are removed
   37107 ** from this list when a transaction is committed or rolled back, or when
   37108 ** a btree handle is closed.
   37109 */
   37110 struct BtLock {
   37111   Btree *pBtree;        /* Btree handle holding this lock */
   37112   Pgno iTable;          /* Root page of table */
   37113   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
   37114   BtLock *pNext;        /* Next in BtShared.pLock list */
   37115 };
   37116 
   37117 /* Candidate values for BtLock.eLock */
   37118 #define READ_LOCK     1
   37119 #define WRITE_LOCK    2
   37120 
   37121 /* A Btree handle
   37122 **
   37123 ** A database connection contains a pointer to an instance of
   37124 ** this object for every database file that it has open.  This structure
   37125 ** is opaque to the database connection.  The database connection cannot
   37126 ** see the internals of this structure and only deals with pointers to
   37127 ** this structure.
   37128 **
   37129 ** For some database files, the same underlying database cache might be
   37130 ** shared between multiple connections.  In that case, each connection
   37131 ** has it own instance of this object.  But each instance of this object
   37132 ** points to the same BtShared object.  The database cache and the
   37133 ** schema associated with the database file are all contained within
   37134 ** the BtShared object.
   37135 **
   37136 ** All fields in this structure are accessed under sqlite3.mutex.
   37137 ** The pBt pointer itself may not be changed while there exists cursors
   37138 ** in the referenced BtShared that point back to this Btree since those
   37139 ** cursors have to do go through this Btree to find their BtShared and
   37140 ** they often do so without holding sqlite3.mutex.
   37141 */
   37142 struct Btree {
   37143   sqlite3 *db;       /* The database connection holding this btree */
   37144   BtShared *pBt;     /* Sharable content of this btree */
   37145   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
   37146   u8 sharable;       /* True if we can share pBt with another db */
   37147   u8 locked;         /* True if db currently has pBt locked */
   37148   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
   37149   int nBackup;       /* Number of backup operations reading this btree */
   37150   Btree *pNext;      /* List of other sharable Btrees from the same db */
   37151   Btree *pPrev;      /* Back pointer of the same list */
   37152 #ifndef SQLITE_OMIT_SHARED_CACHE
   37153   BtLock lock;       /* Object used to lock page 1 */
   37154 #endif
   37155 };
   37156 
   37157 /*
   37158 ** Btree.inTrans may take one of the following values.
   37159 **
   37160 ** If the shared-data extension is enabled, there may be multiple users
   37161 ** of the Btree structure. At most one of these may open a write transaction,
   37162 ** but any number may have active read transactions.
   37163 */
   37164 #define TRANS_NONE  0
   37165 #define TRANS_READ  1
   37166 #define TRANS_WRITE 2
   37167 
   37168 /*
   37169 ** An instance of this object represents a single database file.
   37170 **
   37171 ** A single database file can be in use as the same time by two
   37172 ** or more database connections.  When two or more connections are
   37173 ** sharing the same database file, each connection has it own
   37174 ** private Btree object for the file and each of those Btrees points
   37175 ** to this one BtShared object.  BtShared.nRef is the number of
   37176 ** connections currently sharing this database file.
   37177 **
   37178 ** Fields in this structure are accessed under the BtShared.mutex
   37179 ** mutex, except for nRef and pNext which are accessed under the
   37180 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
   37181 ** may not be modified once it is initially set as long as nRef>0.
   37182 ** The pSchema field may be set once under BtShared.mutex and
   37183 ** thereafter is unchanged as long as nRef>0.
   37184 **
   37185 ** isPending:
   37186 **
   37187 **   If a BtShared client fails to obtain a write-lock on a database
   37188 **   table (because there exists one or more read-locks on the table),
   37189 **   the shared-cache enters 'pending-lock' state and isPending is
   37190 **   set to true.
   37191 **
   37192 **   The shared-cache leaves the 'pending lock' state when either of
   37193 **   the following occur:
   37194 **
   37195 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
   37196 **     2) The number of locks held by other connections drops to zero.
   37197 **
   37198 **   while in the 'pending-lock' state, no connection may start a new
   37199 **   transaction.
   37200 **
   37201 **   This feature is included to help prevent writer-starvation.
   37202 */
   37203 struct BtShared {
   37204   Pager *pPager;        /* The page cache */
   37205   sqlite3 *db;          /* Database connection currently using this Btree */
   37206   BtCursor *pCursor;    /* A list of all open cursors */
   37207   MemPage *pPage1;      /* First page of the database */
   37208   u8 readOnly;          /* True if the underlying file is readonly */
   37209   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
   37210 #ifndef SQLITE_OMIT_AUTOVACUUM
   37211   u8 autoVacuum;        /* True if auto-vacuum is enabled */
   37212   u8 incrVacuum;        /* True if incr-vacuum is enabled */
   37213 #endif
   37214   u16 pageSize;         /* Total number of bytes on a page */
   37215   u16 usableSize;       /* Number of usable bytes on each page */
   37216   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
   37217   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
   37218   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
   37219   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
   37220   u8 inTransaction;     /* Transaction state */
   37221   int nTransaction;     /* Number of open transactions (read + write) */
   37222   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
   37223   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
   37224   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
   37225   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
   37226 #ifndef SQLITE_OMIT_SHARED_CACHE
   37227   int nRef;             /* Number of references to this structure */
   37228   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
   37229   BtLock *pLock;        /* List of locks held on this shared-btree struct */
   37230   Btree *pWriter;       /* Btree with currently open write transaction */
   37231   u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
   37232   u8 isPending;         /* If waiting for read-locks to clear */
   37233 #endif
   37234   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
   37235 };
   37236 
   37237 /*
   37238 ** An instance of the following structure is used to hold information
   37239 ** about a cell.  The parseCellPtr() function fills in this structure
   37240 ** based on information extract from the raw disk page.
   37241 */
   37242 typedef struct CellInfo CellInfo;
   37243 struct CellInfo {
   37244   u8 *pCell;     /* Pointer to the start of cell content */
   37245   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
   37246   u32 nData;     /* Number of bytes of data */
   37247   u32 nPayload;  /* Total amount of payload */
   37248   u16 nHeader;   /* Size of the cell content header in bytes */
   37249   u16 nLocal;    /* Amount of payload held locally */
   37250   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
   37251   u16 nSize;     /* Size of the cell content on the main b-tree page */
   37252 };
   37253 
   37254 /*
   37255 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
   37256 ** this will be declared corrupt. This value is calculated based on a
   37257 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
   37258 ** root-node and 3 for all other internal nodes.
   37259 **
   37260 ** If a tree that appears to be taller than this is encountered, it is
   37261 ** assumed that the database is corrupt.
   37262 */
   37263 #define BTCURSOR_MAX_DEPTH 20
   37264 
   37265 /*
   37266 ** A cursor is a pointer to a particular entry within a particular
   37267 ** b-tree within a database file.
   37268 **
   37269 ** The entry is identified by its MemPage and the index in
   37270 ** MemPage.aCell[] of the entry.
   37271 **
   37272 ** A single database file can shared by two more database connections,
   37273 ** but cursors cannot be shared.  Each cursor is associated with a
   37274 ** particular database connection identified BtCursor.pBtree.db.
   37275 **
   37276 ** Fields in this structure are accessed under the BtShared.mutex
   37277 ** found at self->pBt->mutex.
   37278 */
   37279 struct BtCursor {
   37280   Btree *pBtree;            /* The Btree to which this cursor belongs */
   37281   BtShared *pBt;            /* The BtShared this cursor points to */
   37282   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
   37283   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
   37284   Pgno pgnoRoot;            /* The root page of this tree */
   37285   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
   37286   CellInfo info;            /* A parse of the cell we are pointing at */
   37287   u8 wrFlag;                /* True if writable */
   37288   u8 atLast;                /* Cursor pointing to the last entry */
   37289   u8 validNKey;             /* True if info.nKey is valid */
   37290   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
   37291   void *pKey;      /* Saved key that was cursor's last known position */
   37292   i64 nKey;        /* Size of pKey, or last integer key */
   37293   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
   37294 #ifndef SQLITE_OMIT_INCRBLOB
   37295   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
   37296   Pgno *aOverflow;          /* Cache of overflow page locations */
   37297 #endif
   37298   i16 iPage;                            /* Index of current page in apPage */
   37299   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
   37300   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
   37301 };
   37302 
   37303 /*
   37304 ** Potential values for BtCursor.eState.
   37305 **
   37306 ** CURSOR_VALID:
   37307 **   Cursor points to a valid entry. getPayload() etc. may be called.
   37308 **
   37309 ** CURSOR_INVALID:
   37310 **   Cursor does not point to a valid entry. This can happen (for example)
   37311 **   because the table is empty or because BtreeCursorFirst() has not been
   37312 **   called.
   37313 **
   37314 ** CURSOR_REQUIRESEEK:
   37315 **   The table that this cursor was opened on still exists, but has been
   37316 **   modified since the cursor was last used. The cursor position is saved
   37317 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
   37318 **   this state, restoreCursorPosition() can be called to attempt to
   37319 **   seek the cursor to the saved position.
   37320 **
   37321 ** CURSOR_FAULT:
   37322 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
   37323 **   on a different connection that shares the BtShared cache with this
   37324 **   cursor.  The error has left the cache in an inconsistent state.
   37325 **   Do nothing else with this cursor.  Any attempt to use the cursor
   37326 **   should return the error code stored in BtCursor.skip
   37327 */
   37328 #define CURSOR_INVALID           0
   37329 #define CURSOR_VALID             1
   37330 #define CURSOR_REQUIRESEEK       2
   37331 #define CURSOR_FAULT             3
   37332 
   37333 /*
   37334 ** The database page the PENDING_BYTE occupies. This page is never used.
   37335 */
   37336 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
   37337 
   37338 /*
   37339 ** These macros define the location of the pointer-map entry for a
   37340 ** database page. The first argument to each is the number of usable
   37341 ** bytes on each page of the database (often 1024). The second is the
   37342 ** page number to look up in the pointer map.
   37343 **
   37344 ** PTRMAP_PAGENO returns the database page number of the pointer-map
   37345 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
   37346 ** the offset of the requested map entry.
   37347 **
   37348 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
   37349 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
   37350 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
   37351 ** this test.
   37352 */
   37353 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
   37354 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
   37355 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
   37356 
   37357 /*
   37358 ** The pointer map is a lookup table that identifies the parent page for
   37359 ** each child page in the database file.  The parent page is the page that
   37360 ** contains a pointer to the child.  Every page in the database contains
   37361 ** 0 or 1 parent pages.  (In this context 'database page' refers
   37362 ** to any page that is not part of the pointer map itself.)  Each pointer map
   37363 ** entry consists of a single byte 'type' and a 4 byte parent page number.
   37364 ** The PTRMAP_XXX identifiers below are the valid types.
   37365 **
   37366 ** The purpose of the pointer map is to facility moving pages from one
   37367 ** position in the file to another as part of autovacuum.  When a page
   37368 ** is moved, the pointer in its parent must be updated to point to the
   37369 ** new location.  The pointer map is used to locate the parent page quickly.
   37370 **
   37371 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
   37372 **                  used in this case.
   37373 **
   37374 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
   37375 **                  is not used in this case.
   37376 **
   37377 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
   37378 **                   overflow pages. The page number identifies the page that
   37379 **                   contains the cell with a pointer to this overflow page.
   37380 **
   37381 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
   37382 **                   overflow pages. The page-number identifies the previous
   37383 **                   page in the overflow page list.
   37384 **
   37385 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
   37386 **               identifies the parent page in the btree.
   37387 */
   37388 #define PTRMAP_ROOTPAGE 1
   37389 #define PTRMAP_FREEPAGE 2
   37390 #define PTRMAP_OVERFLOW1 3
   37391 #define PTRMAP_OVERFLOW2 4
   37392 #define PTRMAP_BTREE 5
   37393 
   37394 /* A bunch of assert() statements to check the transaction state variables
   37395 ** of handle p (type Btree*) are internally consistent.
   37396 */
   37397 #define btreeIntegrity(p) \
   37398   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
   37399   assert( p->pBt->inTransaction>=p->inTrans );
   37400 
   37401 
   37402 /*
   37403 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
   37404 ** if the database supports auto-vacuum or not. Because it is used
   37405 ** within an expression that is an argument to another macro
   37406 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
   37407 ** So, this macro is defined instead.
   37408 */
   37409 #ifndef SQLITE_OMIT_AUTOVACUUM
   37410 #define ISAUTOVACUUM (pBt->autoVacuum)
   37411 #else
   37412 #define ISAUTOVACUUM 0
   37413 #endif
   37414 
   37415 
   37416 /*
   37417 ** This structure is passed around through all the sanity checking routines
   37418 ** in order to keep track of some global state information.
   37419 */
   37420 typedef struct IntegrityCk IntegrityCk;
   37421 struct IntegrityCk {
   37422   BtShared *pBt;    /* The tree being checked out */
   37423   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
   37424   Pgno nPage;       /* Number of pages in the database */
   37425   int *anRef;       /* Number of times each page is referenced */
   37426   int mxErr;        /* Stop accumulating errors when this reaches zero */
   37427   int nErr;         /* Number of messages written to zErrMsg so far */
   37428   int mallocFailed; /* A memory allocation error has occurred */
   37429   StrAccum errMsg;  /* Accumulate the error message text here */
   37430 };
   37431 
   37432 /*
   37433 ** Read or write a two- and four-byte big-endian integer values.
   37434 */
   37435 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
   37436 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
   37437 #define get4byte sqlite3Get4byte
   37438 #define put4byte sqlite3Put4byte
   37439 
   37440 /************** End of btreeInt.h ********************************************/
   37441 /************** Continuing where we left off in btmutex.c ********************/
   37442 #ifndef SQLITE_OMIT_SHARED_CACHE
   37443 #if SQLITE_THREADSAFE
   37444 
   37445 /*
   37446 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
   37447 ** set BtShared.db to the database handle associated with p and the
   37448 ** p->locked boolean to true.
   37449 */
   37450 static void lockBtreeMutex(Btree *p){
   37451   assert( p->locked==0 );
   37452   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
   37453   assert( sqlite3_mutex_held(p->db->mutex) );
   37454 
   37455   sqlite3_mutex_enter(p->pBt->mutex);
   37456   p->pBt->db = p->db;
   37457   p->locked = 1;
   37458 }
   37459 
   37460 /*
   37461 ** Release the BtShared mutex associated with B-Tree handle p and
   37462 ** clear the p->locked boolean.
   37463 */
   37464 static void unlockBtreeMutex(Btree *p){
   37465   assert( p->locked==1 );
   37466   assert( sqlite3_mutex_held(p->pBt->mutex) );
   37467   assert( sqlite3_mutex_held(p->db->mutex) );
   37468   assert( p->db==p->pBt->db );
   37469 
   37470   sqlite3_mutex_leave(p->pBt->mutex);
   37471   p->locked = 0;
   37472 }
   37473 
   37474 /*
   37475 ** Enter a mutex on the given BTree object.
   37476 **
   37477 ** If the object is not sharable, then no mutex is ever required
   37478 ** and this routine is a no-op.  The underlying mutex is non-recursive.
   37479 ** But we keep a reference count in Btree.wantToLock so the behavior
   37480 ** of this interface is recursive.
   37481 **
   37482 ** To avoid deadlocks, multiple Btrees are locked in the same order
   37483 ** by all database connections.  The p->pNext is a list of other
   37484 ** Btrees belonging to the same database connection as the p Btree
   37485 ** which need to be locked after p.  If we cannot get a lock on
   37486 ** p, then first unlock all of the others on p->pNext, then wait
   37487 ** for the lock to become available on p, then relock all of the
   37488 ** subsequent Btrees that desire a lock.
   37489 */
   37490 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
   37491   Btree *pLater;
   37492 
   37493   /* Some basic sanity checking on the Btree.  The list of Btrees
   37494   ** connected by pNext and pPrev should be in sorted order by
   37495   ** Btree.pBt value. All elements of the list should belong to
   37496   ** the same connection. Only shared Btrees are on the list. */
   37497   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
   37498   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
   37499   assert( p->pNext==0 || p->pNext->db==p->db );
   37500   assert( p->pPrev==0 || p->pPrev->db==p->db );
   37501   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
   37502 
   37503   /* Check for locking consistency */
   37504   assert( !p->locked || p->wantToLock>0 );
   37505   assert( p->sharable || p->wantToLock==0 );
   37506 
   37507   /* We should already hold a lock on the database connection */
   37508   assert( sqlite3_mutex_held(p->db->mutex) );
   37509 
   37510   /* Unless the database is sharable and unlocked, then BtShared.db
   37511   ** should already be set correctly. */
   37512   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
   37513 
   37514   if( !p->sharable ) return;
   37515   p->wantToLock++;
   37516   if( p->locked ) return;
   37517 
   37518   /* In most cases, we should be able to acquire the lock we
   37519   ** want without having to go throught the ascending lock
   37520   ** procedure that follows.  Just be sure not to block.
   37521   */
   37522   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
   37523     p->pBt->db = p->db;
   37524     p->locked = 1;
   37525     return;
   37526   }
   37527 
   37528   /* To avoid deadlock, first release all locks with a larger
   37529   ** BtShared address.  Then acquire our lock.  Then reacquire
   37530   ** the other BtShared locks that we used to hold in ascending
   37531   ** order.
   37532   */
   37533   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
   37534     assert( pLater->sharable );
   37535     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
   37536     assert( !pLater->locked || pLater->wantToLock>0 );
   37537     if( pLater->locked ){
   37538       unlockBtreeMutex(pLater);
   37539     }
   37540   }
   37541   lockBtreeMutex(p);
   37542   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
   37543     if( pLater->wantToLock ){
   37544       lockBtreeMutex(pLater);
   37545     }
   37546   }
   37547 }
   37548 
   37549 /*
   37550 ** Exit the recursive mutex on a Btree.
   37551 */
   37552 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
   37553   if( p->sharable ){
   37554     assert( p->wantToLock>0 );
   37555     p->wantToLock--;
   37556     if( p->wantToLock==0 ){
   37557       unlockBtreeMutex(p);
   37558     }
   37559   }
   37560 }
   37561 
   37562 #ifndef NDEBUG
   37563 /*
   37564 ** Return true if the BtShared mutex is held on the btree, or if the
   37565 ** B-Tree is not marked as sharable.
   37566 **
   37567 ** This routine is used only from within assert() statements.
   37568 */
   37569 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
   37570   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
   37571   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
   37572   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
   37573   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
   37574 
   37575   return (p->sharable==0 || p->locked);
   37576 }
   37577 #endif
   37578 
   37579 
   37580 #ifndef SQLITE_OMIT_INCRBLOB
   37581 /*
   37582 ** Enter and leave a mutex on a Btree given a cursor owned by that
   37583 ** Btree.  These entry points are used by incremental I/O and can be
   37584 ** omitted if that module is not used.
   37585 */
   37586 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
   37587   sqlite3BtreeEnter(pCur->pBtree);
   37588 }
   37589 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
   37590   sqlite3BtreeLeave(pCur->pBtree);
   37591 }
   37592 #endif /* SQLITE_OMIT_INCRBLOB */
   37593 
   37594 
   37595 /*
   37596 ** Enter the mutex on every Btree associated with a database
   37597 ** connection.  This is needed (for example) prior to parsing
   37598 ** a statement since we will be comparing table and column names
   37599 ** against all schemas and we do not want those schemas being
   37600 ** reset out from under us.
   37601 **
   37602 ** There is a corresponding leave-all procedures.
   37603 **
   37604 ** Enter the mutexes in accending order by BtShared pointer address
   37605 ** to avoid the possibility of deadlock when two threads with
   37606 ** two or more btrees in common both try to lock all their btrees
   37607 ** at the same instant.
   37608 */
   37609 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
   37610   int i;
   37611   Btree *p, *pLater;
   37612   assert( sqlite3_mutex_held(db->mutex) );
   37613   for(i=0; i<db->nDb; i++){
   37614     p = db->aDb[i].pBt;
   37615     assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
   37616     if( p && p->sharable ){
   37617       p->wantToLock++;
   37618       if( !p->locked ){
   37619         assert( p->wantToLock==1 );
   37620         while( p->pPrev ) p = p->pPrev;
   37621         /* Reason for ALWAYS:  There must be at least on unlocked Btree in
   37622         ** the chain.  Otherwise the !p->locked test above would have failed */
   37623         while( p->locked && ALWAYS(p->pNext) ) p = p->pNext;
   37624         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
   37625           if( pLater->locked ){
   37626             unlockBtreeMutex(pLater);
   37627           }
   37628         }
   37629         while( p ){
   37630           lockBtreeMutex(p);
   37631           p = p->pNext;
   37632         }
   37633       }
   37634     }
   37635   }
   37636 }
   37637 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
   37638   int i;
   37639   Btree *p;
   37640   assert( sqlite3_mutex_held(db->mutex) );
   37641   for(i=0; i<db->nDb; i++){
   37642     p = db->aDb[i].pBt;
   37643     if( p && p->sharable ){
   37644       assert( p->wantToLock>0 );
   37645       p->wantToLock--;
   37646       if( p->wantToLock==0 ){
   37647         unlockBtreeMutex(p);
   37648       }
   37649     }
   37650   }
   37651 }
   37652 
   37653 #ifndef NDEBUG
   37654 /*
   37655 ** Return true if the current thread holds the database connection
   37656 ** mutex and all required BtShared mutexes.
   37657 **
   37658 ** This routine is used inside assert() statements only.
   37659 */
   37660 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
   37661   int i;
   37662   if( !sqlite3_mutex_held(db->mutex) ){
   37663     return 0;
   37664   }
   37665   for(i=0; i<db->nDb; i++){
   37666     Btree *p;
   37667     p = db->aDb[i].pBt;
   37668     if( p && p->sharable &&
   37669          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
   37670       return 0;
   37671     }
   37672   }
   37673   return 1;
   37674 }
   37675 #endif /* NDEBUG */
   37676 
   37677 /*
   37678 ** Add a new Btree pointer to a BtreeMutexArray.
   37679 ** if the pointer can possibly be shared with
   37680 ** another database connection.
   37681 **
   37682 ** The pointers are kept in sorted order by pBtree->pBt.  That
   37683 ** way when we go to enter all the mutexes, we can enter them
   37684 ** in order without every having to backup and retry and without
   37685 ** worrying about deadlock.
   37686 **
   37687 ** The number of shared btrees will always be small (usually 0 or 1)
   37688 ** so an insertion sort is an adequate algorithm here.
   37689 */
   37690 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
   37691   int i, j;
   37692   BtShared *pBt;
   37693   if( pBtree==0 || pBtree->sharable==0 ) return;
   37694 #ifndef NDEBUG
   37695   {
   37696     for(i=0; i<pArray->nMutex; i++){
   37697       assert( pArray->aBtree[i]!=pBtree );
   37698     }
   37699   }
   37700 #endif
   37701   assert( pArray->nMutex>=0 );
   37702   assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
   37703   pBt = pBtree->pBt;
   37704   for(i=0; i<pArray->nMutex; i++){
   37705     assert( pArray->aBtree[i]!=pBtree );
   37706     if( pArray->aBtree[i]->pBt>pBt ){
   37707       for(j=pArray->nMutex; j>i; j--){
   37708         pArray->aBtree[j] = pArray->aBtree[j-1];
   37709       }
   37710       pArray->aBtree[i] = pBtree;
   37711       pArray->nMutex++;
   37712       return;
   37713     }
   37714   }
   37715   pArray->aBtree[pArray->nMutex++] = pBtree;
   37716 }
   37717 
   37718 /*
   37719 ** Enter the mutex of every btree in the array.  This routine is
   37720 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
   37721 ** exited at the end of the same function.
   37722 */
   37723 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
   37724   int i;
   37725   for(i=0; i<pArray->nMutex; i++){
   37726     Btree *p = pArray->aBtree[i];
   37727     /* Some basic sanity checking */
   37728     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
   37729     assert( !p->locked || p->wantToLock>0 );
   37730 
   37731     /* We should already hold a lock on the database connection */
   37732     assert( sqlite3_mutex_held(p->db->mutex) );
   37733 
   37734     /* The Btree is sharable because only sharable Btrees are entered
   37735     ** into the array in the first place. */
   37736     assert( p->sharable );
   37737 
   37738     p->wantToLock++;
   37739     if( !p->locked ){
   37740       lockBtreeMutex(p);
   37741     }
   37742   }
   37743 }
   37744 
   37745 /*
   37746 ** Leave the mutex of every btree in the group.
   37747 */
   37748 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
   37749   int i;
   37750   for(i=0; i<pArray->nMutex; i++){
   37751     Btree *p = pArray->aBtree[i];
   37752     /* Some basic sanity checking */
   37753     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
   37754     assert( p->locked );
   37755     assert( p->wantToLock>0 );
   37756 
   37757     /* We should already hold a lock on the database connection */
   37758     assert( sqlite3_mutex_held(p->db->mutex) );
   37759 
   37760     p->wantToLock--;
   37761     if( p->wantToLock==0 ){
   37762       unlockBtreeMutex(p);
   37763     }
   37764   }
   37765 }
   37766 
   37767 #else
   37768 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
   37769   p->pBt->db = p->db;
   37770 }
   37771 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
   37772   int i;
   37773   for(i=0; i<db->nDb; i++){
   37774     Btree *p = db->aDb[i].pBt;
   37775     if( p ){
   37776       p->pBt->db = p->db;
   37777     }
   37778   }
   37779 }
   37780 #endif /* if SQLITE_THREADSAFE */
   37781 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
   37782 
   37783 /************** End of btmutex.c *********************************************/
   37784 /************** Begin file btree.c *******************************************/
   37785 /*
   37786 ** 2004 April 6
   37787 **
   37788 ** The author disclaims copyright to this source code.  In place of
   37789 ** a legal notice, here is a blessing:
   37790 **
   37791 **    May you do good and not evil.
   37792 **    May you find forgiveness for yourself and forgive others.
   37793 **    May you share freely, never taking more than you give.
   37794 **
   37795 *************************************************************************
   37796 ** This file implements a external (disk-based) database using BTrees.
   37797 ** See the header comment on "btreeInt.h" for additional information.
   37798 ** Including a description of file format and an overview of operation.
   37799 */
   37800 
   37801 /*
   37802 ** The header string that appears at the beginning of every
   37803 ** SQLite database.
   37804 */
   37805 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
   37806 
   37807 /*
   37808 ** Set this global variable to 1 to enable tracing using the TRACE
   37809 ** macro.
   37810 */
   37811 #if 0
   37812 int sqlite3BtreeTrace=1;  /* True to enable tracing */
   37813 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
   37814 #else
   37815 # define TRACE(X)
   37816 #endif
   37817 
   37818 
   37819 
   37820 #ifndef SQLITE_OMIT_SHARED_CACHE
   37821 /*
   37822 ** A list of BtShared objects that are eligible for participation
   37823 ** in shared cache.  This variable has file scope during normal builds,
   37824 ** but the test harness needs to access it so we make it global for
   37825 ** test builds.
   37826 **
   37827 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
   37828 */
   37829 #ifdef SQLITE_TEST
   37830 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
   37831 #else
   37832 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
   37833 #endif
   37834 #endif /* SQLITE_OMIT_SHARED_CACHE */
   37835 
   37836 #ifndef SQLITE_OMIT_SHARED_CACHE
   37837 /*
   37838 ** Enable or disable the shared pager and schema features.
   37839 **
   37840 ** This routine has no effect on existing database connections.
   37841 ** The shared cache setting effects only future calls to
   37842 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
   37843 */
   37844 SQLITE_API int sqlite3_enable_shared_cache(int enable){
   37845   sqlite3GlobalConfig.sharedCacheEnabled = enable;
   37846   return SQLITE_OK;
   37847 }
   37848 #endif
   37849 
   37850 
   37851 
   37852 #ifdef SQLITE_OMIT_SHARED_CACHE
   37853   /*
   37854   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
   37855   ** and clearAllSharedCacheTableLocks()
   37856   ** manipulate entries in the BtShared.pLock linked list used to store
   37857   ** shared-cache table level locks. If the library is compiled with the
   37858   ** shared-cache feature disabled, then there is only ever one user
   37859   ** of each BtShared structure and so this locking is not necessary.
   37860   ** So define the lock related functions as no-ops.
   37861   */
   37862   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
   37863   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
   37864   #define clearAllSharedCacheTableLocks(a)
   37865   #define downgradeAllSharedCacheTableLocks(a)
   37866   #define hasSharedCacheTableLock(a,b,c,d) 1
   37867   #define hasReadConflicts(a, b) 0
   37868 #endif
   37869 
   37870 #ifndef SQLITE_OMIT_SHARED_CACHE
   37871 
   37872 #ifdef SQLITE_DEBUG
   37873 /*
   37874 **** This function is only used as part of an assert() statement. ***
   37875 **
   37876 ** Check to see if pBtree holds the required locks to read or write to the
   37877 ** table with root page iRoot.   Return 1 if it does and 0 if not.
   37878 **
   37879 ** For example, when writing to a table with root-page iRoot via
   37880 ** Btree connection pBtree:
   37881 **
   37882 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
   37883 **
   37884 ** When writing to an index that resides in a sharable database, the
   37885 ** caller should have first obtained a lock specifying the root page of
   37886 ** the corresponding table. This makes things a bit more complicated,
   37887 ** as this module treats each table as a separate structure. To determine
   37888 ** the table corresponding to the index being written, this
   37889 ** function has to search through the database schema.
   37890 **
   37891 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
   37892 ** hold a write-lock on the schema table (root page 1). This is also
   37893 ** acceptable.
   37894 */
   37895 static int hasSharedCacheTableLock(
   37896   Btree *pBtree,         /* Handle that must hold lock */
   37897   Pgno iRoot,            /* Root page of b-tree */
   37898   int isIndex,           /* True if iRoot is the root of an index b-tree */
   37899   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
   37900 ){
   37901   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
   37902   Pgno iTab = 0;
   37903   BtLock *pLock;
   37904 
   37905   /* If this database is not shareable, or if the client is reading
   37906   ** and has the read-uncommitted flag set, then no lock is required.
   37907   ** Return true immediately.
   37908   */
   37909   if( (pBtree->sharable==0)
   37910    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
   37911   ){
   37912     return 1;
   37913   }
   37914 
   37915   /* If the client is reading  or writing an index and the schema is
   37916   ** not loaded, then it is too difficult to actually check to see if
   37917   ** the correct locks are held.  So do not bother - just return true.
   37918   ** This case does not come up very often anyhow.
   37919   */
   37920   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
   37921     return 1;
   37922   }
   37923 
   37924   /* Figure out the root-page that the lock should be held on. For table
   37925   ** b-trees, this is just the root page of the b-tree being read or
   37926   ** written. For index b-trees, it is the root page of the associated
   37927   ** table.  */
   37928   if( isIndex ){
   37929     HashElem *p;
   37930     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
   37931       Index *pIdx = (Index *)sqliteHashData(p);
   37932       if( pIdx->tnum==(int)iRoot ){
   37933         iTab = pIdx->pTable->tnum;
   37934       }
   37935     }
   37936   }else{
   37937     iTab = iRoot;
   37938   }
   37939 
   37940   /* Search for the required lock. Either a write-lock on root-page iTab, a
   37941   ** write-lock on the schema table, or (if the client is reading) a
   37942   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
   37943   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
   37944     if( pLock->pBtree==pBtree
   37945      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
   37946      && pLock->eLock>=eLockType
   37947     ){
   37948       return 1;
   37949     }
   37950   }
   37951 
   37952   /* Failed to find the required lock. */
   37953   return 0;
   37954 }
   37955 #endif /* SQLITE_DEBUG */
   37956 
   37957 #ifdef SQLITE_DEBUG
   37958 /*
   37959 **** This function may be used as part of assert() statements only. ****
   37960 **
   37961 ** Return true if it would be illegal for pBtree to write into the
   37962 ** table or index rooted at iRoot because other shared connections are
   37963 ** simultaneously reading that same table or index.
   37964 **
   37965 ** It is illegal for pBtree to write if some other Btree object that
   37966 ** shares the same BtShared object is currently reading or writing
   37967 ** the iRoot table.  Except, if the other Btree object has the
   37968 ** read-uncommitted flag set, then it is OK for the other object to
   37969 ** have a read cursor.
   37970 **
   37971 ** For example, before writing to any part of the table or index
   37972 ** rooted at page iRoot, one should call:
   37973 **
   37974 **    assert( !hasReadConflicts(pBtree, iRoot) );
   37975 */
   37976 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
   37977   BtCursor *p;
   37978   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
   37979     if( p->pgnoRoot==iRoot
   37980      && p->pBtree!=pBtree
   37981      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
   37982     ){
   37983       return 1;
   37984     }
   37985   }
   37986   return 0;
   37987 }
   37988 #endif    /* #ifdef SQLITE_DEBUG */
   37989 
   37990 /*
   37991 ** Query to see if Btree handle p may obtain a lock of type eLock
   37992 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
   37993 ** SQLITE_OK if the lock may be obtained (by calling
   37994 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
   37995 */
   37996 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
   37997   BtShared *pBt = p->pBt;
   37998   BtLock *pIter;
   37999 
   38000   assert( sqlite3BtreeHoldsMutex(p) );
   38001   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
   38002   assert( p->db!=0 );
   38003   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
   38004 
   38005   /* If requesting a write-lock, then the Btree must have an open write
   38006   ** transaction on this file. And, obviously, for this to be so there
   38007   ** must be an open write transaction on the file itself.
   38008   */
   38009   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
   38010   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
   38011 
   38012   /* This routine is a no-op if the shared-cache is not enabled */
   38013   if( !p->sharable ){
   38014     return SQLITE_OK;
   38015   }
   38016 
   38017   /* If some other connection is holding an exclusive lock, the
   38018   ** requested lock may not be obtained.
   38019   */
   38020   if( pBt->pWriter!=p && pBt->isExclusive ){
   38021     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
   38022     return SQLITE_LOCKED_SHAREDCACHE;
   38023   }
   38024 
   38025   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   38026     /* The condition (pIter->eLock!=eLock) in the following if(...)
   38027     ** statement is a simplification of:
   38028     **
   38029     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
   38030     **
   38031     ** since we know that if eLock==WRITE_LOCK, then no other connection
   38032     ** may hold a WRITE_LOCK on any table in this file (since there can
   38033     ** only be a single writer).
   38034     */
   38035     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
   38036     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
   38037     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
   38038       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
   38039       if( eLock==WRITE_LOCK ){
   38040         assert( p==pBt->pWriter );
   38041         pBt->isPending = 1;
   38042       }
   38043       return SQLITE_LOCKED_SHAREDCACHE;
   38044     }
   38045   }
   38046   return SQLITE_OK;
   38047 }
   38048 #endif /* !SQLITE_OMIT_SHARED_CACHE */
   38049 
   38050 #ifndef SQLITE_OMIT_SHARED_CACHE
   38051 /*
   38052 ** Add a lock on the table with root-page iTable to the shared-btree used
   38053 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
   38054 ** WRITE_LOCK.
   38055 **
   38056 ** This function assumes the following:
   38057 **
   38058 **   (a) The specified Btree object p is connected to a sharable
   38059 **       database (one with the BtShared.sharable flag set), and
   38060 **
   38061 **   (b) No other Btree objects hold a lock that conflicts
   38062 **       with the requested lock (i.e. querySharedCacheTableLock() has
   38063 **       already been called and returned SQLITE_OK).
   38064 **
   38065 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
   38066 ** is returned if a malloc attempt fails.
   38067 */
   38068 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
   38069   BtShared *pBt = p->pBt;
   38070   BtLock *pLock = 0;
   38071   BtLock *pIter;
   38072 
   38073   assert( sqlite3BtreeHoldsMutex(p) );
   38074   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
   38075   assert( p->db!=0 );
   38076 
   38077   /* A connection with the read-uncommitted flag set will never try to
   38078   ** obtain a read-lock using this function. The only read-lock obtained
   38079   ** by a connection in read-uncommitted mode is on the sqlite_master
   38080   ** table, and that lock is obtained in BtreeBeginTrans().  */
   38081   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
   38082 
   38083   /* This function should only be called on a sharable b-tree after it
   38084   ** has been determined that no other b-tree holds a conflicting lock.  */
   38085   assert( p->sharable );
   38086   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
   38087 
   38088   /* First search the list for an existing lock on this table. */
   38089   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   38090     if( pIter->iTable==iTable && pIter->pBtree==p ){
   38091       pLock = pIter;
   38092       break;
   38093     }
   38094   }
   38095 
   38096   /* If the above search did not find a BtLock struct associating Btree p
   38097   ** with table iTable, allocate one and link it into the list.
   38098   */
   38099   if( !pLock ){
   38100     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
   38101     if( !pLock ){
   38102       return SQLITE_NOMEM;
   38103     }
   38104     pLock->iTable = iTable;
   38105     pLock->pBtree = p;
   38106     pLock->pNext = pBt->pLock;
   38107     pBt->pLock = pLock;
   38108   }
   38109 
   38110   /* Set the BtLock.eLock variable to the maximum of the current lock
   38111   ** and the requested lock. This means if a write-lock was already held
   38112   ** and a read-lock requested, we don't incorrectly downgrade the lock.
   38113   */
   38114   assert( WRITE_LOCK>READ_LOCK );
   38115   if( eLock>pLock->eLock ){
   38116     pLock->eLock = eLock;
   38117   }
   38118 
   38119   return SQLITE_OK;
   38120 }
   38121 #endif /* !SQLITE_OMIT_SHARED_CACHE */
   38122 
   38123 #ifndef SQLITE_OMIT_SHARED_CACHE
   38124 /*
   38125 ** Release all the table locks (locks obtained via calls to
   38126 ** the setSharedCacheTableLock() procedure) held by Btree object p.
   38127 **
   38128 ** This function assumes that Btree p has an open read or write
   38129 ** transaction. If it does not, then the BtShared.isPending variable
   38130 ** may be incorrectly cleared.
   38131 */
   38132 static void clearAllSharedCacheTableLocks(Btree *p){
   38133   BtShared *pBt = p->pBt;
   38134   BtLock **ppIter = &pBt->pLock;
   38135 
   38136   assert( sqlite3BtreeHoldsMutex(p) );
   38137   assert( p->sharable || 0==*ppIter );
   38138   assert( p->inTrans>0 );
   38139 
   38140   while( *ppIter ){
   38141     BtLock *pLock = *ppIter;
   38142     assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
   38143     assert( pLock->pBtree->inTrans>=pLock->eLock );
   38144     if( pLock->pBtree==p ){
   38145       *ppIter = pLock->pNext;
   38146       assert( pLock->iTable!=1 || pLock==&p->lock );
   38147       if( pLock->iTable!=1 ){
   38148         sqlite3_free(pLock);
   38149       }
   38150     }else{
   38151       ppIter = &pLock->pNext;
   38152     }
   38153   }
   38154 
   38155   assert( pBt->isPending==0 || pBt->pWriter );
   38156   if( pBt->pWriter==p ){
   38157     pBt->pWriter = 0;
   38158     pBt->isExclusive = 0;
   38159     pBt->isPending = 0;
   38160   }else if( pBt->nTransaction==2 ){
   38161     /* This function is called when Btree p is concluding its
   38162     ** transaction. If there currently exists a writer, and p is not
   38163     ** that writer, then the number of locks held by connections other
   38164     ** than the writer must be about to drop to zero. In this case
   38165     ** set the isPending flag to 0.
   38166     **
   38167     ** If there is not currently a writer, then BtShared.isPending must
   38168     ** be zero already. So this next line is harmless in that case.
   38169     */
   38170     pBt->isPending = 0;
   38171   }
   38172 }
   38173 
   38174 /*
   38175 ** This function changes all write-locks held by Btree p into read-locks.
   38176 */
   38177 static void downgradeAllSharedCacheTableLocks(Btree *p){
   38178   BtShared *pBt = p->pBt;
   38179   if( pBt->pWriter==p ){
   38180     BtLock *pLock;
   38181     pBt->pWriter = 0;
   38182     pBt->isExclusive = 0;
   38183     pBt->isPending = 0;
   38184     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
   38185       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
   38186       pLock->eLock = READ_LOCK;
   38187     }
   38188   }
   38189 }
   38190 
   38191 #endif /* SQLITE_OMIT_SHARED_CACHE */
   38192 
   38193 static void releasePage(MemPage *pPage);  /* Forward reference */
   38194 
   38195 /*
   38196 ***** This routine is used inside of assert() only ****
   38197 **
   38198 ** Verify that the cursor holds the mutex on its BtShared
   38199 */
   38200 #ifdef SQLITE_DEBUG
   38201 static int cursorHoldsMutex(BtCursor *p){
   38202   return sqlite3_mutex_held(p->pBt->mutex);
   38203 }
   38204 #endif
   38205 
   38206 
   38207 #ifndef SQLITE_OMIT_INCRBLOB
   38208 /*
   38209 ** Invalidate the overflow page-list cache for cursor pCur, if any.
   38210 */
   38211 static void invalidateOverflowCache(BtCursor *pCur){
   38212   assert( cursorHoldsMutex(pCur) );
   38213   sqlite3_free(pCur->aOverflow);
   38214   pCur->aOverflow = 0;
   38215 }
   38216 
   38217 /*
   38218 ** Invalidate the overflow page-list cache for all cursors opened
   38219 ** on the shared btree structure pBt.
   38220 */
   38221 static void invalidateAllOverflowCache(BtShared *pBt){
   38222   BtCursor *p;
   38223   assert( sqlite3_mutex_held(pBt->mutex) );
   38224   for(p=pBt->pCursor; p; p=p->pNext){
   38225     invalidateOverflowCache(p);
   38226   }
   38227 }
   38228 
   38229 /*
   38230 ** This function is called before modifying the contents of a table
   38231 ** to invalidate any incrblob cursors that are open on the
   38232 ** row or one of the rows being modified.
   38233 **
   38234 ** If argument isClearTable is true, then the entire contents of the
   38235 ** table is about to be deleted. In this case invalidate all incrblob
   38236 ** cursors open on any row within the table with root-page pgnoRoot.
   38237 **
   38238 ** Otherwise, if argument isClearTable is false, then the row with
   38239 ** rowid iRow is being replaced or deleted. In this case invalidate
   38240 ** only those incrblob cursors open on that specific row.
   38241 */
   38242 static void invalidateIncrblobCursors(
   38243   Btree *pBtree,          /* The database file to check */
   38244   i64 iRow,               /* The rowid that might be changing */
   38245   int isClearTable        /* True if all rows are being deleted */
   38246 ){
   38247   BtCursor *p;
   38248   BtShared *pBt = pBtree->pBt;
   38249   assert( sqlite3BtreeHoldsMutex(pBtree) );
   38250   for(p=pBt->pCursor; p; p=p->pNext){
   38251     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
   38252       p->eState = CURSOR_INVALID;
   38253     }
   38254   }
   38255 }
   38256 
   38257 #else
   38258   /* Stub functions when INCRBLOB is omitted */
   38259   #define invalidateOverflowCache(x)
   38260   #define invalidateAllOverflowCache(x)
   38261   #define invalidateIncrblobCursors(x,y,z)
   38262 #endif /* SQLITE_OMIT_INCRBLOB */
   38263 
   38264 /*
   38265 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
   38266 ** when a page that previously contained data becomes a free-list leaf
   38267 ** page.
   38268 **
   38269 ** The BtShared.pHasContent bitvec exists to work around an obscure
   38270 ** bug caused by the interaction of two useful IO optimizations surrounding
   38271 ** free-list leaf pages:
   38272 **
   38273 **   1) When all data is deleted from a page and the page becomes
   38274 **      a free-list leaf page, the page is not written to the database
   38275 **      (as free-list leaf pages contain no meaningful data). Sometimes
   38276 **      such a page is not even journalled (as it will not be modified,
   38277 **      why bother journalling it?).
   38278 **
   38279 **   2) When a free-list leaf page is reused, its content is not read
   38280 **      from the database or written to the journal file (why should it
   38281 **      be, if it is not at all meaningful?).
   38282 **
   38283 ** By themselves, these optimizations work fine and provide a handy
   38284 ** performance boost to bulk delete or insert operations. However, if
   38285 ** a page is moved to the free-list and then reused within the same
   38286 ** transaction, a problem comes up. If the page is not journalled when
   38287 ** it is moved to the free-list and it is also not journalled when it
   38288 ** is extracted from the free-list and reused, then the original data
   38289 ** may be lost. In the event of a rollback, it may not be possible
   38290 ** to restore the database to its original configuration.
   38291 **
   38292 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
   38293 ** moved to become a free-list leaf page, the corresponding bit is
   38294 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
   38295 ** optimization 2 above is omitted if the corresponding bit is already
   38296 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
   38297 ** at the end of every transaction.
   38298 */
   38299 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
   38300   int rc = SQLITE_OK;
   38301   if( !pBt->pHasContent ){
   38302     int nPage = 100;
   38303     sqlite3PagerPagecount(pBt->pPager, &nPage);
   38304     /* If sqlite3PagerPagecount() fails there is no harm because the
   38305     ** nPage variable is unchanged from its default value of 100 */
   38306     pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
   38307     if( !pBt->pHasContent ){
   38308       rc = SQLITE_NOMEM;
   38309     }
   38310   }
   38311   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
   38312     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
   38313   }
   38314   return rc;
   38315 }
   38316 
   38317 /*
   38318 ** Query the BtShared.pHasContent vector.
   38319 **
   38320 ** This function is called when a free-list leaf page is removed from the
   38321 ** free-list for reuse. It returns false if it is safe to retrieve the
   38322 ** page from the pager layer with the 'no-content' flag set. True otherwise.
   38323 */
   38324 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
   38325   Bitvec *p = pBt->pHasContent;
   38326   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
   38327 }
   38328 
   38329 /*
   38330 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
   38331 ** invoked at the conclusion of each write-transaction.
   38332 */
   38333 static void btreeClearHasContent(BtShared *pBt){
   38334   sqlite3BitvecDestroy(pBt->pHasContent);
   38335   pBt->pHasContent = 0;
   38336 }
   38337 
   38338 /*
   38339 ** Save the current cursor position in the variables BtCursor.nKey
   38340 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
   38341 **
   38342 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
   38343 ** prior to calling this routine.
   38344 */
   38345 static int saveCursorPosition(BtCursor *pCur){
   38346   int rc;
   38347 
   38348   assert( CURSOR_VALID==pCur->eState );
   38349   assert( 0==pCur->pKey );
   38350   assert( cursorHoldsMutex(pCur) );
   38351 
   38352   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
   38353   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
   38354 
   38355   /* If this is an intKey table, then the above call to BtreeKeySize()
   38356   ** stores the integer key in pCur->nKey. In this case this value is
   38357   ** all that is required. Otherwise, if pCur is not open on an intKey
   38358   ** table, then malloc space for and store the pCur->nKey bytes of key
   38359   ** data.
   38360   */
   38361   if( 0==pCur->apPage[0]->intKey ){
   38362     void *pKey = sqlite3Malloc( (int)pCur->nKey );
   38363     if( pKey ){
   38364       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
   38365       if( rc==SQLITE_OK ){
   38366         pCur->pKey = pKey;
   38367       }else{
   38368         sqlite3_free(pKey);
   38369       }
   38370     }else{
   38371       rc = SQLITE_NOMEM;
   38372     }
   38373   }
   38374   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
   38375 
   38376   if( rc==SQLITE_OK ){
   38377     int i;
   38378     for(i=0; i<=pCur->iPage; i++){
   38379       releasePage(pCur->apPage[i]);
   38380       pCur->apPage[i] = 0;
   38381     }
   38382     pCur->iPage = -1;
   38383     pCur->eState = CURSOR_REQUIRESEEK;
   38384   }
   38385 
   38386   invalidateOverflowCache(pCur);
   38387   return rc;
   38388 }
   38389 
   38390 /*
   38391 ** Save the positions of all cursors (except pExcept) that are open on
   38392 ** the table  with root-page iRoot. Usually, this is called just before cursor
   38393 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
   38394 */
   38395 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
   38396   BtCursor *p;
   38397   assert( sqlite3_mutex_held(pBt->mutex) );
   38398   assert( pExcept==0 || pExcept->pBt==pBt );
   38399   for(p=pBt->pCursor; p; p=p->pNext){
   38400     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
   38401         p->eState==CURSOR_VALID ){
   38402       int rc = saveCursorPosition(p);
   38403       if( SQLITE_OK!=rc ){
   38404         return rc;
   38405       }
   38406     }
   38407   }
   38408   return SQLITE_OK;
   38409 }
   38410 
   38411 /*
   38412 ** Clear the current cursor position.
   38413 */
   38414 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
   38415   assert( cursorHoldsMutex(pCur) );
   38416   sqlite3_free(pCur->pKey);
   38417   pCur->pKey = 0;
   38418   pCur->eState = CURSOR_INVALID;
   38419 }
   38420 
   38421 /*
   38422 ** In this version of BtreeMoveto, pKey is a packed index record
   38423 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
   38424 ** record and then call BtreeMovetoUnpacked() to do the work.
   38425 */
   38426 static int btreeMoveto(
   38427   BtCursor *pCur,     /* Cursor open on the btree to be searched */
   38428   const void *pKey,   /* Packed key if the btree is an index */
   38429   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
   38430   int bias,           /* Bias search to the high end */
   38431   int *pRes           /* Write search results here */
   38432 ){
   38433   int rc;                    /* Status code */
   38434   UnpackedRecord *pIdxKey;   /* Unpacked index key */
   38435   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
   38436 
   38437   if( pKey ){
   38438     assert( nKey==(i64)(int)nKey );
   38439     pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
   38440                                       aSpace, sizeof(aSpace));
   38441     if( pIdxKey==0 ) return SQLITE_NOMEM;
   38442   }else{
   38443     pIdxKey = 0;
   38444   }
   38445   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
   38446   if( pKey ){
   38447     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
   38448   }
   38449   return rc;
   38450 }
   38451 
   38452 /*
   38453 ** Restore the cursor to the position it was in (or as close to as possible)
   38454 ** when saveCursorPosition() was called. Note that this call deletes the
   38455 ** saved position info stored by saveCursorPosition(), so there can be
   38456 ** at most one effective restoreCursorPosition() call after each
   38457 ** saveCursorPosition().
   38458 */
   38459 static int btreeRestoreCursorPosition(BtCursor *pCur){
   38460   int rc;
   38461   assert( cursorHoldsMutex(pCur) );
   38462   assert( pCur->eState>=CURSOR_REQUIRESEEK );
   38463   if( pCur->eState==CURSOR_FAULT ){
   38464     return pCur->skipNext;
   38465   }
   38466   pCur->eState = CURSOR_INVALID;
   38467   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
   38468   if( rc==SQLITE_OK ){
   38469     sqlite3_free(pCur->pKey);
   38470     pCur->pKey = 0;
   38471     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
   38472   }
   38473   return rc;
   38474 }
   38475 
   38476 #define restoreCursorPosition(p) \
   38477   (p->eState>=CURSOR_REQUIRESEEK ? \
   38478          btreeRestoreCursorPosition(p) : \
   38479          SQLITE_OK)
   38480 
   38481 /*
   38482 ** Determine whether or not a cursor has moved from the position it
   38483 ** was last placed at.  Cursors can move when the row they are pointing
   38484 ** at is deleted out from under them.
   38485 **
   38486 ** This routine returns an error code if something goes wrong.  The
   38487 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
   38488 */
   38489 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
   38490   int rc;
   38491 
   38492   rc = restoreCursorPosition(pCur);
   38493   if( rc ){
   38494     *pHasMoved = 1;
   38495     return rc;
   38496   }
   38497   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
   38498     *pHasMoved = 1;
   38499   }else{
   38500     *pHasMoved = 0;
   38501   }
   38502   return SQLITE_OK;
   38503 }
   38504 
   38505 #ifndef SQLITE_OMIT_AUTOVACUUM
   38506 /*
   38507 ** Given a page number of a regular database page, return the page
   38508 ** number for the pointer-map page that contains the entry for the
   38509 ** input page number.
   38510 */
   38511 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
   38512   int nPagesPerMapPage;
   38513   Pgno iPtrMap, ret;
   38514   assert( sqlite3_mutex_held(pBt->mutex) );
   38515   nPagesPerMapPage = (pBt->usableSize/5)+1;
   38516   iPtrMap = (pgno-2)/nPagesPerMapPage;
   38517   ret = (iPtrMap*nPagesPerMapPage) + 2;
   38518   if( ret==PENDING_BYTE_PAGE(pBt) ){
   38519     ret++;
   38520   }
   38521   return ret;
   38522 }
   38523 
   38524 /*
   38525 ** Write an entry into the pointer map.
   38526 **
   38527 ** This routine updates the pointer map entry for page number 'key'
   38528 ** so that it maps to type 'eType' and parent page number 'pgno'.
   38529 **
   38530 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
   38531 ** a no-op.  If an error occurs, the appropriate error code is written
   38532 ** into *pRC.
   38533 */
   38534 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
   38535   DbPage *pDbPage;  /* The pointer map page */
   38536   u8 *pPtrmap;      /* The pointer map data */
   38537   Pgno iPtrmap;     /* The pointer map page number */
   38538   int offset;       /* Offset in pointer map page */
   38539   int rc;           /* Return code from subfunctions */
   38540 
   38541   if( *pRC ) return;
   38542 
   38543   assert( sqlite3_mutex_held(pBt->mutex) );
   38544   /* The master-journal page number must never be used as a pointer map page */
   38545   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
   38546 
   38547   assert( pBt->autoVacuum );
   38548   if( key==0 ){
   38549     *pRC = SQLITE_CORRUPT_BKPT;
   38550     return;
   38551   }
   38552   iPtrmap = PTRMAP_PAGENO(pBt, key);
   38553   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
   38554   if( rc!=SQLITE_OK ){
   38555     *pRC = rc;
   38556     return;
   38557   }
   38558   offset = PTRMAP_PTROFFSET(iPtrmap, key);
   38559   if( offset<0 ){
   38560     *pRC = SQLITE_CORRUPT_BKPT;
   38561     goto ptrmap_exit;
   38562   }
   38563   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
   38564 
   38565   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
   38566     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
   38567     *pRC= rc = sqlite3PagerWrite(pDbPage);
   38568     if( rc==SQLITE_OK ){
   38569       pPtrmap[offset] = eType;
   38570       put4byte(&pPtrmap[offset+1], parent);
   38571     }
   38572   }
   38573 
   38574 ptrmap_exit:
   38575   sqlite3PagerUnref(pDbPage);
   38576 }
   38577 
   38578 /*
   38579 ** Read an entry from the pointer map.
   38580 **
   38581 ** This routine retrieves the pointer map entry for page 'key', writing
   38582 ** the type and parent page number to *pEType and *pPgno respectively.
   38583 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
   38584 */
   38585 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
   38586   DbPage *pDbPage;   /* The pointer map page */
   38587   int iPtrmap;       /* Pointer map page index */
   38588   u8 *pPtrmap;       /* Pointer map page data */
   38589   int offset;        /* Offset of entry in pointer map */
   38590   int rc;
   38591 
   38592   assert( sqlite3_mutex_held(pBt->mutex) );
   38593 
   38594   iPtrmap = PTRMAP_PAGENO(pBt, key);
   38595   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
   38596   if( rc!=0 ){
   38597     return rc;
   38598   }
   38599   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
   38600 
   38601   offset = PTRMAP_PTROFFSET(iPtrmap, key);
   38602   assert( pEType!=0 );
   38603   *pEType = pPtrmap[offset];
   38604   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
   38605 
   38606   sqlite3PagerUnref(pDbPage);
   38607   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
   38608   return SQLITE_OK;
   38609 }
   38610 
   38611 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
   38612   #define ptrmapPut(w,x,y,z,rc)
   38613   #define ptrmapGet(w,x,y,z) SQLITE_OK
   38614   #define ptrmapPutOvflPtr(x, y, rc)
   38615 #endif
   38616 
   38617 /*
   38618 ** Given a btree page and a cell index (0 means the first cell on
   38619 ** the page, 1 means the second cell, and so forth) return a pointer
   38620 ** to the cell content.
   38621 **
   38622 ** This routine works only for pages that do not contain overflow cells.
   38623 */
   38624 #define findCell(P,I) \
   38625   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
   38626 
   38627 /*
   38628 ** This a more complex version of findCell() that works for
   38629 ** pages that do contain overflow cells.
   38630 */
   38631 static u8 *findOverflowCell(MemPage *pPage, int iCell){
   38632   int i;
   38633   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   38634   for(i=pPage->nOverflow-1; i>=0; i--){
   38635     int k;
   38636     struct _OvflCell *pOvfl;
   38637     pOvfl = &pPage->aOvfl[i];
   38638     k = pOvfl->idx;
   38639     if( k<=iCell ){
   38640       if( k==iCell ){
   38641         return pOvfl->pCell;
   38642       }
   38643       iCell--;
   38644     }
   38645   }
   38646   return findCell(pPage, iCell);
   38647 }
   38648 
   38649 /*
   38650 ** Parse a cell content block and fill in the CellInfo structure.  There
   38651 ** are two versions of this function.  btreeParseCell() takes a
   38652 ** cell index as the second argument and btreeParseCellPtr()
   38653 ** takes a pointer to the body of the cell as its second argument.
   38654 **
   38655 ** Within this file, the parseCell() macro can be called instead of
   38656 ** btreeParseCellPtr(). Using some compilers, this will be faster.
   38657 */
   38658 static void btreeParseCellPtr(
   38659   MemPage *pPage,         /* Page containing the cell */
   38660   u8 *pCell,              /* Pointer to the cell text. */
   38661   CellInfo *pInfo         /* Fill in this structure */
   38662 ){
   38663   u16 n;                  /* Number bytes in cell content header */
   38664   u32 nPayload;           /* Number of bytes of cell payload */
   38665 
   38666   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   38667 
   38668   pInfo->pCell = pCell;
   38669   assert( pPage->leaf==0 || pPage->leaf==1 );
   38670   n = pPage->childPtrSize;
   38671   assert( n==4-4*pPage->leaf );
   38672   if( pPage->intKey ){
   38673     if( pPage->hasData ){
   38674       n += getVarint32(&pCell[n], nPayload);
   38675     }else{
   38676       nPayload = 0;
   38677     }
   38678     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
   38679     pInfo->nData = nPayload;
   38680   }else{
   38681     pInfo->nData = 0;
   38682     n += getVarint32(&pCell[n], nPayload);
   38683     pInfo->nKey = nPayload;
   38684   }
   38685   pInfo->nPayload = nPayload;
   38686   pInfo->nHeader = n;
   38687   testcase( nPayload==pPage->maxLocal );
   38688   testcase( nPayload==pPage->maxLocal+1 );
   38689   if( likely(nPayload<=pPage->maxLocal) ){
   38690     /* This is the (easy) common case where the entire payload fits
   38691     ** on the local page.  No overflow is required.
   38692     */
   38693     int nSize;          /* Total size of cell content in bytes */
   38694     nSize = nPayload + n;
   38695     pInfo->nLocal = (u16)nPayload;
   38696     pInfo->iOverflow = 0;
   38697     if( (nSize & ~3)==0 ){
   38698       nSize = 4;        /* Minimum cell size is 4 */
   38699     }
   38700     pInfo->nSize = (u16)nSize;
   38701   }else{
   38702     /* If the payload will not fit completely on the local page, we have
   38703     ** to decide how much to store locally and how much to spill onto
   38704     ** overflow pages.  The strategy is to minimize the amount of unused
   38705     ** space on overflow pages while keeping the amount of local storage
   38706     ** in between minLocal and maxLocal.
   38707     **
   38708     ** Warning:  changing the way overflow payload is distributed in any
   38709     ** way will result in an incompatible file format.
   38710     */
   38711     int minLocal;  /* Minimum amount of payload held locally */
   38712     int maxLocal;  /* Maximum amount of payload held locally */
   38713     int surplus;   /* Overflow payload available for local storage */
   38714 
   38715     minLocal = pPage->minLocal;
   38716     maxLocal = pPage->maxLocal;
   38717     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
   38718     testcase( surplus==maxLocal );
   38719     testcase( surplus==maxLocal+1 );
   38720     if( surplus <= maxLocal ){
   38721       pInfo->nLocal = (u16)surplus;
   38722     }else{
   38723       pInfo->nLocal = (u16)minLocal;
   38724     }
   38725     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
   38726     pInfo->nSize = pInfo->iOverflow + 4;
   38727   }
   38728 }
   38729 #define parseCell(pPage, iCell, pInfo) \
   38730   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
   38731 static void btreeParseCell(
   38732   MemPage *pPage,         /* Page containing the cell */
   38733   int iCell,              /* The cell index.  First cell is 0 */
   38734   CellInfo *pInfo         /* Fill in this structure */
   38735 ){
   38736   parseCell(pPage, iCell, pInfo);
   38737 }
   38738 
   38739 /*
   38740 ** Compute the total number of bytes that a Cell needs in the cell
   38741 ** data area of the btree-page.  The return number includes the cell
   38742 ** data header and the local payload, but not any overflow page or
   38743 ** the space used by the cell pointer.
   38744 */
   38745 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
   38746   u8 *pIter = &pCell[pPage->childPtrSize];
   38747   u32 nSize;
   38748 
   38749 #ifdef SQLITE_DEBUG
   38750   /* The value returned by this function should always be the same as
   38751   ** the (CellInfo.nSize) value found by doing a full parse of the
   38752   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
   38753   ** this function verifies that this invariant is not violated. */
   38754   CellInfo debuginfo;
   38755   btreeParseCellPtr(pPage, pCell, &debuginfo);
   38756 #endif
   38757 
   38758   if( pPage->intKey ){
   38759     u8 *pEnd;
   38760     if( pPage->hasData ){
   38761       pIter += getVarint32(pIter, nSize);
   38762     }else{
   38763       nSize = 0;
   38764     }
   38765 
   38766     /* pIter now points at the 64-bit integer key value, a variable length
   38767     ** integer. The following block moves pIter to point at the first byte
   38768     ** past the end of the key value. */
   38769     pEnd = &pIter[9];
   38770     while( (*pIter++)&0x80 && pIter<pEnd );
   38771   }else{
   38772     pIter += getVarint32(pIter, nSize);
   38773   }
   38774 
   38775   testcase( nSize==pPage->maxLocal );
   38776   testcase( nSize==pPage->maxLocal+1 );
   38777   if( nSize>pPage->maxLocal ){
   38778     int minLocal = pPage->minLocal;
   38779     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
   38780     testcase( nSize==pPage->maxLocal );
   38781     testcase( nSize==pPage->maxLocal+1 );
   38782     if( nSize>pPage->maxLocal ){
   38783       nSize = minLocal;
   38784     }
   38785     nSize += 4;
   38786   }
   38787   nSize += (u32)(pIter - pCell);
   38788 
   38789   /* The minimum size of any cell is 4 bytes. */
   38790   if( nSize<4 ){
   38791     nSize = 4;
   38792   }
   38793 
   38794   assert( nSize==debuginfo.nSize );
   38795   return (u16)nSize;
   38796 }
   38797 
   38798 #ifdef SQLITE_DEBUG
   38799 /* This variation on cellSizePtr() is used inside of assert() statements
   38800 ** only. */
   38801 static u16 cellSize(MemPage *pPage, int iCell){
   38802   return cellSizePtr(pPage, findCell(pPage, iCell));
   38803 }
   38804 #endif
   38805 
   38806 #ifndef SQLITE_OMIT_AUTOVACUUM
   38807 /*
   38808 ** If the cell pCell, part of page pPage contains a pointer
   38809 ** to an overflow page, insert an entry into the pointer-map
   38810 ** for the overflow page.
   38811 */
   38812 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
   38813   CellInfo info;
   38814   if( *pRC ) return;
   38815   assert( pCell!=0 );
   38816   btreeParseCellPtr(pPage, pCell, &info);
   38817   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
   38818   if( info.iOverflow ){
   38819     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
   38820     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
   38821   }
   38822 }
   38823 #endif
   38824 
   38825 
   38826 /*
   38827 ** Defragment the page given.  All Cells are moved to the
   38828 ** end of the page and all free space is collected into one
   38829 ** big FreeBlk that occurs in between the header and cell
   38830 ** pointer array and the cell content area.
   38831 */
   38832 static int defragmentPage(MemPage *pPage){
   38833   int i;                     /* Loop counter */
   38834   int pc;                    /* Address of a i-th cell */
   38835   int hdr;                   /* Offset to the page header */
   38836   int size;                  /* Size of a cell */
   38837   int usableSize;            /* Number of usable bytes on a page */
   38838   int cellOffset;            /* Offset to the cell pointer array */
   38839   int cbrk;                  /* Offset to the cell content area */
   38840   int nCell;                 /* Number of cells on the page */
   38841   unsigned char *data;       /* The page data */
   38842   unsigned char *temp;       /* Temp area for cell content */
   38843   int iCellFirst;            /* First allowable cell index */
   38844   int iCellLast;             /* Last possible cell index */
   38845 
   38846 
   38847   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   38848   assert( pPage->pBt!=0 );
   38849   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
   38850   assert( pPage->nOverflow==0 );
   38851   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   38852   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
   38853   data = pPage->aData;
   38854   hdr = pPage->hdrOffset;
   38855   cellOffset = pPage->cellOffset;
   38856   nCell = pPage->nCell;
   38857   assert( nCell==get2byte(&data[hdr+3]) );
   38858   usableSize = pPage->pBt->usableSize;
   38859   cbrk = get2byte(&data[hdr+5]);
   38860   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
   38861   cbrk = usableSize;
   38862   iCellFirst = cellOffset + 2*nCell;
   38863   iCellLast = usableSize - 4;
   38864   for(i=0; i<nCell; i++){
   38865     u8 *pAddr;     /* The i-th cell pointer */
   38866     pAddr = &data[cellOffset + i*2];
   38867     pc = get2byte(pAddr);
   38868     testcase( pc==iCellFirst );
   38869     testcase( pc==iCellLast );
   38870 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   38871     /* These conditions have already been verified in btreeInitPage()
   38872     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
   38873     */
   38874     if( pc<iCellFirst || pc>iCellLast ){
   38875       return SQLITE_CORRUPT_BKPT;
   38876     }
   38877 #endif
   38878     assert( pc>=iCellFirst && pc<=iCellLast );
   38879     size = cellSizePtr(pPage, &temp[pc]);
   38880     cbrk -= size;
   38881 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   38882     if( cbrk<iCellFirst ){
   38883       return SQLITE_CORRUPT_BKPT;
   38884     }
   38885 #else
   38886     if( cbrk<iCellFirst || pc+size>usableSize ){
   38887       return SQLITE_CORRUPT_BKPT;
   38888     }
   38889 #endif
   38890     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
   38891     testcase( cbrk+size==usableSize );
   38892     testcase( pc+size==usableSize );
   38893     memcpy(&data[cbrk], &temp[pc], size);
   38894     put2byte(pAddr, cbrk);
   38895   }
   38896   assert( cbrk>=iCellFirst );
   38897   put2byte(&data[hdr+5], cbrk);
   38898   data[hdr+1] = 0;
   38899   data[hdr+2] = 0;
   38900   data[hdr+7] = 0;
   38901   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
   38902   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   38903   if( cbrk-iCellFirst!=pPage->nFree ){
   38904     return SQLITE_CORRUPT_BKPT;
   38905   }
   38906   return SQLITE_OK;
   38907 }
   38908 
   38909 /*
   38910 ** Allocate nByte bytes of space from within the B-Tree page passed
   38911 ** as the first argument. Write into *pIdx the index into pPage->aData[]
   38912 ** of the first byte of allocated space. Return either SQLITE_OK or
   38913 ** an error code (usually SQLITE_CORRUPT).
   38914 **
   38915 ** The caller guarantees that there is sufficient space to make the
   38916 ** allocation.  This routine might need to defragment in order to bring
   38917 ** all the space together, however.  This routine will avoid using
   38918 ** the first two bytes past the cell pointer area since presumably this
   38919 ** allocation is being made in order to insert a new cell, so we will
   38920 ** also end up needing a new cell pointer.
   38921 */
   38922 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
   38923   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
   38924   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
   38925   int nFrag;                           /* Number of fragmented bytes on pPage */
   38926   int top;                             /* First byte of cell content area */
   38927   int gap;        /* First byte of gap between cell pointers and cell content */
   38928   int rc;         /* Integer return code */
   38929   int usableSize; /* Usable size of the page */
   38930 
   38931   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   38932   assert( pPage->pBt );
   38933   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   38934   assert( nByte>=0 );  /* Minimum cell size is 4 */
   38935   assert( pPage->nFree>=nByte );
   38936   assert( pPage->nOverflow==0 );
   38937   usableSize = pPage->pBt->usableSize;
   38938   assert( nByte < usableSize-8 );
   38939 
   38940   nFrag = data[hdr+7];
   38941   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
   38942   gap = pPage->cellOffset + 2*pPage->nCell;
   38943   top = get2byte(&data[hdr+5]);
   38944   if( gap>top ) return SQLITE_CORRUPT_BKPT;
   38945   testcase( gap+2==top );
   38946   testcase( gap+1==top );
   38947   testcase( gap==top );
   38948 
   38949   if( nFrag>=60 ){
   38950     /* Always defragment highly fragmented pages */
   38951     rc = defragmentPage(pPage);
   38952     if( rc ) return rc;
   38953     top = get2byte(&data[hdr+5]);
   38954   }else if( gap+2<=top ){
   38955     /* Search the freelist looking for a free slot big enough to satisfy
   38956     ** the request. The allocation is made from the first free slot in
   38957     ** the list that is large enough to accomadate it.
   38958     */
   38959     int pc, addr;
   38960     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
   38961       int size;            /* Size of the free slot */
   38962       if( pc>usableSize-4 || pc<addr+4 ){
   38963         return SQLITE_CORRUPT_BKPT;
   38964       }
   38965       size = get2byte(&data[pc+2]);
   38966       if( size>=nByte ){
   38967         int x = size - nByte;
   38968         testcase( x==4 );
   38969         testcase( x==3 );
   38970         if( x<4 ){
   38971           /* Remove the slot from the free-list. Update the number of
   38972           ** fragmented bytes within the page. */
   38973           memcpy(&data[addr], &data[pc], 2);
   38974           data[hdr+7] = (u8)(nFrag + x);
   38975         }else if( size+pc > usableSize ){
   38976           return SQLITE_CORRUPT_BKPT;
   38977         }else{
   38978           /* The slot remains on the free-list. Reduce its size to account
   38979           ** for the portion used by the new allocation. */
   38980           put2byte(&data[pc+2], x);
   38981         }
   38982         *pIdx = pc + x;
   38983         return SQLITE_OK;
   38984       }
   38985     }
   38986   }
   38987 
   38988   /* Check to make sure there is enough space in the gap to satisfy
   38989   ** the allocation.  If not, defragment.
   38990   */
   38991   testcase( gap+2+nByte==top );
   38992   if( gap+2+nByte>top ){
   38993     rc = defragmentPage(pPage);
   38994     if( rc ) return rc;
   38995     top = get2byte(&data[hdr+5]);
   38996     assert( gap+nByte<=top );
   38997   }
   38998 
   38999 
   39000   /* Allocate memory from the gap in between the cell pointer array
   39001   ** and the cell content area.  The btreeInitPage() call has already
   39002   ** validated the freelist.  Given that the freelist is valid, there
   39003   ** is no way that the allocation can extend off the end of the page.
   39004   ** The assert() below verifies the previous sentence.
   39005   */
   39006   top -= nByte;
   39007   put2byte(&data[hdr+5], top);
   39008   assert( top+nByte <= pPage->pBt->usableSize );
   39009   *pIdx = top;
   39010   return SQLITE_OK;
   39011 }
   39012 
   39013 /*
   39014 ** Return a section of the pPage->aData to the freelist.
   39015 ** The first byte of the new free block is pPage->aDisk[start]
   39016 ** and the size of the block is "size" bytes.
   39017 **
   39018 ** Most of the effort here is involved in coalesing adjacent
   39019 ** free blocks into a single big free block.
   39020 */
   39021 static int freeSpace(MemPage *pPage, int start, int size){
   39022   int addr, pbegin, hdr;
   39023   int iLast;                        /* Largest possible freeblock offset */
   39024   unsigned char *data = pPage->aData;
   39025 
   39026   assert( pPage->pBt!=0 );
   39027   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   39028   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
   39029   assert( (start + size)<=pPage->pBt->usableSize );
   39030   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   39031   assert( size>=0 );   /* Minimum cell size is 4 */
   39032 
   39033 #ifdef SQLITE_SECURE_DELETE
   39034   /* Overwrite deleted information with zeros when the SECURE_DELETE
   39035   ** option is enabled at compile-time */
   39036   memset(&data[start], 0, size);
   39037 #endif
   39038 
   39039   /* Add the space back into the linked list of freeblocks.  Note that
   39040   ** even though the freeblock list was checked by btreeInitPage(),
   39041   ** btreeInitPage() did not detect overlapping cells or
   39042   ** freeblocks that overlapped cells.   Nor does it detect when the
   39043   ** cell content area exceeds the value in the page header.  If these
   39044   ** situations arise, then subsequent insert operations might corrupt
   39045   ** the freelist.  So we do need to check for corruption while scanning
   39046   ** the freelist.
   39047   */
   39048   hdr = pPage->hdrOffset;
   39049   addr = hdr + 1;
   39050   iLast = pPage->pBt->usableSize - 4;
   39051   assert( start<=iLast );
   39052   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
   39053     if( pbegin<addr+4 ){
   39054       return SQLITE_CORRUPT_BKPT;
   39055     }
   39056     addr = pbegin;
   39057   }
   39058   if( pbegin>iLast ){
   39059     return SQLITE_CORRUPT_BKPT;
   39060   }
   39061   assert( pbegin>addr || pbegin==0 );
   39062   put2byte(&data[addr], start);
   39063   put2byte(&data[start], pbegin);
   39064   put2byte(&data[start+2], size);
   39065   pPage->nFree = pPage->nFree + (u16)size;
   39066 
   39067   /* Coalesce adjacent free blocks */
   39068   addr = hdr + 1;
   39069   while( (pbegin = get2byte(&data[addr]))>0 ){
   39070     int pnext, psize, x;
   39071     assert( pbegin>addr );
   39072     assert( pbegin<=pPage->pBt->usableSize-4 );
   39073     pnext = get2byte(&data[pbegin]);
   39074     psize = get2byte(&data[pbegin+2]);
   39075     if( pbegin + psize + 3 >= pnext && pnext>0 ){
   39076       int frag = pnext - (pbegin+psize);
   39077       if( (frag<0) || (frag>(int)data[hdr+7]) ){
   39078         return SQLITE_CORRUPT_BKPT;
   39079       }
   39080       data[hdr+7] -= (u8)frag;
   39081       x = get2byte(&data[pnext]);
   39082       put2byte(&data[pbegin], x);
   39083       x = pnext + get2byte(&data[pnext+2]) - pbegin;
   39084       put2byte(&data[pbegin+2], x);
   39085     }else{
   39086       addr = pbegin;
   39087     }
   39088   }
   39089 
   39090   /* If the cell content area begins with a freeblock, remove it. */
   39091   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
   39092     int top;
   39093     pbegin = get2byte(&data[hdr+1]);
   39094     memcpy(&data[hdr+1], &data[pbegin], 2);
   39095     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
   39096     put2byte(&data[hdr+5], top);
   39097   }
   39098   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   39099   return SQLITE_OK;
   39100 }
   39101 
   39102 /*
   39103 ** Decode the flags byte (the first byte of the header) for a page
   39104 ** and initialize fields of the MemPage structure accordingly.
   39105 **
   39106 ** Only the following combinations are supported.  Anything different
   39107 ** indicates a corrupt database files:
   39108 **
   39109 **         PTF_ZERODATA
   39110 **         PTF_ZERODATA | PTF_LEAF
   39111 **         PTF_LEAFDATA | PTF_INTKEY
   39112 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
   39113 */
   39114 static int decodeFlags(MemPage *pPage, int flagByte){
   39115   BtShared *pBt;     /* A copy of pPage->pBt */
   39116 
   39117   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
   39118   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   39119   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
   39120   flagByte &= ~PTF_LEAF;
   39121   pPage->childPtrSize = 4-4*pPage->leaf;
   39122   pBt = pPage->pBt;
   39123   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
   39124     pPage->intKey = 1;
   39125     pPage->hasData = pPage->leaf;
   39126     pPage->maxLocal = pBt->maxLeaf;
   39127     pPage->minLocal = pBt->minLeaf;
   39128   }else if( flagByte==PTF_ZERODATA ){
   39129     pPage->intKey = 0;
   39130     pPage->hasData = 0;
   39131     pPage->maxLocal = pBt->maxLocal;
   39132     pPage->minLocal = pBt->minLocal;
   39133   }else{
   39134     return SQLITE_CORRUPT_BKPT;
   39135   }
   39136   return SQLITE_OK;
   39137 }
   39138 
   39139 /*
   39140 ** Initialize the auxiliary information for a disk block.
   39141 **
   39142 ** Return SQLITE_OK on success.  If we see that the page does
   39143 ** not contain a well-formed database page, then return
   39144 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
   39145 ** guarantee that the page is well-formed.  It only shows that
   39146 ** we failed to detect any corruption.
   39147 */
   39148 static int btreeInitPage(MemPage *pPage){
   39149 
   39150   assert( pPage->pBt!=0 );
   39151   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   39152   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
   39153   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
   39154   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
   39155 
   39156   if( !pPage->isInit ){
   39157     u16 pc;            /* Address of a freeblock within pPage->aData[] */
   39158     u8 hdr;            /* Offset to beginning of page header */
   39159     u8 *data;          /* Equal to pPage->aData */
   39160     BtShared *pBt;        /* The main btree structure */
   39161     u16 usableSize;    /* Amount of usable space on each page */
   39162     u16 cellOffset;    /* Offset from start of page to first cell pointer */
   39163     u16 nFree;         /* Number of unused bytes on the page */
   39164     u16 top;           /* First byte of the cell content area */
   39165     int iCellFirst;    /* First allowable cell or freeblock offset */
   39166     int iCellLast;     /* Last possible cell or freeblock offset */
   39167 
   39168     pBt = pPage->pBt;
   39169 
   39170     hdr = pPage->hdrOffset;
   39171     data = pPage->aData;
   39172     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
   39173     assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
   39174     pPage->maskPage = pBt->pageSize - 1;
   39175     pPage->nOverflow = 0;
   39176     usableSize = pBt->usableSize;
   39177     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
   39178     top = get2byte(&data[hdr+5]);
   39179     pPage->nCell = get2byte(&data[hdr+3]);
   39180     if( pPage->nCell>MX_CELL(pBt) ){
   39181       /* To many cells for a single page.  The page must be corrupt */
   39182       return SQLITE_CORRUPT_BKPT;
   39183     }
   39184     testcase( pPage->nCell==MX_CELL(pBt) );
   39185 
   39186     /* A malformed database page might cause us to read past the end
   39187     ** of page when parsing a cell.
   39188     **
   39189     ** The following block of code checks early to see if a cell extends
   39190     ** past the end of a page boundary and causes SQLITE_CORRUPT to be
   39191     ** returned if it does.
   39192     */
   39193     iCellFirst = cellOffset + 2*pPage->nCell;
   39194     iCellLast = usableSize - 4;
   39195 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   39196     {
   39197       int i;            /* Index into the cell pointer array */
   39198       int sz;           /* Size of a cell */
   39199 
   39200       if( !pPage->leaf ) iCellLast--;
   39201       for(i=0; i<pPage->nCell; i++){
   39202         pc = get2byte(&data[cellOffset+i*2]);
   39203         testcase( pc==iCellFirst );
   39204         testcase( pc==iCellLast );
   39205         if( pc<iCellFirst || pc>iCellLast ){
   39206           return SQLITE_CORRUPT_BKPT;
   39207         }
   39208         sz = cellSizePtr(pPage, &data[pc]);
   39209         testcase( pc+sz==usableSize );
   39210         if( pc+sz>usableSize ){
   39211           return SQLITE_CORRUPT_BKPT;
   39212         }
   39213       }
   39214       if( !pPage->leaf ) iCellLast++;
   39215     }
   39216 #endif
   39217 
   39218     /* Compute the total free space on the page */
   39219     pc = get2byte(&data[hdr+1]);
   39220     nFree = data[hdr+7] + top;
   39221     while( pc>0 ){
   39222       u16 next, size;
   39223       if( pc<iCellFirst || pc>iCellLast ){
   39224         /* Start of free block is off the page */
   39225         return SQLITE_CORRUPT_BKPT;
   39226       }
   39227       next = get2byte(&data[pc]);
   39228       size = get2byte(&data[pc+2]);
   39229       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
   39230         /* Free blocks must be in ascending order. And the last byte of
   39231 	** the free-block must lie on the database page.  */
   39232         return SQLITE_CORRUPT_BKPT;
   39233       }
   39234       nFree = nFree + size;
   39235       pc = next;
   39236     }
   39237 
   39238     /* At this point, nFree contains the sum of the offset to the start
   39239     ** of the cell-content area plus the number of free bytes within
   39240     ** the cell-content area. If this is greater than the usable-size
   39241     ** of the page, then the page must be corrupted. This check also
   39242     ** serves to verify that the offset to the start of the cell-content
   39243     ** area, according to the page header, lies within the page.
   39244     */
   39245     if( nFree>usableSize ){
   39246       return SQLITE_CORRUPT_BKPT;
   39247     }
   39248     pPage->nFree = (u16)(nFree - iCellFirst);
   39249     pPage->isInit = 1;
   39250   }
   39251   return SQLITE_OK;
   39252 }
   39253 
   39254 /*
   39255 ** Set up a raw page so that it looks like a database page holding
   39256 ** no entries.
   39257 */
   39258 static void zeroPage(MemPage *pPage, int flags){
   39259   unsigned char *data = pPage->aData;
   39260   BtShared *pBt = pPage->pBt;
   39261   u8 hdr = pPage->hdrOffset;
   39262   u16 first;
   39263 
   39264   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
   39265   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
   39266   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
   39267   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   39268   assert( sqlite3_mutex_held(pBt->mutex) );
   39269 #ifdef SQLITE_SECURE_DELETE
   39270   memset(&data[hdr], 0, pBt->usableSize - hdr);
   39271 #endif
   39272   data[hdr] = (char)flags;
   39273   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
   39274   memset(&data[hdr+1], 0, 4);
   39275   data[hdr+7] = 0;
   39276   put2byte(&data[hdr+5], pBt->usableSize);
   39277   pPage->nFree = pBt->usableSize - first;
   39278   decodeFlags(pPage, flags);
   39279   pPage->hdrOffset = hdr;
   39280   pPage->cellOffset = first;
   39281   pPage->nOverflow = 0;
   39282   assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
   39283   pPage->maskPage = pBt->pageSize - 1;
   39284   pPage->nCell = 0;
   39285   pPage->isInit = 1;
   39286 }
   39287 
   39288 
   39289 /*
   39290 ** Convert a DbPage obtained from the pager into a MemPage used by
   39291 ** the btree layer.
   39292 */
   39293 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
   39294   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
   39295   pPage->aData = sqlite3PagerGetData(pDbPage);
   39296   pPage->pDbPage = pDbPage;
   39297   pPage->pBt = pBt;
   39298   pPage->pgno = pgno;
   39299   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
   39300   return pPage;
   39301 }
   39302 
   39303 /*
   39304 ** Get a page from the pager.  Initialize the MemPage.pBt and
   39305 ** MemPage.aData elements if needed.
   39306 **
   39307 ** If the noContent flag is set, it means that we do not care about
   39308 ** the content of the page at this time.  So do not go to the disk
   39309 ** to fetch the content.  Just fill in the content with zeros for now.
   39310 ** If in the future we call sqlite3PagerWrite() on this page, that
   39311 ** means we have started to be concerned about content and the disk
   39312 ** read should occur at that point.
   39313 */
   39314 static int btreeGetPage(
   39315   BtShared *pBt,       /* The btree */
   39316   Pgno pgno,           /* Number of the page to fetch */
   39317   MemPage **ppPage,    /* Return the page in this parameter */
   39318   int noContent        /* Do not load page content if true */
   39319 ){
   39320   int rc;
   39321   DbPage *pDbPage;
   39322 
   39323   assert( sqlite3_mutex_held(pBt->mutex) );
   39324   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
   39325   if( rc ) return rc;
   39326   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
   39327   return SQLITE_OK;
   39328 }
   39329 
   39330 /*
   39331 ** Retrieve a page from the pager cache. If the requested page is not
   39332 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
   39333 ** MemPage.aData elements if needed.
   39334 */
   39335 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
   39336   DbPage *pDbPage;
   39337   assert( sqlite3_mutex_held(pBt->mutex) );
   39338   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
   39339   if( pDbPage ){
   39340     return btreePageFromDbPage(pDbPage, pgno, pBt);
   39341   }
   39342   return 0;
   39343 }
   39344 
   39345 /*
   39346 ** Return the size of the database file in pages. If there is any kind of
   39347 ** error, return ((unsigned int)-1).
   39348 */
   39349 static Pgno pagerPagecount(BtShared *pBt){
   39350   int nPage = -1;
   39351   int rc;
   39352   assert( pBt->pPage1 );
   39353   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
   39354   assert( rc==SQLITE_OK || nPage==-1 );
   39355   return (Pgno)nPage;
   39356 }
   39357 
   39358 /*
   39359 ** Get a page from the pager and initialize it.  This routine is just a
   39360 ** convenience wrapper around separate calls to btreeGetPage() and
   39361 ** btreeInitPage().
   39362 **
   39363 ** If an error occurs, then the value *ppPage is set to is undefined. It
   39364 ** may remain unchanged, or it may be set to an invalid value.
   39365 */
   39366 static int getAndInitPage(
   39367   BtShared *pBt,          /* The database file */
   39368   Pgno pgno,           /* Number of the page to get */
   39369   MemPage **ppPage     /* Write the page pointer here */
   39370 ){
   39371   int rc;
   39372   TESTONLY( Pgno iLastPg = pagerPagecount(pBt); )
   39373   assert( sqlite3_mutex_held(pBt->mutex) );
   39374 
   39375   rc = btreeGetPage(pBt, pgno, ppPage, 0);
   39376   if( rc==SQLITE_OK ){
   39377     rc = btreeInitPage(*ppPage);
   39378     if( rc!=SQLITE_OK ){
   39379       releasePage(*ppPage);
   39380     }
   39381   }
   39382 
   39383   /* If the requested page number was either 0 or greater than the page
   39384   ** number of the last page in the database, this function should return
   39385   ** SQLITE_CORRUPT or some other error (i.e. SQLITE_FULL). Check that this
   39386   ** is the case.  */
   39387   assert( (pgno>0 && pgno<=iLastPg) || rc!=SQLITE_OK );
   39388   testcase( pgno==0 );
   39389   testcase( pgno==iLastPg );
   39390 
   39391   return rc;
   39392 }
   39393 
   39394 /*
   39395 ** Release a MemPage.  This should be called once for each prior
   39396 ** call to btreeGetPage.
   39397 */
   39398 static void releasePage(MemPage *pPage){
   39399   if( pPage ){
   39400     assert( pPage->aData );
   39401     assert( pPage->pBt );
   39402     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
   39403     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
   39404     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   39405     sqlite3PagerUnref(pPage->pDbPage);
   39406   }
   39407 }
   39408 
   39409 /*
   39410 ** During a rollback, when the pager reloads information into the cache
   39411 ** so that the cache is restored to its original state at the start of
   39412 ** the transaction, for each page restored this routine is called.
   39413 **
   39414 ** This routine needs to reset the extra data section at the end of the
   39415 ** page to agree with the restored data.
   39416 */
   39417 static void pageReinit(DbPage *pData){
   39418   MemPage *pPage;
   39419   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
   39420   assert( sqlite3PagerPageRefcount(pData)>0 );
   39421   if( pPage->isInit ){
   39422     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   39423     pPage->isInit = 0;
   39424     if( sqlite3PagerPageRefcount(pData)>1 ){
   39425       /* pPage might not be a btree page;  it might be an overflow page
   39426       ** or ptrmap page or a free page.  In those cases, the following
   39427       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
   39428       ** But no harm is done by this.  And it is very important that
   39429       ** btreeInitPage() be called on every btree page so we make
   39430       ** the call for every page that comes in for re-initing. */
   39431       btreeInitPage(pPage);
   39432     }
   39433   }
   39434 }
   39435 
   39436 /*
   39437 ** Invoke the busy handler for a btree.
   39438 */
   39439 static int btreeInvokeBusyHandler(void *pArg){
   39440   BtShared *pBt = (BtShared*)pArg;
   39441   assert( pBt->db );
   39442   assert( sqlite3_mutex_held(pBt->db->mutex) );
   39443   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
   39444 }
   39445 
   39446 /*
   39447 ** Open a database file.
   39448 **
   39449 ** zFilename is the name of the database file.  If zFilename is NULL
   39450 ** a new database with a random name is created.  This randomly named
   39451 ** database file will be deleted when sqlite3BtreeClose() is called.
   39452 ** If zFilename is ":memory:" then an in-memory database is created
   39453 ** that is automatically destroyed when it is closed.
   39454 **
   39455 ** If the database is already opened in the same database connection
   39456 ** and we are in shared cache mode, then the open will fail with an
   39457 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
   39458 ** objects in the same database connection since doing so will lead
   39459 ** to problems with locking.
   39460 */
   39461 SQLITE_PRIVATE int sqlite3BtreeOpen(
   39462   const char *zFilename,  /* Name of the file containing the BTree database */
   39463   sqlite3 *db,            /* Associated database handle */
   39464   Btree **ppBtree,        /* Pointer to new Btree object written here */
   39465   int flags,              /* Options */
   39466   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
   39467 ){
   39468   sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
   39469   BtShared *pBt = 0;             /* Shared part of btree structure */
   39470   Btree *p;                      /* Handle to return */
   39471   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
   39472   int rc = SQLITE_OK;            /* Result code from this function */
   39473   u8 nReserve;                   /* Byte of unused space on each page */
   39474   unsigned char zDbHeader[100];  /* Database header content */
   39475 
   39476   /* Set the variable isMemdb to true for an in-memory database, or
   39477   ** false for a file-based database. This symbol is only required if
   39478   ** either of the shared-data or autovacuum features are compiled
   39479   ** into the library.
   39480   */
   39481 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
   39482   #ifdef SQLITE_OMIT_MEMORYDB
   39483     const int isMemdb = 0;
   39484   #else
   39485     const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
   39486   #endif
   39487 #endif
   39488 
   39489   assert( db!=0 );
   39490   assert( sqlite3_mutex_held(db->mutex) );
   39491 
   39492   pVfs = db->pVfs;
   39493   p = sqlite3MallocZero(sizeof(Btree));
   39494   if( !p ){
   39495     return SQLITE_NOMEM;
   39496   }
   39497   p->inTrans = TRANS_NONE;
   39498   p->db = db;
   39499 #ifndef SQLITE_OMIT_SHARED_CACHE
   39500   p->lock.pBtree = p;
   39501   p->lock.iTable = 1;
   39502 #endif
   39503 
   39504 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   39505   /*
   39506   ** If this Btree is a candidate for shared cache, try to find an
   39507   ** existing BtShared object that we can share with
   39508   */
   39509   if( isMemdb==0 && zFilename && zFilename[0] ){
   39510     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
   39511       int nFullPathname = pVfs->mxPathname+1;
   39512       char *zFullPathname = sqlite3Malloc(nFullPathname);
   39513       sqlite3_mutex *mutexShared;
   39514       p->sharable = 1;
   39515       if( !zFullPathname ){
   39516         sqlite3_free(p);
   39517         return SQLITE_NOMEM;
   39518       }
   39519       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
   39520       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
   39521       sqlite3_mutex_enter(mutexOpen);
   39522       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   39523       sqlite3_mutex_enter(mutexShared);
   39524       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
   39525         assert( pBt->nRef>0 );
   39526         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
   39527                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
   39528           int iDb;
   39529           for(iDb=db->nDb-1; iDb>=0; iDb--){
   39530             Btree *pExisting = db->aDb[iDb].pBt;
   39531             if( pExisting && pExisting->pBt==pBt ){
   39532               sqlite3_mutex_leave(mutexShared);
   39533               sqlite3_mutex_leave(mutexOpen);
   39534               sqlite3_free(zFullPathname);
   39535               sqlite3_free(p);
   39536               return SQLITE_CONSTRAINT;
   39537             }
   39538           }
   39539           p->pBt = pBt;
   39540           pBt->nRef++;
   39541           break;
   39542         }
   39543       }
   39544       sqlite3_mutex_leave(mutexShared);
   39545       sqlite3_free(zFullPathname);
   39546     }
   39547 #ifdef SQLITE_DEBUG
   39548     else{
   39549       /* In debug mode, we mark all persistent databases as sharable
   39550       ** even when they are not.  This exercises the locking code and
   39551       ** gives more opportunity for asserts(sqlite3_mutex_held())
   39552       ** statements to find locking problems.
   39553       */
   39554       p->sharable = 1;
   39555     }
   39556 #endif
   39557   }
   39558 #endif
   39559   if( pBt==0 ){
   39560     /*
   39561     ** The following asserts make sure that structures used by the btree are
   39562     ** the right size.  This is to guard against size changes that result
   39563     ** when compiling on a different architecture.
   39564     */
   39565     assert( sizeof(i64)==8 || sizeof(i64)==4 );
   39566     assert( sizeof(u64)==8 || sizeof(u64)==4 );
   39567     assert( sizeof(u32)==4 );
   39568     assert( sizeof(u16)==2 );
   39569     assert( sizeof(Pgno)==4 );
   39570 
   39571     pBt = sqlite3MallocZero( sizeof(*pBt) );
   39572     if( pBt==0 ){
   39573       rc = SQLITE_NOMEM;
   39574       goto btree_open_out;
   39575     }
   39576     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
   39577                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
   39578     if( rc==SQLITE_OK ){
   39579       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
   39580     }
   39581     if( rc!=SQLITE_OK ){
   39582       goto btree_open_out;
   39583     }
   39584     pBt->db = db;
   39585     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
   39586     p->pBt = pBt;
   39587 
   39588     pBt->pCursor = 0;
   39589     pBt->pPage1 = 0;
   39590     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
   39591     pBt->pageSize = get2byte(&zDbHeader[16]);
   39592     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
   39593          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
   39594       pBt->pageSize = 0;
   39595 #ifndef SQLITE_OMIT_AUTOVACUUM
   39596       /* If the magic name ":memory:" will create an in-memory database, then
   39597       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
   39598       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
   39599       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
   39600       ** regular file-name. In this case the auto-vacuum applies as per normal.
   39601       */
   39602       if( zFilename && !isMemdb ){
   39603         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
   39604         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
   39605       }
   39606 #endif
   39607       nReserve = 0;
   39608     }else{
   39609       nReserve = zDbHeader[20];
   39610       pBt->pageSizeFixed = 1;
   39611 #ifndef SQLITE_OMIT_AUTOVACUUM
   39612       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
   39613       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
   39614 #endif
   39615     }
   39616     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
   39617     if( rc ) goto btree_open_out;
   39618     pBt->usableSize = pBt->pageSize - nReserve;
   39619     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
   39620 
   39621 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   39622     /* Add the new BtShared object to the linked list sharable BtShareds.
   39623     */
   39624     if( p->sharable ){
   39625       sqlite3_mutex *mutexShared;
   39626       pBt->nRef = 1;
   39627       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   39628       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
   39629         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
   39630         if( pBt->mutex==0 ){
   39631           rc = SQLITE_NOMEM;
   39632           db->mallocFailed = 0;
   39633           goto btree_open_out;
   39634         }
   39635       }
   39636       sqlite3_mutex_enter(mutexShared);
   39637       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
   39638       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
   39639       sqlite3_mutex_leave(mutexShared);
   39640     }
   39641 #endif
   39642   }
   39643 
   39644 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   39645   /* If the new Btree uses a sharable pBtShared, then link the new
   39646   ** Btree into the list of all sharable Btrees for the same connection.
   39647   ** The list is kept in ascending order by pBt address.
   39648   */
   39649   if( p->sharable ){
   39650     int i;
   39651     Btree *pSib;
   39652     for(i=0; i<db->nDb; i++){
   39653       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
   39654         while( pSib->pPrev ){ pSib = pSib->pPrev; }
   39655         if( p->pBt<pSib->pBt ){
   39656           p->pNext = pSib;
   39657           p->pPrev = 0;
   39658           pSib->pPrev = p;
   39659         }else{
   39660           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
   39661             pSib = pSib->pNext;
   39662           }
   39663           p->pNext = pSib->pNext;
   39664           p->pPrev = pSib;
   39665           if( p->pNext ){
   39666             p->pNext->pPrev = p;
   39667           }
   39668           pSib->pNext = p;
   39669         }
   39670         break;
   39671       }
   39672     }
   39673   }
   39674 #endif
   39675   *ppBtree = p;
   39676 
   39677 btree_open_out:
   39678   if( rc!=SQLITE_OK ){
   39679     if( pBt && pBt->pPager ){
   39680       sqlite3PagerClose(pBt->pPager);
   39681     }
   39682     sqlite3_free(pBt);
   39683     sqlite3_free(p);
   39684     *ppBtree = 0;
   39685   }
   39686   if( mutexOpen ){
   39687     assert( sqlite3_mutex_held(mutexOpen) );
   39688     sqlite3_mutex_leave(mutexOpen);
   39689   }
   39690   return rc;
   39691 }
   39692 
   39693 /*
   39694 ** Decrement the BtShared.nRef counter.  When it reaches zero,
   39695 ** remove the BtShared structure from the sharing list.  Return
   39696 ** true if the BtShared.nRef counter reaches zero and return
   39697 ** false if it is still positive.
   39698 */
   39699 static int removeFromSharingList(BtShared *pBt){
   39700 #ifndef SQLITE_OMIT_SHARED_CACHE
   39701   sqlite3_mutex *pMaster;
   39702   BtShared *pList;
   39703   int removed = 0;
   39704 
   39705   assert( sqlite3_mutex_notheld(pBt->mutex) );
   39706   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   39707   sqlite3_mutex_enter(pMaster);
   39708   pBt->nRef--;
   39709   if( pBt->nRef<=0 ){
   39710     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
   39711       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
   39712     }else{
   39713       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
   39714       while( ALWAYS(pList) && pList->pNext!=pBt ){
   39715         pList=pList->pNext;
   39716       }
   39717       if( ALWAYS(pList) ){
   39718         pList->pNext = pBt->pNext;
   39719       }
   39720     }
   39721     if( SQLITE_THREADSAFE ){
   39722       sqlite3_mutex_free(pBt->mutex);
   39723     }
   39724     removed = 1;
   39725   }
   39726   sqlite3_mutex_leave(pMaster);
   39727   return removed;
   39728 #else
   39729   return 1;
   39730 #endif
   39731 }
   39732 
   39733 /*
   39734 ** Make sure pBt->pTmpSpace points to an allocation of
   39735 ** MX_CELL_SIZE(pBt) bytes.
   39736 */
   39737 static void allocateTempSpace(BtShared *pBt){
   39738   if( !pBt->pTmpSpace ){
   39739     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
   39740   }
   39741 }
   39742 
   39743 /*
   39744 ** Free the pBt->pTmpSpace allocation
   39745 */
   39746 static void freeTempSpace(BtShared *pBt){
   39747   sqlite3PageFree( pBt->pTmpSpace);
   39748   pBt->pTmpSpace = 0;
   39749 }
   39750 
   39751 /*
   39752 ** Close an open database and invalidate all cursors.
   39753 */
   39754 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
   39755   BtShared *pBt = p->pBt;
   39756   BtCursor *pCur;
   39757 
   39758   /* Close all cursors opened via this handle.  */
   39759   assert( sqlite3_mutex_held(p->db->mutex) );
   39760   sqlite3BtreeEnter(p);
   39761   pCur = pBt->pCursor;
   39762   while( pCur ){
   39763     BtCursor *pTmp = pCur;
   39764     pCur = pCur->pNext;
   39765     if( pTmp->pBtree==p ){
   39766       sqlite3BtreeCloseCursor(pTmp);
   39767     }
   39768   }
   39769 
   39770   /* Rollback any active transaction and free the handle structure.
   39771   ** The call to sqlite3BtreeRollback() drops any table-locks held by
   39772   ** this handle.
   39773   */
   39774   sqlite3BtreeRollback(p);
   39775   sqlite3BtreeLeave(p);
   39776 
   39777   /* If there are still other outstanding references to the shared-btree
   39778   ** structure, return now. The remainder of this procedure cleans
   39779   ** up the shared-btree.
   39780   */
   39781   assert( p->wantToLock==0 && p->locked==0 );
   39782   if( !p->sharable || removeFromSharingList(pBt) ){
   39783     /* The pBt is no longer on the sharing list, so we can access
   39784     ** it without having to hold the mutex.
   39785     **
   39786     ** Clean out and delete the BtShared object.
   39787     */
   39788     assert( !pBt->pCursor );
   39789     sqlite3PagerClose(pBt->pPager);
   39790     if( pBt->xFreeSchema && pBt->pSchema ){
   39791       pBt->xFreeSchema(pBt->pSchema);
   39792     }
   39793     sqlite3_free(pBt->pSchema);
   39794     freeTempSpace(pBt);
   39795     sqlite3_free(pBt);
   39796   }
   39797 
   39798 #ifndef SQLITE_OMIT_SHARED_CACHE
   39799   assert( p->wantToLock==0 );
   39800   assert( p->locked==0 );
   39801   if( p->pPrev ) p->pPrev->pNext = p->pNext;
   39802   if( p->pNext ) p->pNext->pPrev = p->pPrev;
   39803 #endif
   39804 
   39805   sqlite3_free(p);
   39806   return SQLITE_OK;
   39807 }
   39808 
   39809 /*
   39810 ** Change the limit on the number of pages allowed in the cache.
   39811 **
   39812 ** The maximum number of cache pages is set to the absolute
   39813 ** value of mxPage.  If mxPage is negative, the pager will
   39814 ** operate asynchronously - it will not stop to do fsync()s
   39815 ** to insure data is written to the disk surface before
   39816 ** continuing.  Transactions still work if synchronous is off,
   39817 ** and the database cannot be corrupted if this program
   39818 ** crashes.  But if the operating system crashes or there is
   39819 ** an abrupt power failure when synchronous is off, the database
   39820 ** could be left in an inconsistent and unrecoverable state.
   39821 ** Synchronous is on by default so database corruption is not
   39822 ** normally a worry.
   39823 */
   39824 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
   39825   BtShared *pBt = p->pBt;
   39826   assert( sqlite3_mutex_held(p->db->mutex) );
   39827   sqlite3BtreeEnter(p);
   39828   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
   39829   sqlite3BtreeLeave(p);
   39830   return SQLITE_OK;
   39831 }
   39832 
   39833 /*
   39834 ** Change the way data is synced to disk in order to increase or decrease
   39835 ** how well the database resists damage due to OS crashes and power
   39836 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
   39837 ** there is a high probability of damage)  Level 2 is the default.  There
   39838 ** is a very low but non-zero probability of damage.  Level 3 reduces the
   39839 ** probability of damage to near zero but with a write performance reduction.
   39840 */
   39841 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   39842 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
   39843   BtShared *pBt = p->pBt;
   39844   assert( sqlite3_mutex_held(p->db->mutex) );
   39845   sqlite3BtreeEnter(p);
   39846   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
   39847   sqlite3BtreeLeave(p);
   39848   return SQLITE_OK;
   39849 }
   39850 #endif
   39851 
   39852 /*
   39853 ** Return TRUE if the given btree is set to safety level 1.  In other
   39854 ** words, return TRUE if no sync() occurs on the disk files.
   39855 */
   39856 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
   39857   BtShared *pBt = p->pBt;
   39858   int rc;
   39859   assert( sqlite3_mutex_held(p->db->mutex) );
   39860   sqlite3BtreeEnter(p);
   39861   assert( pBt && pBt->pPager );
   39862   rc = sqlite3PagerNosync(pBt->pPager);
   39863   sqlite3BtreeLeave(p);
   39864   return rc;
   39865 }
   39866 
   39867 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
   39868 /*
   39869 ** Change the default pages size and the number of reserved bytes per page.
   39870 ** Or, if the page size has already been fixed, return SQLITE_READONLY
   39871 ** without changing anything.
   39872 **
   39873 ** The page size must be a power of 2 between 512 and 65536.  If the page
   39874 ** size supplied does not meet this constraint then the page size is not
   39875 ** changed.
   39876 **
   39877 ** Page sizes are constrained to be a power of two so that the region
   39878 ** of the database file used for locking (beginning at PENDING_BYTE,
   39879 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
   39880 ** at the beginning of a page.
   39881 **
   39882 ** If parameter nReserve is less than zero, then the number of reserved
   39883 ** bytes per page is left unchanged.
   39884 **
   39885 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
   39886 ** and autovacuum mode can no longer be changed.
   39887 */
   39888 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
   39889   int rc = SQLITE_OK;
   39890   BtShared *pBt = p->pBt;
   39891   assert( nReserve>=-1 && nReserve<=255 );
   39892   sqlite3BtreeEnter(p);
   39893   if( pBt->pageSizeFixed ){
   39894     sqlite3BtreeLeave(p);
   39895     return SQLITE_READONLY;
   39896   }
   39897   if( nReserve<0 ){
   39898     nReserve = pBt->pageSize - pBt->usableSize;
   39899   }
   39900   assert( nReserve>=0 && nReserve<=255 );
   39901   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
   39902         ((pageSize-1)&pageSize)==0 ){
   39903     assert( (pageSize & 7)==0 );
   39904     assert( !pBt->pPage1 && !pBt->pCursor );
   39905     pBt->pageSize = (u16)pageSize;
   39906     freeTempSpace(pBt);
   39907   }
   39908   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
   39909   pBt->usableSize = pBt->pageSize - (u16)nReserve;
   39910   if( iFix ) pBt->pageSizeFixed = 1;
   39911   sqlite3BtreeLeave(p);
   39912   return rc;
   39913 }
   39914 
   39915 /*
   39916 ** Return the currently defined page size
   39917 */
   39918 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
   39919   return p->pBt->pageSize;
   39920 }
   39921 
   39922 /*
   39923 ** Return the number of bytes of space at the end of every page that
   39924 ** are intentually left unused.  This is the "reserved" space that is
   39925 ** sometimes used by extensions.
   39926 */
   39927 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
   39928   int n;
   39929   sqlite3BtreeEnter(p);
   39930   n = p->pBt->pageSize - p->pBt->usableSize;
   39931   sqlite3BtreeLeave(p);
   39932   return n;
   39933 }
   39934 
   39935 /*
   39936 ** Set the maximum page count for a database if mxPage is positive.
   39937 ** No changes are made if mxPage is 0 or negative.
   39938 ** Regardless of the value of mxPage, return the maximum page count.
   39939 */
   39940 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
   39941   int n;
   39942   sqlite3BtreeEnter(p);
   39943   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
   39944   sqlite3BtreeLeave(p);
   39945   return n;
   39946 }
   39947 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
   39948 
   39949 /*
   39950 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
   39951 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
   39952 ** is disabled. The default value for the auto-vacuum property is
   39953 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
   39954 */
   39955 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
   39956 #ifdef SQLITE_OMIT_AUTOVACUUM
   39957   return SQLITE_READONLY;
   39958 #else
   39959   BtShared *pBt = p->pBt;
   39960   int rc = SQLITE_OK;
   39961   u8 av = (u8)autoVacuum;
   39962 
   39963   sqlite3BtreeEnter(p);
   39964   if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
   39965     rc = SQLITE_READONLY;
   39966   }else{
   39967     pBt->autoVacuum = av ?1:0;
   39968     pBt->incrVacuum = av==2 ?1:0;
   39969   }
   39970   sqlite3BtreeLeave(p);
   39971   return rc;
   39972 #endif
   39973 }
   39974 
   39975 /*
   39976 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
   39977 ** enabled 1 is returned. Otherwise 0.
   39978 */
   39979 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
   39980 #ifdef SQLITE_OMIT_AUTOVACUUM
   39981   return BTREE_AUTOVACUUM_NONE;
   39982 #else
   39983   int rc;
   39984   sqlite3BtreeEnter(p);
   39985   rc = (
   39986     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
   39987     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
   39988     BTREE_AUTOVACUUM_INCR
   39989   );
   39990   sqlite3BtreeLeave(p);
   39991   return rc;
   39992 #endif
   39993 }
   39994 
   39995 
   39996 /*
   39997 ** Get a reference to pPage1 of the database file.  This will
   39998 ** also acquire a readlock on that file.
   39999 **
   40000 ** SQLITE_OK is returned on success.  If the file is not a
   40001 ** well-formed database file, then SQLITE_CORRUPT is returned.
   40002 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
   40003 ** is returned if we run out of memory.
   40004 */
   40005 static int lockBtree(BtShared *pBt){
   40006   int rc;
   40007   MemPage *pPage1;
   40008   int nPage;
   40009 
   40010   assert( sqlite3_mutex_held(pBt->mutex) );
   40011   assert( pBt->pPage1==0 );
   40012   rc = sqlite3PagerSharedLock(pBt->pPager);
   40013   if( rc!=SQLITE_OK ) return rc;
   40014   rc = btreeGetPage(pBt, 1, &pPage1, 0);
   40015   if( rc!=SQLITE_OK ) return rc;
   40016 
   40017   /* Do some checking to help insure the file we opened really is
   40018   ** a valid database file.
   40019   */
   40020   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
   40021   if( rc!=SQLITE_OK ){
   40022     goto page1_init_failed;
   40023   }else if( nPage>0 ){
   40024     int pageSize;
   40025     int usableSize;
   40026     u8 *page1 = pPage1->aData;
   40027     rc = SQLITE_NOTADB;
   40028     if( memcmp(page1, zMagicHeader, 16)!=0 ){
   40029       goto page1_init_failed;
   40030     }
   40031     if( page1[18]>1 ){
   40032       pBt->readOnly = 1;
   40033     }
   40034     if( page1[19]>1 ){
   40035       goto page1_init_failed;
   40036     }
   40037 
   40038     /* The maximum embedded fraction must be exactly 25%.  And the minimum
   40039     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
   40040     ** The original design allowed these amounts to vary, but as of
   40041     ** version 3.6.0, we require them to be fixed.
   40042     */
   40043     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
   40044       goto page1_init_failed;
   40045     }
   40046     pageSize = get2byte(&page1[16]);
   40047     if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
   40048         (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
   40049     ){
   40050       goto page1_init_failed;
   40051     }
   40052     assert( (pageSize & 7)==0 );
   40053     usableSize = pageSize - page1[20];
   40054     if( pageSize!=pBt->pageSize ){
   40055       /* After reading the first page of the database assuming a page size
   40056       ** of BtShared.pageSize, we have discovered that the page-size is
   40057       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
   40058       ** zero and return SQLITE_OK. The caller will call this function
   40059       ** again with the correct page-size.
   40060       */
   40061       releasePage(pPage1);
   40062       pBt->usableSize = (u16)usableSize;
   40063       pBt->pageSize = (u16)pageSize;
   40064       freeTempSpace(pBt);
   40065       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
   40066                                    pageSize-usableSize);
   40067       return rc;
   40068     }
   40069     if( usableSize<480 ){
   40070       goto page1_init_failed;
   40071     }
   40072     pBt->pageSize = (u16)pageSize;
   40073     pBt->usableSize = (u16)usableSize;
   40074 #ifndef SQLITE_OMIT_AUTOVACUUM
   40075     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
   40076     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
   40077 #endif
   40078   }
   40079 
   40080   /* maxLocal is the maximum amount of payload to store locally for
   40081   ** a cell.  Make sure it is small enough so that at least minFanout
   40082   ** cells can will fit on one page.  We assume a 10-byte page header.
   40083   ** Besides the payload, the cell must store:
   40084   **     2-byte pointer to the cell
   40085   **     4-byte child pointer
   40086   **     9-byte nKey value
   40087   **     4-byte nData value
   40088   **     4-byte overflow page pointer
   40089   ** So a cell consists of a 2-byte poiner, a header which is as much as
   40090   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
   40091   ** page pointer.
   40092   */
   40093   pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
   40094   pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
   40095   pBt->maxLeaf = pBt->usableSize - 35;
   40096   pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
   40097   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
   40098   pBt->pPage1 = pPage1;
   40099   return SQLITE_OK;
   40100 
   40101 page1_init_failed:
   40102   releasePage(pPage1);
   40103   pBt->pPage1 = 0;
   40104   // Begin Android-add
   40105   if (rc == SQLITE_NOTADB) {
   40106     // the file-header is bad. assume that it got corrupted and return "corruption error"
   40107     rc = SQLITE_CORRUPT_BKPT;
   40108   }
   40109   // End Android-add
   40110   return rc;
   40111 }
   40112 
   40113 /*
   40114 ** If there are no outstanding cursors and we are not in the middle
   40115 ** of a transaction but there is a read lock on the database, then
   40116 ** this routine unrefs the first page of the database file which
   40117 ** has the effect of releasing the read lock.
   40118 **
   40119 ** If there is a transaction in progress, this routine is a no-op.
   40120 */
   40121 static void unlockBtreeIfUnused(BtShared *pBt){
   40122   assert( sqlite3_mutex_held(pBt->mutex) );
   40123   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
   40124   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
   40125     assert( pBt->pPage1->aData );
   40126     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
   40127     assert( pBt->pPage1->aData );
   40128     releasePage(pBt->pPage1);
   40129     pBt->pPage1 = 0;
   40130   }
   40131 }
   40132 
   40133 /*
   40134 ** If pBt points to an empty file then convert that empty file
   40135 ** into a new empty database by initializing the first page of
   40136 ** the database.
   40137 */
   40138 static int newDatabase(BtShared *pBt){
   40139   MemPage *pP1;
   40140   unsigned char *data;
   40141   int rc;
   40142   int nPage;
   40143 
   40144   assert( sqlite3_mutex_held(pBt->mutex) );
   40145   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
   40146   if( rc!=SQLITE_OK || nPage>0 ){
   40147     return rc;
   40148   }
   40149   pP1 = pBt->pPage1;
   40150   assert( pP1!=0 );
   40151   data = pP1->aData;
   40152   rc = sqlite3PagerWrite(pP1->pDbPage);
   40153   if( rc ) return rc;
   40154   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
   40155   assert( sizeof(zMagicHeader)==16 );
   40156   put2byte(&data[16], pBt->pageSize);
   40157   data[18] = 1;
   40158   data[19] = 1;
   40159   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
   40160   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
   40161   data[21] = 64;
   40162   data[22] = 32;
   40163   data[23] = 32;
   40164   memset(&data[24], 0, 100-24);
   40165   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
   40166   pBt->pageSizeFixed = 1;
   40167 #ifndef SQLITE_OMIT_AUTOVACUUM
   40168   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
   40169   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
   40170   put4byte(&data[36 + 4*4], pBt->autoVacuum);
   40171   put4byte(&data[36 + 7*4], pBt->incrVacuum);
   40172 #endif
   40173   return SQLITE_OK;
   40174 }
   40175 
   40176 /*
   40177 ** Attempt to start a new transaction. A write-transaction
   40178 ** is started if the second argument is nonzero, otherwise a read-
   40179 ** transaction.  If the second argument is 2 or more and exclusive
   40180 ** transaction is started, meaning that no other process is allowed
   40181 ** to access the database.  A preexisting transaction may not be
   40182 ** upgraded to exclusive by calling this routine a second time - the
   40183 ** exclusivity flag only works for a new transaction.
   40184 **
   40185 ** A write-transaction must be started before attempting any
   40186 ** changes to the database.  None of the following routines
   40187 ** will work unless a transaction is started first:
   40188 **
   40189 **      sqlite3BtreeCreateTable()
   40190 **      sqlite3BtreeCreateIndex()
   40191 **      sqlite3BtreeClearTable()
   40192 **      sqlite3BtreeDropTable()
   40193 **      sqlite3BtreeInsert()
   40194 **      sqlite3BtreeDelete()
   40195 **      sqlite3BtreeUpdateMeta()
   40196 **
   40197 ** If an initial attempt to acquire the lock fails because of lock contention
   40198 ** and the database was previously unlocked, then invoke the busy handler
   40199 ** if there is one.  But if there was previously a read-lock, do not
   40200 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
   40201 ** returned when there is already a read-lock in order to avoid a deadlock.
   40202 **
   40203 ** Suppose there are two processes A and B.  A has a read lock and B has
   40204 ** a reserved lock.  B tries to promote to exclusive but is blocked because
   40205 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
   40206 ** One or the other of the two processes must give way or there can be
   40207 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
   40208 ** when A already has a read lock, we encourage A to give up and let B
   40209 ** proceed.
   40210 */
   40211 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
   40212   sqlite3 *pBlock = 0;
   40213   BtShared *pBt = p->pBt;
   40214   int rc = SQLITE_OK;
   40215 
   40216   sqlite3BtreeEnter(p);
   40217   btreeIntegrity(p);
   40218 
   40219   /* If the btree is already in a write-transaction, or it
   40220   ** is already in a read-transaction and a read-transaction
   40221   ** is requested, this is a no-op.
   40222   */
   40223   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
   40224     goto trans_begun;
   40225   }
   40226 
   40227   /* Write transactions are not possible on a read-only database */
   40228   if( pBt->readOnly && wrflag ){
   40229     rc = SQLITE_READONLY;
   40230     goto trans_begun;
   40231   }
   40232 
   40233 #ifndef SQLITE_OMIT_SHARED_CACHE
   40234   /* If another database handle has already opened a write transaction
   40235   ** on this shared-btree structure and a second write transaction is
   40236   ** requested, return SQLITE_LOCKED.
   40237   */
   40238   if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
   40239     pBlock = pBt->pWriter->db;
   40240   }else if( wrflag>1 ){
   40241     BtLock *pIter;
   40242     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   40243       if( pIter->pBtree!=p ){
   40244         pBlock = pIter->pBtree->db;
   40245         break;
   40246       }
   40247     }
   40248   }
   40249   if( pBlock ){
   40250     sqlite3ConnectionBlocked(p->db, pBlock);
   40251     rc = SQLITE_LOCKED_SHAREDCACHE;
   40252     goto trans_begun;
   40253   }
   40254 #endif
   40255 
   40256   /* Any read-only or read-write transaction implies a read-lock on
   40257   ** page 1. So if some other shared-cache client already has a write-lock
   40258   ** on page 1, the transaction cannot be opened. */
   40259   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
   40260   if( SQLITE_OK!=rc ) goto trans_begun;
   40261 
   40262   do {
   40263     /* Call lockBtree() until either pBt->pPage1 is populated or
   40264     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
   40265     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
   40266     ** reading page 1 it discovers that the page-size of the database
   40267     ** file is not pBt->pageSize. In this case lockBtree() will update
   40268     ** pBt->pageSize to the page-size of the file on disk.
   40269     */
   40270     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
   40271 
   40272     if( rc==SQLITE_OK && wrflag ){
   40273       if( pBt->readOnly ){
   40274         rc = SQLITE_READONLY;
   40275       }else{
   40276         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
   40277         if( rc==SQLITE_OK ){
   40278           rc = newDatabase(pBt);
   40279         }
   40280       }
   40281     }
   40282 
   40283     if( rc!=SQLITE_OK ){
   40284       unlockBtreeIfUnused(pBt);
   40285     }
   40286   }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
   40287           btreeInvokeBusyHandler(pBt) );
   40288 
   40289   if( rc==SQLITE_OK ){
   40290     if( p->inTrans==TRANS_NONE ){
   40291       pBt->nTransaction++;
   40292 #ifndef SQLITE_OMIT_SHARED_CACHE
   40293       if( p->sharable ){
   40294 	assert( p->lock.pBtree==p && p->lock.iTable==1 );
   40295         p->lock.eLock = READ_LOCK;
   40296         p->lock.pNext = pBt->pLock;
   40297         pBt->pLock = &p->lock;
   40298       }
   40299 #endif
   40300     }
   40301     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
   40302     if( p->inTrans>pBt->inTransaction ){
   40303       pBt->inTransaction = p->inTrans;
   40304     }
   40305 #ifndef SQLITE_OMIT_SHARED_CACHE
   40306     if( wrflag ){
   40307       assert( !pBt->pWriter );
   40308       pBt->pWriter = p;
   40309       pBt->isExclusive = (u8)(wrflag>1);
   40310     }
   40311 #endif
   40312   }
   40313 
   40314 
   40315 trans_begun:
   40316   if( rc==SQLITE_OK && wrflag ){
   40317     /* This call makes sure that the pager has the correct number of
   40318     ** open savepoints. If the second parameter is greater than 0 and
   40319     ** the sub-journal is not already open, then it will be opened here.
   40320     */
   40321     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
   40322   }
   40323 
   40324   btreeIntegrity(p);
   40325   sqlite3BtreeLeave(p);
   40326   return rc;
   40327 }
   40328 
   40329 #ifndef SQLITE_OMIT_AUTOVACUUM
   40330 
   40331 /*
   40332 ** Set the pointer-map entries for all children of page pPage. Also, if
   40333 ** pPage contains cells that point to overflow pages, set the pointer
   40334 ** map entries for the overflow pages as well.
   40335 */
   40336 static int setChildPtrmaps(MemPage *pPage){
   40337   int i;                             /* Counter variable */
   40338   int nCell;                         /* Number of cells in page pPage */
   40339   int rc;                            /* Return code */
   40340   BtShared *pBt = pPage->pBt;
   40341   u8 isInitOrig = pPage->isInit;
   40342   Pgno pgno = pPage->pgno;
   40343 
   40344   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   40345   rc = btreeInitPage(pPage);
   40346   if( rc!=SQLITE_OK ){
   40347     goto set_child_ptrmaps_out;
   40348   }
   40349   nCell = pPage->nCell;
   40350 
   40351   for(i=0; i<nCell; i++){
   40352     u8 *pCell = findCell(pPage, i);
   40353 
   40354     ptrmapPutOvflPtr(pPage, pCell, &rc);
   40355 
   40356     if( !pPage->leaf ){
   40357       Pgno childPgno = get4byte(pCell);
   40358       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
   40359     }
   40360   }
   40361 
   40362   if( !pPage->leaf ){
   40363     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   40364     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
   40365   }
   40366 
   40367 set_child_ptrmaps_out:
   40368   pPage->isInit = isInitOrig;
   40369   return rc;
   40370 }
   40371 
   40372 /*
   40373 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
   40374 ** that it points to iTo. Parameter eType describes the type of pointer to
   40375 ** be modified, as  follows:
   40376 **
   40377 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
   40378 **                   page of pPage.
   40379 **
   40380 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
   40381 **                   page pointed to by one of the cells on pPage.
   40382 **
   40383 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
   40384 **                   overflow page in the list.
   40385 */
   40386 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
   40387   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   40388   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   40389   if( eType==PTRMAP_OVERFLOW2 ){
   40390     /* The pointer is always the first 4 bytes of the page in this case.  */
   40391     if( get4byte(pPage->aData)!=iFrom ){
   40392       return SQLITE_CORRUPT_BKPT;
   40393     }
   40394     put4byte(pPage->aData, iTo);
   40395   }else{
   40396     u8 isInitOrig = pPage->isInit;
   40397     int i;
   40398     int nCell;
   40399 
   40400     btreeInitPage(pPage);
   40401     nCell = pPage->nCell;
   40402 
   40403     for(i=0; i<nCell; i++){
   40404       u8 *pCell = findCell(pPage, i);
   40405       if( eType==PTRMAP_OVERFLOW1 ){
   40406         CellInfo info;
   40407         btreeParseCellPtr(pPage, pCell, &info);
   40408         if( info.iOverflow ){
   40409           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
   40410             put4byte(&pCell[info.iOverflow], iTo);
   40411             break;
   40412           }
   40413         }
   40414       }else{
   40415         if( get4byte(pCell)==iFrom ){
   40416           put4byte(pCell, iTo);
   40417           break;
   40418         }
   40419       }
   40420     }
   40421 
   40422     if( i==nCell ){
   40423       if( eType!=PTRMAP_BTREE ||
   40424           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
   40425         return SQLITE_CORRUPT_BKPT;
   40426       }
   40427       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
   40428     }
   40429 
   40430     pPage->isInit = isInitOrig;
   40431   }
   40432   return SQLITE_OK;
   40433 }
   40434 
   40435 
   40436 /*
   40437 ** Move the open database page pDbPage to location iFreePage in the
   40438 ** database. The pDbPage reference remains valid.
   40439 **
   40440 ** The isCommit flag indicates that there is no need to remember that
   40441 ** the journal needs to be sync()ed before database page pDbPage->pgno
   40442 ** can be written to. The caller has already promised not to write to that
   40443 ** page.
   40444 */
   40445 static int relocatePage(
   40446   BtShared *pBt,           /* Btree */
   40447   MemPage *pDbPage,        /* Open page to move */
   40448   u8 eType,                /* Pointer map 'type' entry for pDbPage */
   40449   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
   40450   Pgno iFreePage,          /* The location to move pDbPage to */
   40451   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
   40452 ){
   40453   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
   40454   Pgno iDbPage = pDbPage->pgno;
   40455   Pager *pPager = pBt->pPager;
   40456   int rc;
   40457 
   40458   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
   40459       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
   40460   assert( sqlite3_mutex_held(pBt->mutex) );
   40461   assert( pDbPage->pBt==pBt );
   40462 
   40463   /* Move page iDbPage from its current location to page number iFreePage */
   40464   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
   40465       iDbPage, iFreePage, iPtrPage, eType));
   40466   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
   40467   if( rc!=SQLITE_OK ){
   40468     return rc;
   40469   }
   40470   pDbPage->pgno = iFreePage;
   40471 
   40472   /* If pDbPage was a btree-page, then it may have child pages and/or cells
   40473   ** that point to overflow pages. The pointer map entries for all these
   40474   ** pages need to be changed.
   40475   **
   40476   ** If pDbPage is an overflow page, then the first 4 bytes may store a
   40477   ** pointer to a subsequent overflow page. If this is the case, then
   40478   ** the pointer map needs to be updated for the subsequent overflow page.
   40479   */
   40480   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
   40481     rc = setChildPtrmaps(pDbPage);
   40482     if( rc!=SQLITE_OK ){
   40483       return rc;
   40484     }
   40485   }else{
   40486     Pgno nextOvfl = get4byte(pDbPage->aData);
   40487     if( nextOvfl!=0 ){
   40488       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
   40489       if( rc!=SQLITE_OK ){
   40490         return rc;
   40491       }
   40492     }
   40493   }
   40494 
   40495   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
   40496   ** that it points at iFreePage. Also fix the pointer map entry for
   40497   ** iPtrPage.
   40498   */
   40499   if( eType!=PTRMAP_ROOTPAGE ){
   40500     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
   40501     if( rc!=SQLITE_OK ){
   40502       return rc;
   40503     }
   40504     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
   40505     if( rc!=SQLITE_OK ){
   40506       releasePage(pPtrPage);
   40507       return rc;
   40508     }
   40509     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
   40510     releasePage(pPtrPage);
   40511     if( rc==SQLITE_OK ){
   40512       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
   40513     }
   40514   }
   40515   return rc;
   40516 }
   40517 
   40518 /* Forward declaration required by incrVacuumStep(). */
   40519 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
   40520 
   40521 /*
   40522 ** Perform a single step of an incremental-vacuum. If successful,
   40523 ** return SQLITE_OK. If there is no work to do (and therefore no
   40524 ** point in calling this function again), return SQLITE_DONE.
   40525 **
   40526 ** More specificly, this function attempts to re-organize the
   40527 ** database so that the last page of the file currently in use
   40528 ** is no longer in use.
   40529 **
   40530 ** If the nFin parameter is non-zero, this function assumes
   40531 ** that the caller will keep calling incrVacuumStep() until
   40532 ** it returns SQLITE_DONE or an error, and that nFin is the
   40533 ** number of pages the database file will contain after this
   40534 ** process is complete.  If nFin is zero, it is assumed that
   40535 ** incrVacuumStep() will be called a finite amount of times
   40536 ** which may or may not empty the freelist.  A full autovacuum
   40537 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
   40538 */
   40539 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
   40540   Pgno nFreeList;           /* Number of pages still on the free-list */
   40541 
   40542   assert( sqlite3_mutex_held(pBt->mutex) );
   40543   assert( iLastPg>nFin );
   40544 
   40545   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
   40546     int rc;
   40547     u8 eType;
   40548     Pgno iPtrPage;
   40549 
   40550     nFreeList = get4byte(&pBt->pPage1->aData[36]);
   40551     if( nFreeList==0 ){
   40552       return SQLITE_DONE;
   40553     }
   40554 
   40555     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
   40556     if( rc!=SQLITE_OK ){
   40557       return rc;
   40558     }
   40559     if( eType==PTRMAP_ROOTPAGE ){
   40560       return SQLITE_CORRUPT_BKPT;
   40561     }
   40562 
   40563     if( eType==PTRMAP_FREEPAGE ){
   40564       if( nFin==0 ){
   40565         /* Remove the page from the files free-list. This is not required
   40566         ** if nFin is non-zero. In that case, the free-list will be
   40567         ** truncated to zero after this function returns, so it doesn't
   40568         ** matter if it still contains some garbage entries.
   40569         */
   40570         Pgno iFreePg;
   40571         MemPage *pFreePg;
   40572         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
   40573         if( rc!=SQLITE_OK ){
   40574           return rc;
   40575         }
   40576         assert( iFreePg==iLastPg );
   40577         releasePage(pFreePg);
   40578       }
   40579     } else {
   40580       Pgno iFreePg;             /* Index of free page to move pLastPg to */
   40581       MemPage *pLastPg;
   40582 
   40583       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
   40584       if( rc!=SQLITE_OK ){
   40585         return rc;
   40586       }
   40587 
   40588       /* If nFin is zero, this loop runs exactly once and page pLastPg
   40589       ** is swapped with the first free page pulled off the free list.
   40590       **
   40591       ** On the other hand, if nFin is greater than zero, then keep
   40592       ** looping until a free-page located within the first nFin pages
   40593       ** of the file is found.
   40594       */
   40595       do {
   40596         MemPage *pFreePg;
   40597         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
   40598         if( rc!=SQLITE_OK ){
   40599           releasePage(pLastPg);
   40600           return rc;
   40601         }
   40602         releasePage(pFreePg);
   40603       }while( nFin!=0 && iFreePg>nFin );
   40604       assert( iFreePg<iLastPg );
   40605 
   40606       rc = sqlite3PagerWrite(pLastPg->pDbPage);
   40607       if( rc==SQLITE_OK ){
   40608         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
   40609       }
   40610       releasePage(pLastPg);
   40611       if( rc!=SQLITE_OK ){
   40612         return rc;
   40613       }
   40614     }
   40615   }
   40616 
   40617   if( nFin==0 ){
   40618     iLastPg--;
   40619     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
   40620       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
   40621         MemPage *pPg;
   40622         int rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
   40623         if( rc!=SQLITE_OK ){
   40624           return rc;
   40625         }
   40626         rc = sqlite3PagerWrite(pPg->pDbPage);
   40627         releasePage(pPg);
   40628         if( rc!=SQLITE_OK ){
   40629           return rc;
   40630         }
   40631       }
   40632       iLastPg--;
   40633     }
   40634     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
   40635   }
   40636   return SQLITE_OK;
   40637 }
   40638 
   40639 /*
   40640 ** A write-transaction must be opened before calling this function.
   40641 ** It performs a single unit of work towards an incremental vacuum.
   40642 **
   40643 ** If the incremental vacuum is finished after this function has run,
   40644 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
   40645 ** SQLITE_OK is returned. Otherwise an SQLite error code.
   40646 */
   40647 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
   40648   int rc;
   40649   BtShared *pBt = p->pBt;
   40650 
   40651   sqlite3BtreeEnter(p);
   40652   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
   40653   if( !pBt->autoVacuum ){
   40654     rc = SQLITE_DONE;
   40655   }else{
   40656     invalidateAllOverflowCache(pBt);
   40657     rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
   40658   }
   40659   sqlite3BtreeLeave(p);
   40660   return rc;
   40661 }
   40662 
   40663 /*
   40664 ** This routine is called prior to sqlite3PagerCommit when a transaction
   40665 ** is commited for an auto-vacuum database.
   40666 **
   40667 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
   40668 ** the database file should be truncated to during the commit process.
   40669 ** i.e. the database has been reorganized so that only the first *pnTrunc
   40670 ** pages are in use.
   40671 */
   40672 static int autoVacuumCommit(BtShared *pBt){
   40673   int rc = SQLITE_OK;
   40674   Pager *pPager = pBt->pPager;
   40675   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
   40676 
   40677   assert( sqlite3_mutex_held(pBt->mutex) );
   40678   invalidateAllOverflowCache(pBt);
   40679   assert(pBt->autoVacuum);
   40680   if( !pBt->incrVacuum ){
   40681     Pgno nFin;         /* Number of pages in database after autovacuuming */
   40682     Pgno nFree;        /* Number of pages on the freelist initially */
   40683     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
   40684     Pgno iFree;        /* The next page to be freed */
   40685     int nEntry;        /* Number of entries on one ptrmap page */
   40686     Pgno nOrig;        /* Database size before freeing */
   40687 
   40688     nOrig = pagerPagecount(pBt);
   40689     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
   40690       /* It is not possible to create a database for which the final page
   40691       ** is either a pointer-map page or the pending-byte page. If one
   40692       ** is encountered, this indicates corruption.
   40693       */
   40694       return SQLITE_CORRUPT_BKPT;
   40695     }
   40696 
   40697     nFree = get4byte(&pBt->pPage1->aData[36]);
   40698     nEntry = pBt->usableSize/5;
   40699     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
   40700     nFin = nOrig - nFree - nPtrmap;
   40701     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
   40702       nFin--;
   40703     }
   40704     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
   40705       nFin--;
   40706     }
   40707     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
   40708 
   40709     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
   40710       rc = incrVacuumStep(pBt, nFin, iFree);
   40711     }
   40712     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
   40713       rc = SQLITE_OK;
   40714       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   40715       put4byte(&pBt->pPage1->aData[32], 0);
   40716       put4byte(&pBt->pPage1->aData[36], 0);
   40717       sqlite3PagerTruncateImage(pBt->pPager, nFin);
   40718     }
   40719     if( rc!=SQLITE_OK ){
   40720       sqlite3PagerRollback(pPager);
   40721     }
   40722   }
   40723 
   40724   assert( nRef==sqlite3PagerRefcount(pPager) );
   40725   return rc;
   40726 }
   40727 
   40728 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
   40729 # define setChildPtrmaps(x) SQLITE_OK
   40730 #endif
   40731 
   40732 /*
   40733 ** This routine does the first phase of a two-phase commit.  This routine
   40734 ** causes a rollback journal to be created (if it does not already exist)
   40735 ** and populated with enough information so that if a power loss occurs
   40736 ** the database can be restored to its original state by playing back
   40737 ** the journal.  Then the contents of the journal are flushed out to
   40738 ** the disk.  After the journal is safely on oxide, the changes to the
   40739 ** database are written into the database file and flushed to oxide.
   40740 ** At the end of this call, the rollback journal still exists on the
   40741 ** disk and we are still holding all locks, so the transaction has not
   40742 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
   40743 ** commit process.
   40744 **
   40745 ** This call is a no-op if no write-transaction is currently active on pBt.
   40746 **
   40747 ** Otherwise, sync the database file for the btree pBt. zMaster points to
   40748 ** the name of a master journal file that should be written into the
   40749 ** individual journal file, or is NULL, indicating no master journal file
   40750 ** (single database transaction).
   40751 **
   40752 ** When this is called, the master journal should already have been
   40753 ** created, populated with this journal pointer and synced to disk.
   40754 **
   40755 ** Once this is routine has returned, the only thing required to commit
   40756 ** the write-transaction for this database file is to delete the journal.
   40757 */
   40758 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
   40759   int rc = SQLITE_OK;
   40760   if( p->inTrans==TRANS_WRITE ){
   40761     BtShared *pBt = p->pBt;
   40762     sqlite3BtreeEnter(p);
   40763 #ifndef SQLITE_OMIT_AUTOVACUUM
   40764     if( pBt->autoVacuum ){
   40765       rc = autoVacuumCommit(pBt);
   40766       if( rc!=SQLITE_OK ){
   40767         sqlite3BtreeLeave(p);
   40768         return rc;
   40769       }
   40770     }
   40771 #endif
   40772     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
   40773     sqlite3BtreeLeave(p);
   40774   }
   40775   return rc;
   40776 }
   40777 
   40778 /*
   40779 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
   40780 ** at the conclusion of a transaction.
   40781 */
   40782 static void btreeEndTransaction(Btree *p){
   40783   BtShared *pBt = p->pBt;
   40784   assert( sqlite3BtreeHoldsMutex(p) );
   40785 
   40786   btreeClearHasContent(pBt);
   40787   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
   40788     /* If there are other active statements that belong to this database
   40789     ** handle, downgrade to a read-only transaction. The other statements
   40790     ** may still be reading from the database.  */
   40791     downgradeAllSharedCacheTableLocks(p);
   40792     p->inTrans = TRANS_READ;
   40793   }else{
   40794     /* If the handle had any kind of transaction open, decrement the
   40795     ** transaction count of the shared btree. If the transaction count
   40796     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
   40797     ** call below will unlock the pager.  */
   40798     if( p->inTrans!=TRANS_NONE ){
   40799       clearAllSharedCacheTableLocks(p);
   40800       pBt->nTransaction--;
   40801       if( 0==pBt->nTransaction ){
   40802         pBt->inTransaction = TRANS_NONE;
   40803       }
   40804     }
   40805 
   40806     /* Set the current transaction state to TRANS_NONE and unlock the
   40807     ** pager if this call closed the only read or write transaction.  */
   40808     p->inTrans = TRANS_NONE;
   40809     unlockBtreeIfUnused(pBt);
   40810   }
   40811 
   40812   btreeIntegrity(p);
   40813 }
   40814 
   40815 /*
   40816 ** Commit the transaction currently in progress.
   40817 **
   40818 ** This routine implements the second phase of a 2-phase commit.  The
   40819 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
   40820 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
   40821 ** routine did all the work of writing information out to disk and flushing the
   40822 ** contents so that they are written onto the disk platter.  All this
   40823 ** routine has to do is delete or truncate or zero the header in the
   40824 ** the rollback journal (which causes the transaction to commit) and
   40825 ** drop locks.
   40826 **
   40827 ** This will release the write lock on the database file.  If there
   40828 ** are no active cursors, it also releases the read lock.
   40829 */
   40830 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
   40831   BtShared *pBt = p->pBt;
   40832 
   40833   sqlite3BtreeEnter(p);
   40834   btreeIntegrity(p);
   40835 
   40836   /* If the handle has a write-transaction open, commit the shared-btrees
   40837   ** transaction and set the shared state to TRANS_READ.
   40838   */
   40839   if( p->inTrans==TRANS_WRITE ){
   40840     int rc;
   40841     assert( pBt->inTransaction==TRANS_WRITE );
   40842     assert( pBt->nTransaction>0 );
   40843     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
   40844     if( rc!=SQLITE_OK ){
   40845       sqlite3BtreeLeave(p);
   40846       return rc;
   40847     }
   40848     pBt->inTransaction = TRANS_READ;
   40849   }
   40850 
   40851   btreeEndTransaction(p);
   40852   sqlite3BtreeLeave(p);
   40853   return SQLITE_OK;
   40854 }
   40855 
   40856 /*
   40857 ** Do both phases of a commit.
   40858 */
   40859 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
   40860   int rc;
   40861   sqlite3BtreeEnter(p);
   40862   rc = sqlite3BtreeCommitPhaseOne(p, 0);
   40863   if( rc==SQLITE_OK ){
   40864     rc = sqlite3BtreeCommitPhaseTwo(p);
   40865   }
   40866   sqlite3BtreeLeave(p);
   40867   return rc;
   40868 }
   40869 
   40870 #ifndef NDEBUG
   40871 /*
   40872 ** Return the number of write-cursors open on this handle. This is for use
   40873 ** in assert() expressions, so it is only compiled if NDEBUG is not
   40874 ** defined.
   40875 **
   40876 ** For the purposes of this routine, a write-cursor is any cursor that
   40877 ** is capable of writing to the databse.  That means the cursor was
   40878 ** originally opened for writing and the cursor has not be disabled
   40879 ** by having its state changed to CURSOR_FAULT.
   40880 */
   40881 static int countWriteCursors(BtShared *pBt){
   40882   BtCursor *pCur;
   40883   int r = 0;
   40884   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
   40885     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
   40886   }
   40887   return r;
   40888 }
   40889 #endif
   40890 
   40891 /*
   40892 ** This routine sets the state to CURSOR_FAULT and the error
   40893 ** code to errCode for every cursor on BtShared that pBtree
   40894 ** references.
   40895 **
   40896 ** Every cursor is tripped, including cursors that belong
   40897 ** to other database connections that happen to be sharing
   40898 ** the cache with pBtree.
   40899 **
   40900 ** This routine gets called when a rollback occurs.
   40901 ** All cursors using the same cache must be tripped
   40902 ** to prevent them from trying to use the btree after
   40903 ** the rollback.  The rollback may have deleted tables
   40904 ** or moved root pages, so it is not sufficient to
   40905 ** save the state of the cursor.  The cursor must be
   40906 ** invalidated.
   40907 */
   40908 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
   40909   BtCursor *p;
   40910   sqlite3BtreeEnter(pBtree);
   40911   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
   40912     int i;
   40913     sqlite3BtreeClearCursor(p);
   40914     p->eState = CURSOR_FAULT;
   40915     p->skipNext = errCode;
   40916     for(i=0; i<=p->iPage; i++){
   40917       releasePage(p->apPage[i]);
   40918       p->apPage[i] = 0;
   40919     }
   40920   }
   40921   sqlite3BtreeLeave(pBtree);
   40922 }
   40923 
   40924 /*
   40925 ** Rollback the transaction in progress.  All cursors will be
   40926 ** invalided by this operation.  Any attempt to use a cursor
   40927 ** that was open at the beginning of this operation will result
   40928 ** in an error.
   40929 **
   40930 ** This will release the write lock on the database file.  If there
   40931 ** are no active cursors, it also releases the read lock.
   40932 */
   40933 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
   40934   int rc;
   40935   BtShared *pBt = p->pBt;
   40936   MemPage *pPage1;
   40937 
   40938   sqlite3BtreeEnter(p);
   40939   rc = saveAllCursors(pBt, 0, 0);
   40940 #ifndef SQLITE_OMIT_SHARED_CACHE
   40941   if( rc!=SQLITE_OK ){
   40942     /* This is a horrible situation. An IO or malloc() error occurred whilst
   40943     ** trying to save cursor positions. If this is an automatic rollback (as
   40944     ** the result of a constraint, malloc() failure or IO error) then
   40945     ** the cache may be internally inconsistent (not contain valid trees) so
   40946     ** we cannot simply return the error to the caller. Instead, abort
   40947     ** all queries that may be using any of the cursors that failed to save.
   40948     */
   40949     sqlite3BtreeTripAllCursors(p, rc);
   40950   }
   40951 #endif
   40952   btreeIntegrity(p);
   40953 
   40954   if( p->inTrans==TRANS_WRITE ){
   40955     int rc2;
   40956 
   40957     assert( TRANS_WRITE==pBt->inTransaction );
   40958     rc2 = sqlite3PagerRollback(pBt->pPager);
   40959     if( rc2!=SQLITE_OK ){
   40960       rc = rc2;
   40961     }
   40962 
   40963     /* The rollback may have destroyed the pPage1->aData value.  So
   40964     ** call btreeGetPage() on page 1 again to make
   40965     ** sure pPage1->aData is set correctly. */
   40966     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
   40967       releasePage(pPage1);
   40968     }
   40969     assert( countWriteCursors(pBt)==0 );
   40970     pBt->inTransaction = TRANS_READ;
   40971   }
   40972 
   40973   btreeEndTransaction(p);
   40974   sqlite3BtreeLeave(p);
   40975   return rc;
   40976 }
   40977 
   40978 /*
   40979 ** Start a statement subtransaction. The subtransaction can can be rolled
   40980 ** back independently of the main transaction. You must start a transaction
   40981 ** before starting a subtransaction. The subtransaction is ended automatically
   40982 ** if the main transaction commits or rolls back.
   40983 **
   40984 ** Statement subtransactions are used around individual SQL statements
   40985 ** that are contained within a BEGIN...COMMIT block.  If a constraint
   40986 ** error occurs within the statement, the effect of that one statement
   40987 ** can be rolled back without having to rollback the entire transaction.
   40988 **
   40989 ** A statement sub-transaction is implemented as an anonymous savepoint. The
   40990 ** value passed as the second parameter is the total number of savepoints,
   40991 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
   40992 ** are no active savepoints and no other statement-transactions open,
   40993 ** iStatement is 1. This anonymous savepoint can be released or rolled back
   40994 ** using the sqlite3BtreeSavepoint() function.
   40995 */
   40996 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
   40997   int rc;
   40998   BtShared *pBt = p->pBt;
   40999   sqlite3BtreeEnter(p);
   41000   assert( p->inTrans==TRANS_WRITE );
   41001   assert( pBt->readOnly==0 );
   41002   assert( iStatement>0 );
   41003   assert( iStatement>p->db->nSavepoint );
   41004   if( NEVER(p->inTrans!=TRANS_WRITE || pBt->readOnly) ){
   41005     rc = SQLITE_INTERNAL;
   41006   }else{
   41007     assert( pBt->inTransaction==TRANS_WRITE );
   41008     /* At the pager level, a statement transaction is a savepoint with
   41009     ** an index greater than all savepoints created explicitly using
   41010     ** SQL statements. It is illegal to open, release or rollback any
   41011     ** such savepoints while the statement transaction savepoint is active.
   41012     */
   41013     rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
   41014   }
   41015   sqlite3BtreeLeave(p);
   41016   return rc;
   41017 }
   41018 
   41019 /*
   41020 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
   41021 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
   41022 ** savepoint identified by parameter iSavepoint, depending on the value
   41023 ** of op.
   41024 **
   41025 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
   41026 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
   41027 ** contents of the entire transaction are rolled back. This is different
   41028 ** from a normal transaction rollback, as no locks are released and the
   41029 ** transaction remains open.
   41030 */
   41031 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
   41032   int rc = SQLITE_OK;
   41033   if( p && p->inTrans==TRANS_WRITE ){
   41034     BtShared *pBt = p->pBt;
   41035     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
   41036     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
   41037     sqlite3BtreeEnter(p);
   41038     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
   41039     if( rc==SQLITE_OK ){
   41040       rc = newDatabase(pBt);
   41041     }
   41042     sqlite3BtreeLeave(p);
   41043   }
   41044   return rc;
   41045 }
   41046 
   41047 /*
   41048 ** Create a new cursor for the BTree whose root is on the page
   41049 ** iTable. If a read-only cursor is requested, it is assumed that
   41050 ** the caller already has at least a read-only transaction open
   41051 ** on the database already. If a write-cursor is requested, then
   41052 ** the caller is assumed to have an open write transaction.
   41053 **
   41054 ** If wrFlag==0, then the cursor can only be used for reading.
   41055 ** If wrFlag==1, then the cursor can be used for reading or for
   41056 ** writing if other conditions for writing are also met.  These
   41057 ** are the conditions that must be met in order for writing to
   41058 ** be allowed:
   41059 **
   41060 ** 1:  The cursor must have been opened with wrFlag==1
   41061 **
   41062 ** 2:  Other database connections that share the same pager cache
   41063 **     but which are not in the READ_UNCOMMITTED state may not have
   41064 **     cursors open with wrFlag==0 on the same table.  Otherwise
   41065 **     the changes made by this write cursor would be visible to
   41066 **     the read cursors in the other database connection.
   41067 **
   41068 ** 3:  The database must be writable (not on read-only media)
   41069 **
   41070 ** 4:  There must be an active transaction.
   41071 **
   41072 ** No checking is done to make sure that page iTable really is the
   41073 ** root page of a b-tree.  If it is not, then the cursor acquired
   41074 ** will not work correctly.
   41075 **
   41076 ** It is assumed that the sqlite3BtreeCursorZero() has been called
   41077 ** on pCur to initialize the memory space prior to invoking this routine.
   41078 */
   41079 static int btreeCursor(
   41080   Btree *p,                              /* The btree */
   41081   int iTable,                            /* Root page of table to open */
   41082   int wrFlag,                            /* 1 to write. 0 read-only */
   41083   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
   41084   BtCursor *pCur                         /* Space for new cursor */
   41085 ){
   41086   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
   41087 
   41088   assert( sqlite3BtreeHoldsMutex(p) );
   41089   assert( wrFlag==0 || wrFlag==1 );
   41090 
   41091   /* The following assert statements verify that if this is a sharable
   41092   ** b-tree database, the connection is holding the required table locks,
   41093   ** and that no other connection has any open cursor that conflicts with
   41094   ** this lock.  */
   41095   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
   41096   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
   41097 
   41098   /* Assert that the caller has opened the required transaction. */
   41099   assert( p->inTrans>TRANS_NONE );
   41100   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
   41101   assert( pBt->pPage1 && pBt->pPage1->aData );
   41102 
   41103   if( NEVER(wrFlag && pBt->readOnly) ){
   41104     return SQLITE_READONLY;
   41105   }
   41106   if( iTable==1 && pagerPagecount(pBt)==0 ){
   41107     return SQLITE_EMPTY;
   41108   }
   41109 
   41110   /* Now that no other errors can occur, finish filling in the BtCursor
   41111   ** variables and link the cursor into the BtShared list.  */
   41112   pCur->pgnoRoot = (Pgno)iTable;
   41113   pCur->iPage = -1;
   41114   pCur->pKeyInfo = pKeyInfo;
   41115   pCur->pBtree = p;
   41116   pCur->pBt = pBt;
   41117   pCur->wrFlag = (u8)wrFlag;
   41118   pCur->pNext = pBt->pCursor;
   41119   if( pCur->pNext ){
   41120     pCur->pNext->pPrev = pCur;
   41121   }
   41122   pBt->pCursor = pCur;
   41123   pCur->eState = CURSOR_INVALID;
   41124   pCur->cachedRowid = 0;
   41125   return SQLITE_OK;
   41126 }
   41127 SQLITE_PRIVATE int sqlite3BtreeCursor(
   41128   Btree *p,                                   /* The btree */
   41129   int iTable,                                 /* Root page of table to open */
   41130   int wrFlag,                                 /* 1 to write. 0 read-only */
   41131   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
   41132   BtCursor *pCur                              /* Write new cursor here */
   41133 ){
   41134   int rc;
   41135   sqlite3BtreeEnter(p);
   41136   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
   41137   sqlite3BtreeLeave(p);
   41138   return rc;
   41139 }
   41140 
   41141 /*
   41142 ** Return the size of a BtCursor object in bytes.
   41143 **
   41144 ** This interfaces is needed so that users of cursors can preallocate
   41145 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
   41146 ** to users so they cannot do the sizeof() themselves - they must call
   41147 ** this routine.
   41148 */
   41149 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
   41150   return ROUND8(sizeof(BtCursor));
   41151 }
   41152 
   41153 /*
   41154 ** Initialize memory that will be converted into a BtCursor object.
   41155 **
   41156 ** The simple approach here would be to memset() the entire object
   41157 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
   41158 ** do not need to be zeroed and they are large, so we can save a lot
   41159 ** of run-time by skipping the initialization of those elements.
   41160 */
   41161 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
   41162   memset(p, 0, offsetof(BtCursor, iPage));
   41163 }
   41164 
   41165 /*
   41166 ** Set the cached rowid value of every cursor in the same database file
   41167 ** as pCur and having the same root page number as pCur.  The value is
   41168 ** set to iRowid.
   41169 **
   41170 ** Only positive rowid values are considered valid for this cache.
   41171 ** The cache is initialized to zero, indicating an invalid cache.
   41172 ** A btree will work fine with zero or negative rowids.  We just cannot
   41173 ** cache zero or negative rowids, which means tables that use zero or
   41174 ** negative rowids might run a little slower.  But in practice, zero
   41175 ** or negative rowids are very uncommon so this should not be a problem.
   41176 */
   41177 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
   41178   BtCursor *p;
   41179   for(p=pCur->pBt->pCursor; p; p=p->pNext){
   41180     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
   41181   }
   41182   assert( pCur->cachedRowid==iRowid );
   41183 }
   41184 
   41185 /*
   41186 ** Return the cached rowid for the given cursor.  A negative or zero
   41187 ** return value indicates that the rowid cache is invalid and should be
   41188 ** ignored.  If the rowid cache has never before been set, then a
   41189 ** zero is returned.
   41190 */
   41191 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
   41192   return pCur->cachedRowid;
   41193 }
   41194 
   41195 /*
   41196 ** Close a cursor.  The read lock on the database file is released
   41197 ** when the last cursor is closed.
   41198 */
   41199 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
   41200   Btree *pBtree = pCur->pBtree;
   41201   if( pBtree ){
   41202     int i;
   41203     BtShared *pBt = pCur->pBt;
   41204     sqlite3BtreeEnter(pBtree);
   41205     sqlite3BtreeClearCursor(pCur);
   41206     if( pCur->pPrev ){
   41207       pCur->pPrev->pNext = pCur->pNext;
   41208     }else{
   41209       pBt->pCursor = pCur->pNext;
   41210     }
   41211     if( pCur->pNext ){
   41212       pCur->pNext->pPrev = pCur->pPrev;
   41213     }
   41214     for(i=0; i<=pCur->iPage; i++){
   41215       releasePage(pCur->apPage[i]);
   41216     }
   41217     unlockBtreeIfUnused(pBt);
   41218     invalidateOverflowCache(pCur);
   41219     /* sqlite3_free(pCur); */
   41220     sqlite3BtreeLeave(pBtree);
   41221   }
   41222   return SQLITE_OK;
   41223 }
   41224 
   41225 /*
   41226 ** Make sure the BtCursor* given in the argument has a valid
   41227 ** BtCursor.info structure.  If it is not already valid, call
   41228 ** btreeParseCell() to fill it in.
   41229 **
   41230 ** BtCursor.info is a cache of the information in the current cell.
   41231 ** Using this cache reduces the number of calls to btreeParseCell().
   41232 **
   41233 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
   41234 ** compiler to crash when getCellInfo() is implemented as a macro.
   41235 ** But there is a measureable speed advantage to using the macro on gcc
   41236 ** (when less compiler optimizations like -Os or -O0 are used and the
   41237 ** compiler is not doing agressive inlining.)  So we use a real function
   41238 ** for MSVC and a macro for everything else.  Ticket #2457.
   41239 */
   41240 #ifndef NDEBUG
   41241   static void assertCellInfo(BtCursor *pCur){
   41242     CellInfo info;
   41243     int iPage = pCur->iPage;
   41244     memset(&info, 0, sizeof(info));
   41245     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
   41246     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
   41247   }
   41248 #else
   41249   #define assertCellInfo(x)
   41250 #endif
   41251 #ifdef _MSC_VER
   41252   /* Use a real function in MSVC to work around bugs in that compiler. */
   41253   static void getCellInfo(BtCursor *pCur){
   41254     if( pCur->info.nSize==0 ){
   41255       int iPage = pCur->iPage;
   41256       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
   41257       pCur->validNKey = 1;
   41258     }else{
   41259       assertCellInfo(pCur);
   41260     }
   41261   }
   41262 #else /* if not _MSC_VER */
   41263   /* Use a macro in all other compilers so that the function is inlined */
   41264 #define getCellInfo(pCur)                                                      \
   41265   if( pCur->info.nSize==0 ){                                                   \
   41266     int iPage = pCur->iPage;                                                   \
   41267     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
   41268     pCur->validNKey = 1;                                                       \
   41269   }else{                                                                       \
   41270     assertCellInfo(pCur);                                                      \
   41271   }
   41272 #endif /* _MSC_VER */
   41273 
   41274 #ifndef NDEBUG  /* The next routine used only within assert() statements */
   41275 /*
   41276 ** Return true if the given BtCursor is valid.  A valid cursor is one
   41277 ** that is currently pointing to a row in a (non-empty) table.
   41278 ** This is a verification routine is used only within assert() statements.
   41279 */
   41280 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
   41281   return pCur && pCur->eState==CURSOR_VALID;
   41282 }
   41283 #endif /* NDEBUG */
   41284 
   41285 /*
   41286 ** Set *pSize to the size of the buffer needed to hold the value of
   41287 ** the key for the current entry.  If the cursor is not pointing
   41288 ** to a valid entry, *pSize is set to 0.
   41289 **
   41290 ** For a table with the INTKEY flag set, this routine returns the key
   41291 ** itself, not the number of bytes in the key.
   41292 **
   41293 ** The caller must position the cursor prior to invoking this routine.
   41294 **
   41295 ** This routine cannot fail.  It always returns SQLITE_OK.
   41296 */
   41297 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
   41298   assert( cursorHoldsMutex(pCur) );
   41299   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
   41300   if( pCur->eState!=CURSOR_VALID ){
   41301     *pSize = 0;
   41302   }else{
   41303     getCellInfo(pCur);
   41304     *pSize = pCur->info.nKey;
   41305   }
   41306   return SQLITE_OK;
   41307 }
   41308 
   41309 /*
   41310 ** Set *pSize to the number of bytes of data in the entry the
   41311 ** cursor currently points to.
   41312 **
   41313 ** The caller must guarantee that the cursor is pointing to a non-NULL
   41314 ** valid entry.  In other words, the calling procedure must guarantee
   41315 ** that the cursor has Cursor.eState==CURSOR_VALID.
   41316 **
   41317 ** Failure is not possible.  This function always returns SQLITE_OK.
   41318 ** It might just as well be a procedure (returning void) but we continue
   41319 ** to return an integer result code for historical reasons.
   41320 */
   41321 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
   41322   assert( cursorHoldsMutex(pCur) );
   41323   assert( pCur->eState==CURSOR_VALID );
   41324   getCellInfo(pCur);
   41325   *pSize = pCur->info.nData;
   41326   return SQLITE_OK;
   41327 }
   41328 
   41329 /*
   41330 ** Given the page number of an overflow page in the database (parameter
   41331 ** ovfl), this function finds the page number of the next page in the
   41332 ** linked list of overflow pages. If possible, it uses the auto-vacuum
   41333 ** pointer-map data instead of reading the content of page ovfl to do so.
   41334 **
   41335 ** If an error occurs an SQLite error code is returned. Otherwise:
   41336 **
   41337 ** The page number of the next overflow page in the linked list is
   41338 ** written to *pPgnoNext. If page ovfl is the last page in its linked
   41339 ** list, *pPgnoNext is set to zero.
   41340 **
   41341 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
   41342 ** to page number pOvfl was obtained, then *ppPage is set to point to that
   41343 ** reference. It is the responsibility of the caller to call releasePage()
   41344 ** on *ppPage to free the reference. In no reference was obtained (because
   41345 ** the pointer-map was used to obtain the value for *pPgnoNext), then
   41346 ** *ppPage is set to zero.
   41347 */
   41348 static int getOverflowPage(
   41349   BtShared *pBt,               /* The database file */
   41350   Pgno ovfl,                   /* Current overflow page number */
   41351   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
   41352   Pgno *pPgnoNext              /* OUT: Next overflow page number */
   41353 ){
   41354   Pgno next = 0;
   41355   MemPage *pPage = 0;
   41356   int rc = SQLITE_OK;
   41357 
   41358   assert( sqlite3_mutex_held(pBt->mutex) );
   41359   assert(pPgnoNext);
   41360 
   41361 #ifndef SQLITE_OMIT_AUTOVACUUM
   41362   /* Try to find the next page in the overflow list using the
   41363   ** autovacuum pointer-map pages. Guess that the next page in
   41364   ** the overflow list is page number (ovfl+1). If that guess turns
   41365   ** out to be wrong, fall back to loading the data of page
   41366   ** number ovfl to determine the next page number.
   41367   */
   41368   if( pBt->autoVacuum ){
   41369     Pgno pgno;
   41370     Pgno iGuess = ovfl+1;
   41371     u8 eType;
   41372 
   41373     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
   41374       iGuess++;
   41375     }
   41376 
   41377     if( iGuess<=pagerPagecount(pBt) ){
   41378       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
   41379       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
   41380         next = iGuess;
   41381         rc = SQLITE_DONE;
   41382       }
   41383     }
   41384   }
   41385 #endif
   41386 
   41387   assert( next==0 || rc==SQLITE_DONE );
   41388   if( rc==SQLITE_OK ){
   41389     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
   41390     assert( rc==SQLITE_OK || pPage==0 );
   41391     if( rc==SQLITE_OK ){
   41392       next = get4byte(pPage->aData);
   41393     }
   41394   }
   41395 
   41396   *pPgnoNext = next;
   41397   if( ppPage ){
   41398     *ppPage = pPage;
   41399   }else{
   41400     releasePage(pPage);
   41401   }
   41402   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
   41403 }
   41404 
   41405 /*
   41406 ** Copy data from a buffer to a page, or from a page to a buffer.
   41407 **
   41408 ** pPayload is a pointer to data stored on database page pDbPage.
   41409 ** If argument eOp is false, then nByte bytes of data are copied
   41410 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
   41411 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
   41412 ** of data are copied from the buffer pBuf to pPayload.
   41413 **
   41414 ** SQLITE_OK is returned on success, otherwise an error code.
   41415 */
   41416 static int copyPayload(
   41417   void *pPayload,           /* Pointer to page data */
   41418   void *pBuf,               /* Pointer to buffer */
   41419   int nByte,                /* Number of bytes to copy */
   41420   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
   41421   DbPage *pDbPage           /* Page containing pPayload */
   41422 ){
   41423   if( eOp ){
   41424     /* Copy data from buffer to page (a write operation) */
   41425     int rc = sqlite3PagerWrite(pDbPage);
   41426     if( rc!=SQLITE_OK ){
   41427       return rc;
   41428     }
   41429     memcpy(pPayload, pBuf, nByte);
   41430   }else{
   41431     /* Copy data from page to buffer (a read operation) */
   41432     memcpy(pBuf, pPayload, nByte);
   41433   }
   41434   return SQLITE_OK;
   41435 }
   41436 
   41437 /*
   41438 ** This function is used to read or overwrite payload information
   41439 ** for the entry that the pCur cursor is pointing to. If the eOp
   41440 ** parameter is 0, this is a read operation (data copied into
   41441 ** buffer pBuf). If it is non-zero, a write (data copied from
   41442 ** buffer pBuf).
   41443 **
   41444 ** A total of "amt" bytes are read or written beginning at "offset".
   41445 ** Data is read to or from the buffer pBuf.
   41446 **
   41447 ** The content being read or written might appear on the main page
   41448 ** or be scattered out on multiple overflow pages.
   41449 **
   41450 ** If the BtCursor.isIncrblobHandle flag is set, and the current
   41451 ** cursor entry uses one or more overflow pages, this function
   41452 ** allocates space for and lazily popluates the overflow page-list
   41453 ** cache array (BtCursor.aOverflow). Subsequent calls use this
   41454 ** cache to make seeking to the supplied offset more efficient.
   41455 **
   41456 ** Once an overflow page-list cache has been allocated, it may be
   41457 ** invalidated if some other cursor writes to the same table, or if
   41458 ** the cursor is moved to a different row. Additionally, in auto-vacuum
   41459 ** mode, the following events may invalidate an overflow page-list cache.
   41460 **
   41461 **   * An incremental vacuum,
   41462 **   * A commit in auto_vacuum="full" mode,
   41463 **   * Creating a table (may require moving an overflow page).
   41464 */
   41465 static int accessPayload(
   41466   BtCursor *pCur,      /* Cursor pointing to entry to read from */
   41467   u32 offset,          /* Begin reading this far into payload */
   41468   u32 amt,             /* Read this many bytes */
   41469   unsigned char *pBuf, /* Write the bytes into this buffer */
   41470   int eOp              /* zero to read. non-zero to write. */
   41471 ){
   41472   unsigned char *aPayload;
   41473   int rc = SQLITE_OK;
   41474   u32 nKey;
   41475   int iIdx = 0;
   41476   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
   41477   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
   41478 
   41479   assert( pPage );
   41480   assert( pCur->eState==CURSOR_VALID );
   41481   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
   41482   assert( cursorHoldsMutex(pCur) );
   41483 
   41484   getCellInfo(pCur);
   41485   aPayload = pCur->info.pCell + pCur->info.nHeader;
   41486   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
   41487 
   41488   if( NEVER(offset+amt > nKey+pCur->info.nData)
   41489    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
   41490   ){
   41491     /* Trying to read or write past the end of the data is an error */
   41492     return SQLITE_CORRUPT_BKPT;
   41493   }
   41494 
   41495   /* Check if data must be read/written to/from the btree page itself. */
   41496   if( offset<pCur->info.nLocal ){
   41497     int a = amt;
   41498     if( a+offset>pCur->info.nLocal ){
   41499       a = pCur->info.nLocal - offset;
   41500     }
   41501     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
   41502     offset = 0;
   41503     pBuf += a;
   41504     amt -= a;
   41505   }else{
   41506     offset -= pCur->info.nLocal;
   41507   }
   41508 
   41509   if( rc==SQLITE_OK && amt>0 ){
   41510     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
   41511     Pgno nextPage;
   41512 
   41513     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
   41514 
   41515 #ifndef SQLITE_OMIT_INCRBLOB
   41516     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
   41517     ** has not been allocated, allocate it now. The array is sized at
   41518     ** one entry for each overflow page in the overflow chain. The
   41519     ** page number of the first overflow page is stored in aOverflow[0],
   41520     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
   41521     ** (the cache is lazily populated).
   41522     */
   41523     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
   41524       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
   41525       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
   41526       /* nOvfl is always positive.  If it were zero, fetchPayload would have
   41527       ** been used instead of this routine. */
   41528       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
   41529         rc = SQLITE_NOMEM;
   41530       }
   41531     }
   41532 
   41533     /* If the overflow page-list cache has been allocated and the
   41534     ** entry for the first required overflow page is valid, skip
   41535     ** directly to it.
   41536     */
   41537     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
   41538       iIdx = (offset/ovflSize);
   41539       nextPage = pCur->aOverflow[iIdx];
   41540       offset = (offset%ovflSize);
   41541     }
   41542 #endif
   41543 
   41544     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
   41545 
   41546 #ifndef SQLITE_OMIT_INCRBLOB
   41547       /* If required, populate the overflow page-list cache. */
   41548       if( pCur->aOverflow ){
   41549         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
   41550         pCur->aOverflow[iIdx] = nextPage;
   41551       }
   41552 #endif
   41553 
   41554       if( offset>=ovflSize ){
   41555         /* The only reason to read this page is to obtain the page
   41556         ** number for the next page in the overflow chain. The page
   41557         ** data is not required. So first try to lookup the overflow
   41558         ** page-list cache, if any, then fall back to the getOverflowPage()
   41559         ** function.
   41560         */
   41561 #ifndef SQLITE_OMIT_INCRBLOB
   41562         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
   41563           nextPage = pCur->aOverflow[iIdx+1];
   41564         } else
   41565 #endif
   41566           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
   41567         offset -= ovflSize;
   41568       }else{
   41569         /* Need to read this page properly. It contains some of the
   41570         ** range of data that is being read (eOp==0) or written (eOp!=0).
   41571         */
   41572         DbPage *pDbPage;
   41573         int a = amt;
   41574         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
   41575         if( rc==SQLITE_OK ){
   41576           aPayload = sqlite3PagerGetData(pDbPage);
   41577           nextPage = get4byte(aPayload);
   41578           if( a + offset > ovflSize ){
   41579             a = ovflSize - offset;
   41580           }
   41581           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
   41582           sqlite3PagerUnref(pDbPage);
   41583           offset = 0;
   41584           amt -= a;
   41585           pBuf += a;
   41586         }
   41587       }
   41588     }
   41589   }
   41590 
   41591   if( rc==SQLITE_OK && amt>0 ){
   41592     return SQLITE_CORRUPT_BKPT;
   41593   }
   41594   return rc;
   41595 }
   41596 
   41597 /*
   41598 ** Read part of the key associated with cursor pCur.  Exactly
   41599 ** "amt" bytes will be transfered into pBuf[].  The transfer
   41600 ** begins at "offset".
   41601 **
   41602 ** The caller must ensure that pCur is pointing to a valid row
   41603 ** in the table.
   41604 **
   41605 ** Return SQLITE_OK on success or an error code if anything goes
   41606 ** wrong.  An error is returned if "offset+amt" is larger than
   41607 ** the available payload.
   41608 */
   41609 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
   41610   assert( cursorHoldsMutex(pCur) );
   41611   assert( pCur->eState==CURSOR_VALID );
   41612   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
   41613   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   41614   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
   41615 }
   41616 
   41617 /*
   41618 ** Read part of the data associated with cursor pCur.  Exactly
   41619 ** "amt" bytes will be transfered into pBuf[].  The transfer
   41620 ** begins at "offset".
   41621 **
   41622 ** Return SQLITE_OK on success or an error code if anything goes
   41623 ** wrong.  An error is returned if "offset+amt" is larger than
   41624 ** the available payload.
   41625 */
   41626 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
   41627   int rc;
   41628 
   41629 #ifndef SQLITE_OMIT_INCRBLOB
   41630   if ( pCur->eState==CURSOR_INVALID ){
   41631     return SQLITE_ABORT;
   41632   }
   41633 #endif
   41634 
   41635   assert( cursorHoldsMutex(pCur) );
   41636   rc = restoreCursorPosition(pCur);
   41637   if( rc==SQLITE_OK ){
   41638     assert( pCur->eState==CURSOR_VALID );
   41639     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
   41640     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   41641     rc = accessPayload(pCur, offset, amt, pBuf, 0);
   41642   }
   41643   return rc;
   41644 }
   41645 
   41646 /*
   41647 ** Return a pointer to payload information from the entry that the
   41648 ** pCur cursor is pointing to.  The pointer is to the beginning of
   41649 ** the key if skipKey==0 and it points to the beginning of data if
   41650 ** skipKey==1.  The number of bytes of available key/data is written
   41651 ** into *pAmt.  If *pAmt==0, then the value returned will not be
   41652 ** a valid pointer.
   41653 **
   41654 ** This routine is an optimization.  It is common for the entire key
   41655 ** and data to fit on the local page and for there to be no overflow
   41656 ** pages.  When that is so, this routine can be used to access the
   41657 ** key and data without making a copy.  If the key and/or data spills
   41658 ** onto overflow pages, then accessPayload() must be used to reassemble
   41659 ** the key/data and copy it into a preallocated buffer.
   41660 **
   41661 ** The pointer returned by this routine looks directly into the cached
   41662 ** page of the database.  The data might change or move the next time
   41663 ** any btree routine is called.
   41664 */
   41665 static const unsigned char *fetchPayload(
   41666   BtCursor *pCur,      /* Cursor pointing to entry to read from */
   41667   int *pAmt,           /* Write the number of available bytes here */
   41668   int skipKey          /* read beginning at data if this is true */
   41669 ){
   41670   unsigned char *aPayload;
   41671   MemPage *pPage;
   41672   u32 nKey;
   41673   u32 nLocal;
   41674 
   41675   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
   41676   assert( pCur->eState==CURSOR_VALID );
   41677   assert( cursorHoldsMutex(pCur) );
   41678   pPage = pCur->apPage[pCur->iPage];
   41679   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
   41680   if( NEVER(pCur->info.nSize==0) ){
   41681     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
   41682                    &pCur->info);
   41683   }
   41684   aPayload = pCur->info.pCell;
   41685   aPayload += pCur->info.nHeader;
   41686   if( pPage->intKey ){
   41687     nKey = 0;
   41688   }else{
   41689     nKey = (int)pCur->info.nKey;
   41690   }
   41691   if( skipKey ){
   41692     aPayload += nKey;
   41693     nLocal = pCur->info.nLocal - nKey;
   41694   }else{
   41695     nLocal = pCur->info.nLocal;
   41696     assert( nLocal<=nKey );
   41697   }
   41698   *pAmt = nLocal;
   41699   return aPayload;
   41700 }
   41701 
   41702 
   41703 /*
   41704 ** For the entry that cursor pCur is point to, return as
   41705 ** many bytes of the key or data as are available on the local
   41706 ** b-tree page.  Write the number of available bytes into *pAmt.
   41707 **
   41708 ** The pointer returned is ephemeral.  The key/data may move
   41709 ** or be destroyed on the next call to any Btree routine,
   41710 ** including calls from other threads against the same cache.
   41711 ** Hence, a mutex on the BtShared should be held prior to calling
   41712 ** this routine.
   41713 **
   41714 ** These routines is used to get quick access to key and data
   41715 ** in the common case where no overflow pages are used.
   41716 */
   41717 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
   41718   const void *p = 0;
   41719   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   41720   assert( cursorHoldsMutex(pCur) );
   41721   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
   41722     p = (const void*)fetchPayload(pCur, pAmt, 0);
   41723   }
   41724   return p;
   41725 }
   41726 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
   41727   const void *p = 0;
   41728   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   41729   assert( cursorHoldsMutex(pCur) );
   41730   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
   41731     p = (const void*)fetchPayload(pCur, pAmt, 1);
   41732   }
   41733   return p;
   41734 }
   41735 
   41736 
   41737 /*
   41738 ** Move the cursor down to a new child page.  The newPgno argument is the
   41739 ** page number of the child page to move to.
   41740 **
   41741 ** This function returns SQLITE_CORRUPT if the page-header flags field of
   41742 ** the new child page does not match the flags field of the parent (i.e.
   41743 ** if an intkey page appears to be the parent of a non-intkey page, or
   41744 ** vice-versa).
   41745 */
   41746 static int moveToChild(BtCursor *pCur, u32 newPgno){
   41747   int rc;
   41748   int i = pCur->iPage;
   41749   MemPage *pNewPage;
   41750   BtShared *pBt = pCur->pBt;
   41751 
   41752   assert( cursorHoldsMutex(pCur) );
   41753   assert( pCur->eState==CURSOR_VALID );
   41754   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
   41755   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
   41756     return SQLITE_CORRUPT_BKPT;
   41757   }
   41758   rc = getAndInitPage(pBt, newPgno, &pNewPage);
   41759   if( rc ) return rc;
   41760   pCur->apPage[i+1] = pNewPage;
   41761   pCur->aiIdx[i+1] = 0;
   41762   pCur->iPage++;
   41763 
   41764   pCur->info.nSize = 0;
   41765   pCur->validNKey = 0;
   41766   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
   41767     return SQLITE_CORRUPT_BKPT;
   41768   }
   41769   return SQLITE_OK;
   41770 }
   41771 
   41772 #ifndef NDEBUG
   41773 /*
   41774 ** Page pParent is an internal (non-leaf) tree page. This function
   41775 ** asserts that page number iChild is the left-child if the iIdx'th
   41776 ** cell in page pParent. Or, if iIdx is equal to the total number of
   41777 ** cells in pParent, that page number iChild is the right-child of
   41778 ** the page.
   41779 */
   41780 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
   41781   assert( iIdx<=pParent->nCell );
   41782   if( iIdx==pParent->nCell ){
   41783     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
   41784   }else{
   41785     assert( get4byte(findCell(pParent, iIdx))==iChild );
   41786   }
   41787 }
   41788 #else
   41789 #  define assertParentIndex(x,y,z)
   41790 #endif
   41791 
   41792 /*
   41793 ** Move the cursor up to the parent page.
   41794 **
   41795 ** pCur->idx is set to the cell index that contains the pointer
   41796 ** to the page we are coming from.  If we are coming from the
   41797 ** right-most child page then pCur->idx is set to one more than
   41798 ** the largest cell index.
   41799 */
   41800 static void moveToParent(BtCursor *pCur){
   41801   assert( cursorHoldsMutex(pCur) );
   41802   assert( pCur->eState==CURSOR_VALID );
   41803   assert( pCur->iPage>0 );
   41804   assert( pCur->apPage[pCur->iPage] );
   41805   assertParentIndex(
   41806     pCur->apPage[pCur->iPage-1],
   41807     pCur->aiIdx[pCur->iPage-1],
   41808     pCur->apPage[pCur->iPage]->pgno
   41809   );
   41810   releasePage(pCur->apPage[pCur->iPage]);
   41811   pCur->iPage--;
   41812   pCur->info.nSize = 0;
   41813   pCur->validNKey = 0;
   41814 }
   41815 
   41816 /*
   41817 ** Move the cursor to point to the root page of its b-tree structure.
   41818 **
   41819 ** If the table has a virtual root page, then the cursor is moved to point
   41820 ** to the virtual root page instead of the actual root page. A table has a
   41821 ** virtual root page when the actual root page contains no cells and a
   41822 ** single child page. This can only happen with the table rooted at page 1.
   41823 **
   41824 ** If the b-tree structure is empty, the cursor state is set to
   41825 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
   41826 ** cell located on the root (or virtual root) page and the cursor state
   41827 ** is set to CURSOR_VALID.
   41828 **
   41829 ** If this function returns successfully, it may be assumed that the
   41830 ** page-header flags indicate that the [virtual] root-page is the expected
   41831 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
   41832 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
   41833 ** indicating a table b-tree, or if the caller did specify a KeyInfo
   41834 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
   41835 ** b-tree).
   41836 */
   41837 static int moveToRoot(BtCursor *pCur){
   41838   MemPage *pRoot;
   41839   int rc = SQLITE_OK;
   41840   Btree *p = pCur->pBtree;
   41841   BtShared *pBt = p->pBt;
   41842 
   41843   assert( cursorHoldsMutex(pCur) );
   41844   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
   41845   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
   41846   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
   41847   if( pCur->eState>=CURSOR_REQUIRESEEK ){
   41848     if( pCur->eState==CURSOR_FAULT ){
   41849       assert( pCur->skipNext!=SQLITE_OK );
   41850       return pCur->skipNext;
   41851     }
   41852     sqlite3BtreeClearCursor(pCur);
   41853   }
   41854 
   41855   if( pCur->iPage>=0 ){
   41856     int i;
   41857     for(i=1; i<=pCur->iPage; i++){
   41858       releasePage(pCur->apPage[i]);
   41859     }
   41860     pCur->iPage = 0;
   41861   }else{
   41862     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
   41863     if( rc!=SQLITE_OK ){
   41864       pCur->eState = CURSOR_INVALID;
   41865       return rc;
   41866     }
   41867     pCur->iPage = 0;
   41868 
   41869     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
   41870     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
   41871     ** NULL, the caller expects a table b-tree. If this is not the case,
   41872     ** return an SQLITE_CORRUPT error.  */
   41873     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
   41874     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
   41875       return SQLITE_CORRUPT_BKPT;
   41876     }
   41877   }
   41878 
   41879   /* Assert that the root page is of the correct type. This must be the
   41880   ** case as the call to this function that loaded the root-page (either
   41881   ** this call or a previous invocation) would have detected corruption
   41882   ** if the assumption were not true, and it is not possible for the flags
   41883   ** byte to have been modified while this cursor is holding a reference
   41884   ** to the page.  */
   41885   pRoot = pCur->apPage[0];
   41886   assert( pRoot->pgno==pCur->pgnoRoot );
   41887   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
   41888 
   41889   pCur->aiIdx[0] = 0;
   41890   pCur->info.nSize = 0;
   41891   pCur->atLast = 0;
   41892   pCur->validNKey = 0;
   41893 
   41894   if( pRoot->nCell==0 && !pRoot->leaf ){
   41895     Pgno subpage;
   41896     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
   41897     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
   41898     pCur->eState = CURSOR_VALID;
   41899     rc = moveToChild(pCur, subpage);
   41900   }else{
   41901     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
   41902   }
   41903   return rc;
   41904 }
   41905 
   41906 /*
   41907 ** Move the cursor down to the left-most leaf entry beneath the
   41908 ** entry to which it is currently pointing.
   41909 **
   41910 ** The left-most leaf is the one with the smallest key - the first
   41911 ** in ascending order.
   41912 */
   41913 static int moveToLeftmost(BtCursor *pCur){
   41914   Pgno pgno;
   41915   int rc = SQLITE_OK;
   41916   MemPage *pPage;
   41917 
   41918   assert( cursorHoldsMutex(pCur) );
   41919   assert( pCur->eState==CURSOR_VALID );
   41920   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
   41921     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
   41922     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
   41923     rc = moveToChild(pCur, pgno);
   41924   }
   41925   return rc;
   41926 }
   41927 
   41928 /*
   41929 ** Move the cursor down to the right-most leaf entry beneath the
   41930 ** page to which it is currently pointing.  Notice the difference
   41931 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
   41932 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
   41933 ** finds the right-most entry beneath the *page*.
   41934 **
   41935 ** The right-most entry is the one with the largest key - the last
   41936 ** key in ascending order.
   41937 */
   41938 static int moveToRightmost(BtCursor *pCur){
   41939   Pgno pgno;
   41940   int rc = SQLITE_OK;
   41941   MemPage *pPage = 0;
   41942 
   41943   assert( cursorHoldsMutex(pCur) );
   41944   assert( pCur->eState==CURSOR_VALID );
   41945   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
   41946     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   41947     pCur->aiIdx[pCur->iPage] = pPage->nCell;
   41948     rc = moveToChild(pCur, pgno);
   41949   }
   41950   if( rc==SQLITE_OK ){
   41951     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
   41952     pCur->info.nSize = 0;
   41953     pCur->validNKey = 0;
   41954   }
   41955   return rc;
   41956 }
   41957 
   41958 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
   41959 ** on success.  Set *pRes to 0 if the cursor actually points to something
   41960 ** or set *pRes to 1 if the table is empty.
   41961 */
   41962 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
   41963   int rc;
   41964 
   41965   assert( cursorHoldsMutex(pCur) );
   41966   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   41967   rc = moveToRoot(pCur);
   41968   if( rc==SQLITE_OK ){
   41969     if( pCur->eState==CURSOR_INVALID ){
   41970       assert( pCur->apPage[pCur->iPage]->nCell==0 );
   41971       *pRes = 1;
   41972       rc = SQLITE_OK;
   41973     }else{
   41974       assert( pCur->apPage[pCur->iPage]->nCell>0 );
   41975       *pRes = 0;
   41976       rc = moveToLeftmost(pCur);
   41977     }
   41978   }
   41979   return rc;
   41980 }
   41981 
   41982 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
   41983 ** on success.  Set *pRes to 0 if the cursor actually points to something
   41984 ** or set *pRes to 1 if the table is empty.
   41985 */
   41986 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
   41987   int rc;
   41988 
   41989   assert( cursorHoldsMutex(pCur) );
   41990   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   41991 
   41992   /* If the cursor already points to the last entry, this is a no-op. */
   41993   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
   41994 #ifdef SQLITE_DEBUG
   41995     /* This block serves to assert() that the cursor really does point
   41996     ** to the last entry in the b-tree. */
   41997     int ii;
   41998     for(ii=0; ii<pCur->iPage; ii++){
   41999       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
   42000     }
   42001     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
   42002     assert( pCur->apPage[pCur->iPage]->leaf );
   42003 #endif
   42004     return SQLITE_OK;
   42005   }
   42006 
   42007   rc = moveToRoot(pCur);
   42008   if( rc==SQLITE_OK ){
   42009     if( CURSOR_INVALID==pCur->eState ){
   42010       assert( pCur->apPage[pCur->iPage]->nCell==0 );
   42011       *pRes = 1;
   42012     }else{
   42013       assert( pCur->eState==CURSOR_VALID );
   42014       *pRes = 0;
   42015       rc = moveToRightmost(pCur);
   42016       pCur->atLast = rc==SQLITE_OK ?1:0;
   42017     }
   42018   }
   42019   return rc;
   42020 }
   42021 
   42022 /* Move the cursor so that it points to an entry near the key
   42023 ** specified by pIdxKey or intKey.   Return a success code.
   42024 **
   42025 ** For INTKEY tables, the intKey parameter is used.  pIdxKey
   42026 ** must be NULL.  For index tables, pIdxKey is used and intKey
   42027 ** is ignored.
   42028 **
   42029 ** If an exact match is not found, then the cursor is always
   42030 ** left pointing at a leaf page which would hold the entry if it
   42031 ** were present.  The cursor might point to an entry that comes
   42032 ** before or after the key.
   42033 **
   42034 ** An integer is written into *pRes which is the result of
   42035 ** comparing the key with the entry to which the cursor is
   42036 ** pointing.  The meaning of the integer written into
   42037 ** *pRes is as follows:
   42038 **
   42039 **     *pRes<0      The cursor is left pointing at an entry that
   42040 **                  is smaller than intKey/pIdxKey or if the table is empty
   42041 **                  and the cursor is therefore left point to nothing.
   42042 **
   42043 **     *pRes==0     The cursor is left pointing at an entry that
   42044 **                  exactly matches intKey/pIdxKey.
   42045 **
   42046 **     *pRes>0      The cursor is left pointing at an entry that
   42047 **                  is larger than intKey/pIdxKey.
   42048 **
   42049 */
   42050 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
   42051   BtCursor *pCur,          /* The cursor to be moved */
   42052   UnpackedRecord *pIdxKey, /* Unpacked index key */
   42053   i64 intKey,              /* The table key */
   42054   int biasRight,           /* If true, bias the search to the high end */
   42055   int *pRes                /* Write search results here */
   42056 ){
   42057   int rc;
   42058 
   42059   assert( cursorHoldsMutex(pCur) );
   42060   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   42061   assert( pRes );
   42062   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
   42063 
   42064   /* If the cursor is already positioned at the point we are trying
   42065   ** to move to, then just return without doing any work */
   42066   if( pCur->eState==CURSOR_VALID && pCur->validNKey
   42067    && pCur->apPage[0]->intKey
   42068   ){
   42069     if( pCur->info.nKey==intKey ){
   42070       *pRes = 0;
   42071       return SQLITE_OK;
   42072     }
   42073     if( pCur->atLast && pCur->info.nKey<intKey ){
   42074       *pRes = -1;
   42075       return SQLITE_OK;
   42076     }
   42077   }
   42078 
   42079   rc = moveToRoot(pCur);
   42080   if( rc ){
   42081     return rc;
   42082   }
   42083   assert( pCur->apPage[pCur->iPage] );
   42084   assert( pCur->apPage[pCur->iPage]->isInit );
   42085   assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
   42086   if( pCur->eState==CURSOR_INVALID ){
   42087     *pRes = -1;
   42088     assert( pCur->apPage[pCur->iPage]->nCell==0 );
   42089     return SQLITE_OK;
   42090   }
   42091   assert( pCur->apPage[0]->intKey || pIdxKey );
   42092   for(;;){
   42093     int lwr, upr;
   42094     Pgno chldPg;
   42095     MemPage *pPage = pCur->apPage[pCur->iPage];
   42096     int c;
   42097 
   42098     /* pPage->nCell must be greater than zero. If this is the root-page
   42099     ** the cursor would have been INVALID above and this for(;;) loop
   42100     ** not run. If this is not the root-page, then the moveToChild() routine
   42101     ** would have already detected db corruption. Similarly, pPage must
   42102     ** be the right kind (index or table) of b-tree page. Otherwise
   42103     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
   42104     assert( pPage->nCell>0 );
   42105     assert( pPage->intKey==(pIdxKey==0) );
   42106     lwr = 0;
   42107     upr = pPage->nCell-1;
   42108     if( biasRight ){
   42109       pCur->aiIdx[pCur->iPage] = (u16)upr;
   42110     }else{
   42111       pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
   42112     }
   42113     for(;;){
   42114       int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
   42115       u8 *pCell;                          /* Pointer to current cell in pPage */
   42116 
   42117       pCur->info.nSize = 0;
   42118       pCell = findCell(pPage, idx) + pPage->childPtrSize;
   42119       if( pPage->intKey ){
   42120         i64 nCellKey;
   42121         if( pPage->hasData ){
   42122           u32 dummy;
   42123           pCell += getVarint32(pCell, dummy);
   42124         }
   42125         getVarint(pCell, (u64*)&nCellKey);
   42126         if( nCellKey==intKey ){
   42127           c = 0;
   42128         }else if( nCellKey<intKey ){
   42129           c = -1;
   42130         }else{
   42131           assert( nCellKey>intKey );
   42132           c = +1;
   42133         }
   42134         pCur->validNKey = 1;
   42135         pCur->info.nKey = nCellKey;
   42136       }else{
   42137         /* The maximum supported page-size is 32768 bytes. This means that
   42138         ** the maximum number of record bytes stored on an index B-Tree
   42139         ** page is at most 8198 bytes, which may be stored as a 2-byte
   42140         ** varint. This information is used to attempt to avoid parsing
   42141         ** the entire cell by checking for the cases where the record is
   42142         ** stored entirely within the b-tree page by inspecting the first
   42143         ** 2 bytes of the cell.
   42144         */
   42145         int nCell = pCell[0];
   42146         if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
   42147           /* This branch runs if the record-size field of the cell is a
   42148           ** single byte varint and the record fits entirely on the main
   42149           ** b-tree page.  */
   42150           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
   42151         }else if( !(pCell[1] & 0x80)
   42152           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
   42153         ){
   42154           /* The record-size field is a 2 byte varint and the record
   42155           ** fits entirely on the main b-tree page.  */
   42156           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
   42157         }else{
   42158           /* The record flows over onto one or more overflow pages. In
   42159           ** this case the whole cell needs to be parsed, a buffer allocated
   42160           ** and accessPayload() used to retrieve the record into the
   42161           ** buffer before VdbeRecordCompare() can be called. */
   42162           void *pCellKey;
   42163           u8 * const pCellBody = pCell - pPage->childPtrSize;
   42164           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
   42165           nCell = (int)pCur->info.nKey;
   42166           pCellKey = sqlite3Malloc( nCell );
   42167           if( pCellKey==0 ){
   42168             rc = SQLITE_NOMEM;
   42169             goto moveto_finish;
   42170           }
   42171           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
   42172           if( rc ){
   42173             sqlite3_free(pCellKey);
   42174             goto moveto_finish;
   42175           }
   42176           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
   42177           sqlite3_free(pCellKey);
   42178         }
   42179       }
   42180       if( c==0 ){
   42181         if( pPage->intKey && !pPage->leaf ){
   42182           lwr = idx;
   42183           upr = lwr - 1;
   42184           break;
   42185         }else{
   42186           *pRes = 0;
   42187           rc = SQLITE_OK;
   42188           goto moveto_finish;
   42189         }
   42190       }
   42191       if( c<0 ){
   42192         lwr = idx+1;
   42193       }else{
   42194         upr = idx-1;
   42195       }
   42196       if( lwr>upr ){
   42197         break;
   42198       }
   42199       pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
   42200     }
   42201     assert( lwr==upr+1 );
   42202     assert( pPage->isInit );
   42203     if( pPage->leaf ){
   42204       chldPg = 0;
   42205     }else if( lwr>=pPage->nCell ){
   42206       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   42207     }else{
   42208       chldPg = get4byte(findCell(pPage, lwr));
   42209     }
   42210     if( chldPg==0 ){
   42211       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   42212       *pRes = c;
   42213       rc = SQLITE_OK;
   42214       goto moveto_finish;
   42215     }
   42216     pCur->aiIdx[pCur->iPage] = (u16)lwr;
   42217     pCur->info.nSize = 0;
   42218     pCur->validNKey = 0;
   42219     rc = moveToChild(pCur, chldPg);
   42220     if( rc ) goto moveto_finish;
   42221   }
   42222 moveto_finish:
   42223   return rc;
   42224 }
   42225 
   42226 
   42227 /*
   42228 ** Return TRUE if the cursor is not pointing at an entry of the table.
   42229 **
   42230 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
   42231 ** past the last entry in the table or sqlite3BtreePrev() moves past
   42232 ** the first entry.  TRUE is also returned if the table is empty.
   42233 */
   42234 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
   42235   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
   42236   ** have been deleted? This API will need to change to return an error code
   42237   ** as well as the boolean result value.
   42238   */
   42239   return (CURSOR_VALID!=pCur->eState);
   42240 }
   42241 
   42242 /*
   42243 ** Advance the cursor to the next entry in the database.  If
   42244 ** successful then set *pRes=0.  If the cursor
   42245 ** was already pointing to the last entry in the database before
   42246 ** this routine was called, then set *pRes=1.
   42247 */
   42248 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
   42249   int rc;
   42250   int idx;
   42251   MemPage *pPage;
   42252 
   42253   assert( cursorHoldsMutex(pCur) );
   42254   rc = restoreCursorPosition(pCur);
   42255   if( rc!=SQLITE_OK ){
   42256     return rc;
   42257   }
   42258   assert( pRes!=0 );
   42259   if( CURSOR_INVALID==pCur->eState ){
   42260     *pRes = 1;
   42261     return SQLITE_OK;
   42262   }
   42263   if( pCur->skipNext>0 ){
   42264     pCur->skipNext = 0;
   42265     *pRes = 0;
   42266     return SQLITE_OK;
   42267   }
   42268   pCur->skipNext = 0;
   42269 
   42270   pPage = pCur->apPage[pCur->iPage];
   42271   idx = ++pCur->aiIdx[pCur->iPage];
   42272   assert( pPage->isInit );
   42273   assert( idx<=pPage->nCell );
   42274 
   42275   pCur->info.nSize = 0;
   42276   pCur->validNKey = 0;
   42277   if( idx>=pPage->nCell ){
   42278     if( !pPage->leaf ){
   42279       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
   42280       if( rc ) return rc;
   42281       rc = moveToLeftmost(pCur);
   42282       *pRes = 0;
   42283       return rc;
   42284     }
   42285     do{
   42286       if( pCur->iPage==0 ){
   42287         *pRes = 1;
   42288         pCur->eState = CURSOR_INVALID;
   42289         return SQLITE_OK;
   42290       }
   42291       moveToParent(pCur);
   42292       pPage = pCur->apPage[pCur->iPage];
   42293     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
   42294     *pRes = 0;
   42295     if( pPage->intKey ){
   42296       rc = sqlite3BtreeNext(pCur, pRes);
   42297     }else{
   42298       rc = SQLITE_OK;
   42299     }
   42300     return rc;
   42301   }
   42302   *pRes = 0;
   42303   if( pPage->leaf ){
   42304     return SQLITE_OK;
   42305   }
   42306   rc = moveToLeftmost(pCur);
   42307   return rc;
   42308 }
   42309 
   42310 
   42311 /*
   42312 ** Step the cursor to the back to the previous entry in the database.  If
   42313 ** successful then set *pRes=0.  If the cursor
   42314 ** was already pointing to the first entry in the database before
   42315 ** this routine was called, then set *pRes=1.
   42316 */
   42317 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
   42318   int rc;
   42319   MemPage *pPage;
   42320 
   42321   assert( cursorHoldsMutex(pCur) );
   42322   rc = restoreCursorPosition(pCur);
   42323   if( rc!=SQLITE_OK ){
   42324     return rc;
   42325   }
   42326   pCur->atLast = 0;
   42327   if( CURSOR_INVALID==pCur->eState ){
   42328     *pRes = 1;
   42329     return SQLITE_OK;
   42330   }
   42331   if( pCur->skipNext<0 ){
   42332     pCur->skipNext = 0;
   42333     *pRes = 0;
   42334     return SQLITE_OK;
   42335   }
   42336   pCur->skipNext = 0;
   42337 
   42338   pPage = pCur->apPage[pCur->iPage];
   42339   assert( pPage->isInit );
   42340   if( !pPage->leaf ){
   42341     int idx = pCur->aiIdx[pCur->iPage];
   42342     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
   42343     if( rc ){
   42344       return rc;
   42345     }
   42346     rc = moveToRightmost(pCur);
   42347   }else{
   42348     while( pCur->aiIdx[pCur->iPage]==0 ){
   42349       if( pCur->iPage==0 ){
   42350         pCur->eState = CURSOR_INVALID;
   42351         *pRes = 1;
   42352         return SQLITE_OK;
   42353       }
   42354       moveToParent(pCur);
   42355     }
   42356     pCur->info.nSize = 0;
   42357     pCur->validNKey = 0;
   42358 
   42359     pCur->aiIdx[pCur->iPage]--;
   42360     pPage = pCur->apPage[pCur->iPage];
   42361     if( pPage->intKey && !pPage->leaf ){
   42362       rc = sqlite3BtreePrevious(pCur, pRes);
   42363     }else{
   42364       rc = SQLITE_OK;
   42365     }
   42366   }
   42367   *pRes = 0;
   42368   return rc;
   42369 }
   42370 
   42371 /*
   42372 ** Allocate a new page from the database file.
   42373 **
   42374 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
   42375 ** has already been called on the new page.)  The new page has also
   42376 ** been referenced and the calling routine is responsible for calling
   42377 ** sqlite3PagerUnref() on the new page when it is done.
   42378 **
   42379 ** SQLITE_OK is returned on success.  Any other return value indicates
   42380 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
   42381 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
   42382 **
   42383 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to
   42384 ** locate a page close to the page number "nearby".  This can be used in an
   42385 ** attempt to keep related pages close to each other in the database file,
   42386 ** which in turn can make database access faster.
   42387 **
   42388 ** If the "exact" parameter is not 0, and the page-number nearby exists
   42389 ** anywhere on the free-list, then it is guarenteed to be returned. This
   42390 ** is only used by auto-vacuum databases when allocating a new table.
   42391 */
   42392 static int allocateBtreePage(
   42393   BtShared *pBt,
   42394   MemPage **ppPage,
   42395   Pgno *pPgno,
   42396   Pgno nearby,
   42397   u8 exact
   42398 ){
   42399   MemPage *pPage1;
   42400   int rc;
   42401   u32 n;     /* Number of pages on the freelist */
   42402   u32 k;     /* Number of leaves on the trunk of the freelist */
   42403   MemPage *pTrunk = 0;
   42404   MemPage *pPrevTrunk = 0;
   42405   Pgno mxPage;     /* Total size of the database file */
   42406 
   42407   assert( sqlite3_mutex_held(pBt->mutex) );
   42408   pPage1 = pBt->pPage1;
   42409   mxPage = pagerPagecount(pBt);
   42410   n = get4byte(&pPage1->aData[36]);
   42411   testcase( n==mxPage-1 );
   42412   if( n>=mxPage ){
   42413     return SQLITE_CORRUPT_BKPT;
   42414   }
   42415   if( n>0 ){
   42416     /* There are pages on the freelist.  Reuse one of those pages. */
   42417     Pgno iTrunk;
   42418     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
   42419 
   42420     /* If the 'exact' parameter was true and a query of the pointer-map
   42421     ** shows that the page 'nearby' is somewhere on the free-list, then
   42422     ** the entire-list will be searched for that page.
   42423     */
   42424 #ifndef SQLITE_OMIT_AUTOVACUUM
   42425     if( exact && nearby<=mxPage ){
   42426       u8 eType;
   42427       assert( nearby>0 );
   42428       assert( pBt->autoVacuum );
   42429       rc = ptrmapGet(pBt, nearby, &eType, 0);
   42430       if( rc ) return rc;
   42431       if( eType==PTRMAP_FREEPAGE ){
   42432         searchList = 1;
   42433       }
   42434       *pPgno = nearby;
   42435     }
   42436 #endif
   42437 
   42438     /* Decrement the free-list count by 1. Set iTrunk to the index of the
   42439     ** first free-list trunk page. iPrevTrunk is initially 1.
   42440     */
   42441     rc = sqlite3PagerWrite(pPage1->pDbPage);
   42442     if( rc ) return rc;
   42443     put4byte(&pPage1->aData[36], n-1);
   42444 
   42445     /* The code within this loop is run only once if the 'searchList' variable
   42446     ** is not true. Otherwise, it runs once for each trunk-page on the
   42447     ** free-list until the page 'nearby' is located.
   42448     */
   42449     do {
   42450       pPrevTrunk = pTrunk;
   42451       if( pPrevTrunk ){
   42452         iTrunk = get4byte(&pPrevTrunk->aData[0]);
   42453       }else{
   42454         iTrunk = get4byte(&pPage1->aData[32]);
   42455       }
   42456       testcase( iTrunk==mxPage );
   42457       if( iTrunk>mxPage ){
   42458         rc = SQLITE_CORRUPT_BKPT;
   42459       }else{
   42460         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
   42461       }
   42462       if( rc ){
   42463         pTrunk = 0;
   42464         goto end_allocate_page;
   42465       }
   42466 
   42467       k = get4byte(&pTrunk->aData[4]);
   42468       if( k==0 && !searchList ){
   42469         /* The trunk has no leaves and the list is not being searched.
   42470         ** So extract the trunk page itself and use it as the newly
   42471         ** allocated page */
   42472         assert( pPrevTrunk==0 );
   42473         rc = sqlite3PagerWrite(pTrunk->pDbPage);
   42474         if( rc ){
   42475           goto end_allocate_page;
   42476         }
   42477         *pPgno = iTrunk;
   42478         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
   42479         *ppPage = pTrunk;
   42480         pTrunk = 0;
   42481         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
   42482       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
   42483         /* Value of k is out of range.  Database corruption */
   42484         rc = SQLITE_CORRUPT_BKPT;
   42485         goto end_allocate_page;
   42486 #ifndef SQLITE_OMIT_AUTOVACUUM
   42487       }else if( searchList && nearby==iTrunk ){
   42488         /* The list is being searched and this trunk page is the page
   42489         ** to allocate, regardless of whether it has leaves.
   42490         */
   42491         assert( *pPgno==iTrunk );
   42492         *ppPage = pTrunk;
   42493         searchList = 0;
   42494         rc = sqlite3PagerWrite(pTrunk->pDbPage);
   42495         if( rc ){
   42496           goto end_allocate_page;
   42497         }
   42498         if( k==0 ){
   42499           if( !pPrevTrunk ){
   42500             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
   42501           }else{
   42502             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
   42503           }
   42504         }else{
   42505           /* The trunk page is required by the caller but it contains
   42506           ** pointers to free-list leaves. The first leaf becomes a trunk
   42507           ** page in this case.
   42508           */
   42509           MemPage *pNewTrunk;
   42510           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
   42511           if( iNewTrunk>mxPage ){
   42512             rc = SQLITE_CORRUPT_BKPT;
   42513             goto end_allocate_page;
   42514           }
   42515           testcase( iNewTrunk==mxPage );
   42516           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
   42517           if( rc!=SQLITE_OK ){
   42518             goto end_allocate_page;
   42519           }
   42520           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
   42521           if( rc!=SQLITE_OK ){
   42522             releasePage(pNewTrunk);
   42523             goto end_allocate_page;
   42524           }
   42525           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
   42526           put4byte(&pNewTrunk->aData[4], k-1);
   42527           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
   42528           releasePage(pNewTrunk);
   42529           if( !pPrevTrunk ){
   42530             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
   42531             put4byte(&pPage1->aData[32], iNewTrunk);
   42532           }else{
   42533             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
   42534             if( rc ){
   42535               goto end_allocate_page;
   42536             }
   42537             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
   42538           }
   42539         }
   42540         pTrunk = 0;
   42541         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
   42542 #endif
   42543       }else if( k>0 ){
   42544         /* Extract a leaf from the trunk */
   42545         u32 closest;
   42546         Pgno iPage;
   42547         unsigned char *aData = pTrunk->aData;
   42548         rc = sqlite3PagerWrite(pTrunk->pDbPage);
   42549         if( rc ){
   42550           goto end_allocate_page;
   42551         }
   42552         if( nearby>0 ){
   42553           u32 i;
   42554           int dist;
   42555           closest = 0;
   42556           dist = get4byte(&aData[8]) - nearby;
   42557           if( dist<0 ) dist = -dist;
   42558           for(i=1; i<k; i++){
   42559             int d2 = get4byte(&aData[8+i*4]) - nearby;
   42560             if( d2<0 ) d2 = -d2;
   42561             if( d2<dist ){
   42562               closest = i;
   42563               dist = d2;
   42564             }
   42565           }
   42566         }else{
   42567           closest = 0;
   42568         }
   42569 
   42570         iPage = get4byte(&aData[8+closest*4]);
   42571         testcase( iPage==mxPage );
   42572         if( iPage>mxPage ){
   42573           rc = SQLITE_CORRUPT_BKPT;
   42574           goto end_allocate_page;
   42575         }
   42576         testcase( iPage==mxPage );
   42577         if( !searchList || iPage==nearby ){
   42578           int noContent;
   42579           *pPgno = iPage;
   42580           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
   42581                  ": %d more free pages\n",
   42582                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
   42583           if( closest<k-1 ){
   42584             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
   42585           }
   42586           put4byte(&aData[4], k-1);
   42587           assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
   42588           noContent = !btreeGetHasContent(pBt, *pPgno);
   42589           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
   42590           if( rc==SQLITE_OK ){
   42591             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
   42592             if( rc!=SQLITE_OK ){
   42593               releasePage(*ppPage);
   42594             }
   42595           }
   42596           searchList = 0;
   42597         }
   42598       }
   42599       releasePage(pPrevTrunk);
   42600       pPrevTrunk = 0;
   42601     }while( searchList );
   42602   }else{
   42603     /* There are no pages on the freelist, so create a new page at the
   42604     ** end of the file */
   42605     int nPage = pagerPagecount(pBt);
   42606     *pPgno = nPage + 1;
   42607 
   42608     if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
   42609       (*pPgno)++;
   42610     }
   42611 
   42612 #ifndef SQLITE_OMIT_AUTOVACUUM
   42613     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
   42614       /* If *pPgno refers to a pointer-map page, allocate two new pages
   42615       ** at the end of the file instead of one. The first allocated page
   42616       ** becomes a new pointer-map page, the second is used by the caller.
   42617       */
   42618       MemPage *pPg = 0;
   42619       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
   42620       assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
   42621       rc = btreeGetPage(pBt, *pPgno, &pPg, 0);
   42622       if( rc==SQLITE_OK ){
   42623         rc = sqlite3PagerWrite(pPg->pDbPage);
   42624         releasePage(pPg);
   42625       }
   42626       if( rc ) return rc;
   42627       (*pPgno)++;
   42628       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
   42629     }
   42630 #endif
   42631 
   42632     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
   42633     rc = btreeGetPage(pBt, *pPgno, ppPage, 0);
   42634     if( rc ) return rc;
   42635     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
   42636     if( rc!=SQLITE_OK ){
   42637       releasePage(*ppPage);
   42638     }
   42639     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
   42640   }
   42641 
   42642   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
   42643 
   42644 end_allocate_page:
   42645   releasePage(pTrunk);
   42646   releasePage(pPrevTrunk);
   42647   if( rc==SQLITE_OK ){
   42648     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
   42649       releasePage(*ppPage);
   42650       return SQLITE_CORRUPT_BKPT;
   42651     }
   42652     (*ppPage)->isInit = 0;
   42653   }else{
   42654     *ppPage = 0;
   42655   }
   42656   return rc;
   42657 }
   42658 
   42659 /*
   42660 ** This function is used to add page iPage to the database file free-list.
   42661 ** It is assumed that the page is not already a part of the free-list.
   42662 **
   42663 ** The value passed as the second argument to this function is optional.
   42664 ** If the caller happens to have a pointer to the MemPage object
   42665 ** corresponding to page iPage handy, it may pass it as the second value.
   42666 ** Otherwise, it may pass NULL.
   42667 **
   42668 ** If a pointer to a MemPage object is passed as the second argument,
   42669 ** its reference count is not altered by this function.
   42670 */
   42671 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
   42672   MemPage *pTrunk = 0;                /* Free-list trunk page */
   42673   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
   42674   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
   42675   MemPage *pPage;                     /* Page being freed. May be NULL. */
   42676   int rc;                             /* Return Code */
   42677   int nFree;                          /* Initial number of pages on free-list */
   42678 
   42679   assert( sqlite3_mutex_held(pBt->mutex) );
   42680   assert( iPage>1 );
   42681   assert( !pMemPage || pMemPage->pgno==iPage );
   42682 
   42683   if( pMemPage ){
   42684     pPage = pMemPage;
   42685     sqlite3PagerRef(pPage->pDbPage);
   42686   }else{
   42687     pPage = btreePageLookup(pBt, iPage);
   42688   }
   42689 
   42690   /* Increment the free page count on pPage1 */
   42691   rc = sqlite3PagerWrite(pPage1->pDbPage);
   42692   if( rc ) goto freepage_out;
   42693   nFree = get4byte(&pPage1->aData[36]);
   42694   put4byte(&pPage1->aData[36], nFree+1);
   42695 
   42696 #ifdef SQLITE_SECURE_DELETE
   42697   /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
   42698   ** always fully overwrite deleted information with zeros.
   42699   */
   42700   if( (!pPage && (rc = btreeGetPage(pBt, iPage, &pPage, 0)))
   42701    ||            (rc = sqlite3PagerWrite(pPage->pDbPage))
   42702   ){
   42703     goto freepage_out;
   42704   }
   42705   memset(pPage->aData, 0, pPage->pBt->pageSize);
   42706 #endif
   42707 
   42708   /* If the database supports auto-vacuum, write an entry in the pointer-map
   42709   ** to indicate that the page is free.
   42710   */
   42711   if( ISAUTOVACUUM ){
   42712     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
   42713     if( rc ) goto freepage_out;
   42714   }
   42715 
   42716   /* Now manipulate the actual database free-list structure. There are two
   42717   ** possibilities. If the free-list is currently empty, or if the first
   42718   ** trunk page in the free-list is full, then this page will become a
   42719   ** new free-list trunk page. Otherwise, it will become a leaf of the
   42720   ** first trunk page in the current free-list. This block tests if it
   42721   ** is possible to add the page as a new free-list leaf.
   42722   */
   42723   if( nFree!=0 ){
   42724     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
   42725 
   42726     iTrunk = get4byte(&pPage1->aData[32]);
   42727     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
   42728     if( rc!=SQLITE_OK ){
   42729       goto freepage_out;
   42730     }
   42731 
   42732     nLeaf = get4byte(&pTrunk->aData[4]);
   42733     assert( pBt->usableSize>32 );
   42734     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
   42735       rc = SQLITE_CORRUPT_BKPT;
   42736       goto freepage_out;
   42737     }
   42738     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
   42739       /* In this case there is room on the trunk page to insert the page
   42740       ** being freed as a new leaf.
   42741       **
   42742       ** Note that the trunk page is not really full until it contains
   42743       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
   42744       ** coded.  But due to a coding error in versions of SQLite prior to
   42745       ** 3.6.0, databases with freelist trunk pages holding more than
   42746       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
   42747       ** to maintain backwards compatibility with older versions of SQLite,
   42748       ** we will continue to restrict the number of entries to usableSize/4 - 8
   42749       ** for now.  At some point in the future (once everyone has upgraded
   42750       ** to 3.6.0 or later) we should consider fixing the conditional above
   42751       ** to read "usableSize/4-2" instead of "usableSize/4-8".
   42752       */
   42753       rc = sqlite3PagerWrite(pTrunk->pDbPage);
   42754       if( rc==SQLITE_OK ){
   42755         put4byte(&pTrunk->aData[4], nLeaf+1);
   42756         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
   42757 #ifndef SQLITE_SECURE_DELETE
   42758         if( pPage ){
   42759           sqlite3PagerDontWrite(pPage->pDbPage);
   42760         }
   42761 #endif
   42762         rc = btreeSetHasContent(pBt, iPage);
   42763       }
   42764       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
   42765       goto freepage_out;
   42766     }
   42767   }
   42768 
   42769   /* If control flows to this point, then it was not possible to add the
   42770   ** the page being freed as a leaf page of the first trunk in the free-list.
   42771   ** Possibly because the free-list is empty, or possibly because the
   42772   ** first trunk in the free-list is full. Either way, the page being freed
   42773   ** will become the new first trunk page in the free-list.
   42774   */
   42775   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
   42776     goto freepage_out;
   42777   }
   42778   rc = sqlite3PagerWrite(pPage->pDbPage);
   42779   if( rc!=SQLITE_OK ){
   42780     goto freepage_out;
   42781   }
   42782   put4byte(pPage->aData, iTrunk);
   42783   put4byte(&pPage->aData[4], 0);
   42784   put4byte(&pPage1->aData[32], iPage);
   42785   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
   42786 
   42787 freepage_out:
   42788   if( pPage ){
   42789     pPage->isInit = 0;
   42790   }
   42791   releasePage(pPage);
   42792   releasePage(pTrunk);
   42793   return rc;
   42794 }
   42795 static void freePage(MemPage *pPage, int *pRC){
   42796   if( (*pRC)==SQLITE_OK ){
   42797     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
   42798   }
   42799 }
   42800 
   42801 /*
   42802 ** Free any overflow pages associated with the given Cell.
   42803 */
   42804 static int clearCell(MemPage *pPage, unsigned char *pCell){
   42805   BtShared *pBt = pPage->pBt;
   42806   CellInfo info;
   42807   Pgno ovflPgno;
   42808   int rc;
   42809   int nOvfl;
   42810   u16 ovflPageSize;
   42811 
   42812   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   42813   btreeParseCellPtr(pPage, pCell, &info);
   42814   if( info.iOverflow==0 ){
   42815     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
   42816   }
   42817   ovflPgno = get4byte(&pCell[info.iOverflow]);
   42818   assert( pBt->usableSize > 4 );
   42819   ovflPageSize = pBt->usableSize - 4;
   42820   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
   42821   assert( ovflPgno==0 || nOvfl>0 );
   42822   while( nOvfl-- ){
   42823     Pgno iNext = 0;
   42824     MemPage *pOvfl = 0;
   42825     if( ovflPgno<2 || ovflPgno>pagerPagecount(pBt) ){
   42826       /* 0 is not a legal page number and page 1 cannot be an
   42827       ** overflow page. Therefore if ovflPgno<2 or past the end of the
   42828       ** file the database must be corrupt. */
   42829       return SQLITE_CORRUPT_BKPT;
   42830     }
   42831     if( nOvfl ){
   42832       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
   42833       if( rc ) return rc;
   42834     }
   42835     rc = freePage2(pBt, pOvfl, ovflPgno);
   42836     if( pOvfl ){
   42837       sqlite3PagerUnref(pOvfl->pDbPage);
   42838     }
   42839     if( rc ) return rc;
   42840     ovflPgno = iNext;
   42841   }
   42842   return SQLITE_OK;
   42843 }
   42844 
   42845 /*
   42846 ** Create the byte sequence used to represent a cell on page pPage
   42847 ** and write that byte sequence into pCell[].  Overflow pages are
   42848 ** allocated and filled in as necessary.  The calling procedure
   42849 ** is responsible for making sure sufficient space has been allocated
   42850 ** for pCell[].
   42851 **
   42852 ** Note that pCell does not necessary need to point to the pPage->aData
   42853 ** area.  pCell might point to some temporary storage.  The cell will
   42854 ** be constructed in this temporary area then copied into pPage->aData
   42855 ** later.
   42856 */
   42857 static int fillInCell(
   42858   MemPage *pPage,                /* The page that contains the cell */
   42859   unsigned char *pCell,          /* Complete text of the cell */
   42860   const void *pKey, i64 nKey,    /* The key */
   42861   const void *pData,int nData,   /* The data */
   42862   int nZero,                     /* Extra zero bytes to append to pData */
   42863   int *pnSize                    /* Write cell size here */
   42864 ){
   42865   int nPayload;
   42866   const u8 *pSrc;
   42867   int nSrc, n, rc;
   42868   int spaceLeft;
   42869   MemPage *pOvfl = 0;
   42870   MemPage *pToRelease = 0;
   42871   unsigned char *pPrior;
   42872   unsigned char *pPayload;
   42873   BtShared *pBt = pPage->pBt;
   42874   Pgno pgnoOvfl = 0;
   42875   int nHeader;
   42876   CellInfo info;
   42877 
   42878   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   42879 
   42880   /* pPage is not necessarily writeable since pCell might be auxiliary
   42881   ** buffer space that is separate from the pPage buffer area */
   42882   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
   42883             || sqlite3PagerIswriteable(pPage->pDbPage) );
   42884 
   42885   /* Fill in the header. */
   42886   nHeader = 0;
   42887   if( !pPage->leaf ){
   42888     nHeader += 4;
   42889   }
   42890   if( pPage->hasData ){
   42891     nHeader += putVarint(&pCell[nHeader], nData+nZero);
   42892   }else{
   42893     nData = nZero = 0;
   42894   }
   42895   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
   42896   btreeParseCellPtr(pPage, pCell, &info);
   42897   assert( info.nHeader==nHeader );
   42898   assert( info.nKey==nKey );
   42899   assert( info.nData==(u32)(nData+nZero) );
   42900 
   42901   /* Fill in the payload */
   42902   nPayload = nData + nZero;
   42903   if( pPage->intKey ){
   42904     pSrc = pData;
   42905     nSrc = nData;
   42906     nData = 0;
   42907   }else{
   42908     if( NEVER(nKey>0x7fffffff || pKey==0) ){
   42909       return SQLITE_CORRUPT_BKPT;
   42910     }
   42911     nPayload += (int)nKey;
   42912     pSrc = pKey;
   42913     nSrc = (int)nKey;
   42914   }
   42915   *pnSize = info.nSize;
   42916   spaceLeft = info.nLocal;
   42917   pPayload = &pCell[nHeader];
   42918   pPrior = &pCell[info.iOverflow];
   42919 
   42920   while( nPayload>0 ){
   42921     if( spaceLeft==0 ){
   42922 #ifndef SQLITE_OMIT_AUTOVACUUM
   42923       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
   42924       if( pBt->autoVacuum ){
   42925         do{
   42926           pgnoOvfl++;
   42927         } while(
   42928           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
   42929         );
   42930       }
   42931 #endif
   42932       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
   42933 #ifndef SQLITE_OMIT_AUTOVACUUM
   42934       /* If the database supports auto-vacuum, and the second or subsequent
   42935       ** overflow page is being allocated, add an entry to the pointer-map
   42936       ** for that page now.
   42937       **
   42938       ** If this is the first overflow page, then write a partial entry
   42939       ** to the pointer-map. If we write nothing to this pointer-map slot,
   42940       ** then the optimistic overflow chain processing in clearCell()
   42941       ** may misinterpret the uninitialised values and delete the
   42942       ** wrong pages from the database.
   42943       */
   42944       if( pBt->autoVacuum && rc==SQLITE_OK ){
   42945         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
   42946         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
   42947         if( rc ){
   42948           releasePage(pOvfl);
   42949         }
   42950       }
   42951 #endif
   42952       if( rc ){
   42953         releasePage(pToRelease);
   42954         return rc;
   42955       }
   42956 
   42957       /* If pToRelease is not zero than pPrior points into the data area
   42958       ** of pToRelease.  Make sure pToRelease is still writeable. */
   42959       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
   42960 
   42961       /* If pPrior is part of the data area of pPage, then make sure pPage
   42962       ** is still writeable */
   42963       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
   42964             || sqlite3PagerIswriteable(pPage->pDbPage) );
   42965 
   42966       put4byte(pPrior, pgnoOvfl);
   42967       releasePage(pToRelease);
   42968       pToRelease = pOvfl;
   42969       pPrior = pOvfl->aData;
   42970       put4byte(pPrior, 0);
   42971       pPayload = &pOvfl->aData[4];
   42972       spaceLeft = pBt->usableSize - 4;
   42973     }
   42974     n = nPayload;
   42975     if( n>spaceLeft ) n = spaceLeft;
   42976 
   42977     /* If pToRelease is not zero than pPayload points into the data area
   42978     ** of pToRelease.  Make sure pToRelease is still writeable. */
   42979     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
   42980 
   42981     /* If pPayload is part of the data area of pPage, then make sure pPage
   42982     ** is still writeable */
   42983     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
   42984             || sqlite3PagerIswriteable(pPage->pDbPage) );
   42985 
   42986     if( nSrc>0 ){
   42987       if( n>nSrc ) n = nSrc;
   42988       assert( pSrc );
   42989       memcpy(pPayload, pSrc, n);
   42990     }else{
   42991       memset(pPayload, 0, n);
   42992     }
   42993     nPayload -= n;
   42994     pPayload += n;
   42995     pSrc += n;
   42996     nSrc -= n;
   42997     spaceLeft -= n;
   42998     if( nSrc==0 ){
   42999       nSrc = nData;
   43000       pSrc = pData;
   43001     }
   43002   }
   43003   releasePage(pToRelease);
   43004   return SQLITE_OK;
   43005 }
   43006 
   43007 /*
   43008 ** Remove the i-th cell from pPage.  This routine effects pPage only.
   43009 ** The cell content is not freed or deallocated.  It is assumed that
   43010 ** the cell content has been copied someplace else.  This routine just
   43011 ** removes the reference to the cell from pPage.
   43012 **
   43013 ** "sz" must be the number of bytes in the cell.
   43014 */
   43015 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
   43016   int i;          /* Loop counter */
   43017   int pc;         /* Offset to cell content of cell being deleted */
   43018   u8 *data;       /* pPage->aData */
   43019   u8 *ptr;        /* Used to move bytes around within data[] */
   43020   int rc;         /* The return code */
   43021   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
   43022 
   43023   if( *pRC ) return;
   43024 
   43025   assert( idx>=0 && idx<pPage->nCell );
   43026   assert( sz==cellSize(pPage, idx) );
   43027   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   43028   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   43029   data = pPage->aData;
   43030   ptr = &data[pPage->cellOffset + 2*idx];
   43031   pc = get2byte(ptr);
   43032   hdr = pPage->hdrOffset;
   43033   testcase( pc==get2byte(&data[hdr+5]) );
   43034   testcase( pc+sz==pPage->pBt->usableSize );
   43035   if( pc < get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
   43036     *pRC = SQLITE_CORRUPT_BKPT;
   43037     return;
   43038   }
   43039   rc = freeSpace(pPage, pc, sz);
   43040   if( rc ){
   43041     *pRC = rc;
   43042     return;
   43043   }
   43044   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
   43045     ptr[0] = ptr[2];
   43046     ptr[1] = ptr[3];
   43047   }
   43048   pPage->nCell--;
   43049   put2byte(&data[hdr+3], pPage->nCell);
   43050   pPage->nFree += 2;
   43051 }
   43052 
   43053 /*
   43054 ** Insert a new cell on pPage at cell index "i".  pCell points to the
   43055 ** content of the cell.
   43056 **
   43057 ** If the cell content will fit on the page, then put it there.  If it
   43058 ** will not fit, then make a copy of the cell content into pTemp if
   43059 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
   43060 ** in pPage->aOvfl[] and make it point to the cell content (either
   43061 ** in pTemp or the original pCell) and also record its index.
   43062 ** Allocating a new entry in pPage->aCell[] implies that
   43063 ** pPage->nOverflow is incremented.
   43064 **
   43065 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
   43066 ** cell. The caller will overwrite them after this function returns. If
   43067 ** nSkip is non-zero, then pCell may not point to an invalid memory location
   43068 ** (but pCell+nSkip is always valid).
   43069 */
   43070 static void insertCell(
   43071   MemPage *pPage,   /* Page into which we are copying */
   43072   int i,            /* New cell becomes the i-th cell of the page */
   43073   u8 *pCell,        /* Content of the new cell */
   43074   int sz,           /* Bytes of content in pCell */
   43075   u8 *pTemp,        /* Temp storage space for pCell, if needed */
   43076   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
   43077   int *pRC          /* Read and write return code from here */
   43078 ){
   43079   int idx;          /* Where to write new cell content in data[] */
   43080   int j;            /* Loop counter */
   43081   int end;          /* First byte past the last cell pointer in data[] */
   43082   int ins;          /* Index in data[] where new cell pointer is inserted */
   43083   int cellOffset;   /* Address of first cell pointer in data[] */
   43084   u8 *data;         /* The content of the whole page */
   43085   u8 *ptr;          /* Used for moving information around in data[] */
   43086 
   43087   int nSkip = (iChild ? 4 : 0);
   43088 
   43089   if( *pRC ) return;
   43090 
   43091   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
   43092   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
   43093   assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
   43094   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   43095   /* The cell should normally be sized correctly.  However, when moving a
   43096   ** malformed cell from a leaf page to an interior page, if the cell size
   43097   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
   43098   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
   43099   ** the term after the || in the following assert(). */
   43100   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
   43101   if( pPage->nOverflow || sz+2>pPage->nFree ){
   43102     if( pTemp ){
   43103       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
   43104       pCell = pTemp;
   43105     }
   43106     if( iChild ){
   43107       put4byte(pCell, iChild);
   43108     }
   43109     j = pPage->nOverflow++;
   43110     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
   43111     pPage->aOvfl[j].pCell = pCell;
   43112     pPage->aOvfl[j].idx = (u16)i;
   43113   }else{
   43114     int rc = sqlite3PagerWrite(pPage->pDbPage);
   43115     if( rc!=SQLITE_OK ){
   43116       *pRC = rc;
   43117       return;
   43118     }
   43119     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   43120     data = pPage->aData;
   43121     cellOffset = pPage->cellOffset;
   43122     end = cellOffset + 2*pPage->nCell;
   43123     ins = cellOffset + 2*i;
   43124     rc = allocateSpace(pPage, sz, &idx);
   43125     if( rc ){ *pRC = rc; return; }
   43126     /* The allocateSpace() routine guarantees the following two properties
   43127     ** if it returns success */
   43128     assert( idx >= end+2 );
   43129     assert( idx+sz <= pPage->pBt->usableSize );
   43130     pPage->nCell++;
   43131     pPage->nFree -= (u16)(2 + sz);
   43132     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
   43133     if( iChild ){
   43134       put4byte(&data[idx], iChild);
   43135     }
   43136     for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
   43137       ptr[0] = ptr[-2];
   43138       ptr[1] = ptr[-1];
   43139     }
   43140     put2byte(&data[ins], idx);
   43141     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
   43142 #ifndef SQLITE_OMIT_AUTOVACUUM
   43143     if( pPage->pBt->autoVacuum ){
   43144       /* The cell may contain a pointer to an overflow page. If so, write
   43145       ** the entry for the overflow page into the pointer map.
   43146       */
   43147       ptrmapPutOvflPtr(pPage, pCell, pRC);
   43148     }
   43149 #endif
   43150   }
   43151 }
   43152 
   43153 /*
   43154 ** Add a list of cells to a page.  The page should be initially empty.
   43155 ** The cells are guaranteed to fit on the page.
   43156 */
   43157 static void assemblePage(
   43158   MemPage *pPage,   /* The page to be assemblied */
   43159   int nCell,        /* The number of cells to add to this page */
   43160   u8 **apCell,      /* Pointers to cell bodies */
   43161   u16 *aSize        /* Sizes of the cells */
   43162 ){
   43163   int i;            /* Loop counter */
   43164   u8 *pCellptr;     /* Address of next cell pointer */
   43165   int cellbody;     /* Address of next cell body */
   43166   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
   43167   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
   43168   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
   43169 
   43170   assert( pPage->nOverflow==0 );
   43171   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   43172   assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
   43173   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   43174 
   43175   /* Check that the page has just been zeroed by zeroPage() */
   43176   assert( pPage->nCell==0 );
   43177   assert( get2byte(&data[hdr+5])==nUsable );
   43178 
   43179   pCellptr = &data[pPage->cellOffset + nCell*2];
   43180   cellbody = nUsable;
   43181   for(i=nCell-1; i>=0; i--){
   43182     pCellptr -= 2;
   43183     cellbody -= aSize[i];
   43184     put2byte(pCellptr, cellbody);
   43185     memcpy(&data[cellbody], apCell[i], aSize[i]);
   43186   }
   43187   put2byte(&data[hdr+3], nCell);
   43188   put2byte(&data[hdr+5], cellbody);
   43189   pPage->nFree -= (nCell*2 + nUsable - cellbody);
   43190   pPage->nCell = (u16)nCell;
   43191 }
   43192 
   43193 /*
   43194 ** The following parameters determine how many adjacent pages get involved
   43195 ** in a balancing operation.  NN is the number of neighbors on either side
   43196 ** of the page that participate in the balancing operation.  NB is the
   43197 ** total number of pages that participate, including the target page and
   43198 ** NN neighbors on either side.
   43199 **
   43200 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
   43201 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
   43202 ** in exchange for a larger degradation in INSERT and UPDATE performance.
   43203 ** The value of NN appears to give the best results overall.
   43204 */
   43205 #define NN 1             /* Number of neighbors on either side of pPage */
   43206 #define NB (NN*2+1)      /* Total pages involved in the balance */
   43207 
   43208 
   43209 #ifndef SQLITE_OMIT_QUICKBALANCE
   43210 /*
   43211 ** This version of balance() handles the common special case where
   43212 ** a new entry is being inserted on the extreme right-end of the
   43213 ** tree, in other words, when the new entry will become the largest
   43214 ** entry in the tree.
   43215 **
   43216 ** Instead of trying to balance the 3 right-most leaf pages, just add
   43217 ** a new page to the right-hand side and put the one new entry in
   43218 ** that page.  This leaves the right side of the tree somewhat
   43219 ** unbalanced.  But odds are that we will be inserting new entries
   43220 ** at the end soon afterwards so the nearly empty page will quickly
   43221 ** fill up.  On average.
   43222 **
   43223 ** pPage is the leaf page which is the right-most page in the tree.
   43224 ** pParent is its parent.  pPage must have a single overflow entry
   43225 ** which is also the right-most entry on the page.
   43226 **
   43227 ** The pSpace buffer is used to store a temporary copy of the divider
   43228 ** cell that will be inserted into pParent. Such a cell consists of a 4
   43229 ** byte page number followed by a variable length integer. In other
   43230 ** words, at most 13 bytes. Hence the pSpace buffer must be at
   43231 ** least 13 bytes in size.
   43232 */
   43233 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
   43234   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
   43235   MemPage *pNew;                       /* Newly allocated page */
   43236   int rc;                              /* Return Code */
   43237   Pgno pgnoNew;                        /* Page number of pNew */
   43238 
   43239   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   43240   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   43241   assert( pPage->nOverflow==1 );
   43242 
   43243   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
   43244 
   43245   /* Allocate a new page. This page will become the right-sibling of
   43246   ** pPage. Make the parent page writable, so that the new divider cell
   43247   ** may be inserted. If both these operations are successful, proceed.
   43248   */
   43249   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
   43250 
   43251   if( rc==SQLITE_OK ){
   43252 
   43253     u8 *pOut = &pSpace[4];
   43254     u8 *pCell = pPage->aOvfl[0].pCell;
   43255     u16 szCell = cellSizePtr(pPage, pCell);
   43256     u8 *pStop;
   43257 
   43258     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
   43259     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
   43260     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
   43261     assemblePage(pNew, 1, &pCell, &szCell);
   43262 
   43263     /* If this is an auto-vacuum database, update the pointer map
   43264     ** with entries for the new page, and any pointer from the
   43265     ** cell on the page to an overflow page. If either of these
   43266     ** operations fails, the return code is set, but the contents
   43267     ** of the parent page are still manipulated by thh code below.
   43268     ** That is Ok, at this point the parent page is guaranteed to
   43269     ** be marked as dirty. Returning an error code will cause a
   43270     ** rollback, undoing any changes made to the parent page.
   43271     */
   43272     if( ISAUTOVACUUM ){
   43273       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
   43274       if( szCell>pNew->minLocal ){
   43275         ptrmapPutOvflPtr(pNew, pCell, &rc);
   43276       }
   43277     }
   43278 
   43279     /* Create a divider cell to insert into pParent. The divider cell
   43280     ** consists of a 4-byte page number (the page number of pPage) and
   43281     ** a variable length key value (which must be the same value as the
   43282     ** largest key on pPage).
   43283     **
   43284     ** To find the largest key value on pPage, first find the right-most
   43285     ** cell on pPage. The first two fields of this cell are the
   43286     ** record-length (a variable length integer at most 32-bits in size)
   43287     ** and the key value (a variable length integer, may have any value).
   43288     ** The first of the while(...) loops below skips over the record-length
   43289     ** field. The second while(...) loop copies the key value from the
   43290     ** cell on pPage into the pSpace buffer.
   43291     */
   43292     pCell = findCell(pPage, pPage->nCell-1);
   43293     pStop = &pCell[9];
   43294     while( (*(pCell++)&0x80) && pCell<pStop );
   43295     pStop = &pCell[9];
   43296     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
   43297 
   43298     /* Insert the new divider cell into pParent. */
   43299     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
   43300                0, pPage->pgno, &rc);
   43301 
   43302     /* Set the right-child pointer of pParent to point to the new page. */
   43303     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
   43304 
   43305     /* Release the reference to the new page. */
   43306     releasePage(pNew);
   43307   }
   43308 
   43309   return rc;
   43310 }
   43311 #endif /* SQLITE_OMIT_QUICKBALANCE */
   43312 
   43313 #if 0
   43314 /*
   43315 ** This function does not contribute anything to the operation of SQLite.
   43316 ** it is sometimes activated temporarily while debugging code responsible
   43317 ** for setting pointer-map entries.
   43318 */
   43319 static int ptrmapCheckPages(MemPage **apPage, int nPage){
   43320   int i, j;
   43321   for(i=0; i<nPage; i++){
   43322     Pgno n;
   43323     u8 e;
   43324     MemPage *pPage = apPage[i];
   43325     BtShared *pBt = pPage->pBt;
   43326     assert( pPage->isInit );
   43327 
   43328     for(j=0; j<pPage->nCell; j++){
   43329       CellInfo info;
   43330       u8 *z;
   43331 
   43332       z = findCell(pPage, j);
   43333       btreeParseCellPtr(pPage, z, &info);
   43334       if( info.iOverflow ){
   43335         Pgno ovfl = get4byte(&z[info.iOverflow]);
   43336         ptrmapGet(pBt, ovfl, &e, &n);
   43337         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
   43338       }
   43339       if( !pPage->leaf ){
   43340         Pgno child = get4byte(z);
   43341         ptrmapGet(pBt, child, &e, &n);
   43342         assert( n==pPage->pgno && e==PTRMAP_BTREE );
   43343       }
   43344     }
   43345     if( !pPage->leaf ){
   43346       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   43347       ptrmapGet(pBt, child, &e, &n);
   43348       assert( n==pPage->pgno && e==PTRMAP_BTREE );
   43349     }
   43350   }
   43351   return 1;
   43352 }
   43353 #endif
   43354 
   43355 /*
   43356 ** This function is used to copy the contents of the b-tree node stored
   43357 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
   43358 ** the pointer-map entries for each child page are updated so that the
   43359 ** parent page stored in the pointer map is page pTo. If pFrom contained
   43360 ** any cells with overflow page pointers, then the corresponding pointer
   43361 ** map entries are also updated so that the parent page is page pTo.
   43362 **
   43363 ** If pFrom is currently carrying any overflow cells (entries in the
   43364 ** MemPage.aOvfl[] array), they are not copied to pTo.
   43365 **
   43366 ** Before returning, page pTo is reinitialized using btreeInitPage().
   43367 **
   43368 ** The performance of this function is not critical. It is only used by
   43369 ** the balance_shallower() and balance_deeper() procedures, neither of
   43370 ** which are called often under normal circumstances.
   43371 */
   43372 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
   43373   if( (*pRC)==SQLITE_OK ){
   43374     BtShared * const pBt = pFrom->pBt;
   43375     u8 * const aFrom = pFrom->aData;
   43376     u8 * const aTo = pTo->aData;
   43377     int const iFromHdr = pFrom->hdrOffset;
   43378     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
   43379     int rc;
   43380     int iData;
   43381 
   43382 
   43383     assert( pFrom->isInit );
   43384     assert( pFrom->nFree>=iToHdr );
   43385     assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
   43386 
   43387     /* Copy the b-tree node content from page pFrom to page pTo. */
   43388     iData = get2byte(&aFrom[iFromHdr+5]);
   43389     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
   43390     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
   43391 
   43392     /* Reinitialize page pTo so that the contents of the MemPage structure
   43393     ** match the new data. The initialization of pTo can actually fail under
   43394     ** fairly obscure circumstances, even though it is a copy of initialized
   43395     ** page pFrom.
   43396     */
   43397     pTo->isInit = 0;
   43398     rc = btreeInitPage(pTo);
   43399     if( rc!=SQLITE_OK ){
   43400       *pRC = rc;
   43401       return;
   43402     }
   43403 
   43404     /* If this is an auto-vacuum database, update the pointer-map entries
   43405     ** for any b-tree or overflow pages that pTo now contains the pointers to.
   43406     */
   43407     if( ISAUTOVACUUM ){
   43408       *pRC = setChildPtrmaps(pTo);
   43409     }
   43410   }
   43411 }
   43412 
   43413 /*
   43414 ** This routine redistributes cells on the iParentIdx'th child of pParent
   43415 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
   43416 ** same amount of free space. Usually a single sibling on either side of the
   43417 ** page are used in the balancing, though both siblings might come from one
   43418 ** side if the page is the first or last child of its parent. If the page
   43419 ** has fewer than 2 siblings (something which can only happen if the page
   43420 ** is a root page or a child of a root page) then all available siblings
   43421 ** participate in the balancing.
   43422 **
   43423 ** The number of siblings of the page might be increased or decreased by
   43424 ** one or two in an effort to keep pages nearly full but not over full.
   43425 **
   43426 ** Note that when this routine is called, some of the cells on the page
   43427 ** might not actually be stored in MemPage.aData[]. This can happen
   43428 ** if the page is overfull. This routine ensures that all cells allocated
   43429 ** to the page and its siblings fit into MemPage.aData[] before returning.
   43430 **
   43431 ** In the course of balancing the page and its siblings, cells may be
   43432 ** inserted into or removed from the parent page (pParent). Doing so
   43433 ** may cause the parent page to become overfull or underfull. If this
   43434 ** happens, it is the responsibility of the caller to invoke the correct
   43435 ** balancing routine to fix this problem (see the balance() routine).
   43436 **
   43437 ** If this routine fails for any reason, it might leave the database
   43438 ** in a corrupted state. So if this routine fails, the database should
   43439 ** be rolled back.
   43440 **
   43441 ** The third argument to this function, aOvflSpace, is a pointer to a
   43442 ** buffer big enough to hold one page. If while inserting cells into the parent
   43443 ** page (pParent) the parent page becomes overfull, this buffer is
   43444 ** used to store the parent's overflow cells. Because this function inserts
   43445 ** a maximum of four divider cells into the parent page, and the maximum
   43446 ** size of a cell stored within an internal node is always less than 1/4
   43447 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
   43448 ** enough for all overflow cells.
   43449 **
   43450 ** If aOvflSpace is set to a null pointer, this function returns
   43451 ** SQLITE_NOMEM.
   43452 */
   43453 static int balance_nonroot(
   43454   MemPage *pParent,               /* Parent page of siblings being balanced */
   43455   int iParentIdx,                 /* Index of "the page" in pParent */
   43456   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
   43457   int isRoot                      /* True if pParent is a root-page */
   43458 ){
   43459   BtShared *pBt;               /* The whole database */
   43460   int nCell = 0;               /* Number of cells in apCell[] */
   43461   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
   43462   int nNew = 0;                /* Number of pages in apNew[] */
   43463   int nOld;                    /* Number of pages in apOld[] */
   43464   int i, j, k;                 /* Loop counters */
   43465   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
   43466   int rc = SQLITE_OK;          /* The return code */
   43467   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
   43468   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
   43469   int usableSpace;             /* Bytes in pPage beyond the header */
   43470   int pageFlags;               /* Value of pPage->aData[0] */
   43471   int subtotal;                /* Subtotal of bytes in cells on one page */
   43472   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
   43473   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
   43474   int szScratch;               /* Size of scratch memory requested */
   43475   MemPage *apOld[NB];          /* pPage and up to two siblings */
   43476   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
   43477   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
   43478   u8 *pRight;                  /* Location in parent of right-sibling pointer */
   43479   u8 *apDiv[NB-1];             /* Divider cells in pParent */
   43480   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
   43481   int szNew[NB+2];             /* Combined size of cells place on i-th page */
   43482   u8 **apCell = 0;             /* All cells begin balanced */
   43483   u16 *szCell;                 /* Local size of all cells in apCell[] */
   43484   u8 *aSpace1;                 /* Space for copies of dividers cells */
   43485   Pgno pgno;                   /* Temp var to store a page number in */
   43486 
   43487   pBt = pParent->pBt;
   43488   assert( sqlite3_mutex_held(pBt->mutex) );
   43489   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   43490 
   43491 #if 0
   43492   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
   43493 #endif
   43494 
   43495   /* At this point pParent may have at most one overflow cell. And if
   43496   ** this overflow cell is present, it must be the cell with
   43497   ** index iParentIdx. This scenario comes about when this function
   43498   ** is called (indirectly) from sqlite3BtreeDelete().
   43499   */
   43500   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
   43501   assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
   43502 
   43503   if( !aOvflSpace ){
   43504     return SQLITE_NOMEM;
   43505   }
   43506 
   43507   /* Find the sibling pages to balance. Also locate the cells in pParent
   43508   ** that divide the siblings. An attempt is made to find NN siblings on
   43509   ** either side of pPage. More siblings are taken from one side, however,
   43510   ** if there are fewer than NN siblings on the other side. If pParent
   43511   ** has NB or fewer children then all children of pParent are taken.
   43512   **
   43513   ** This loop also drops the divider cells from the parent page. This
   43514   ** way, the remainder of the function does not have to deal with any
   43515   ** overflow cells in the parent page, since if any existed they will
   43516   ** have already been removed.
   43517   */
   43518   i = pParent->nOverflow + pParent->nCell;
   43519   if( i<2 ){
   43520     nxDiv = 0;
   43521     nOld = i+1;
   43522   }else{
   43523     nOld = 3;
   43524     if( iParentIdx==0 ){
   43525       nxDiv = 0;
   43526     }else if( iParentIdx==i ){
   43527       nxDiv = i-2;
   43528     }else{
   43529       nxDiv = iParentIdx-1;
   43530     }
   43531     i = 2;
   43532   }
   43533   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
   43534     pRight = &pParent->aData[pParent->hdrOffset+8];
   43535   }else{
   43536     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
   43537   }
   43538   pgno = get4byte(pRight);
   43539   while( 1 ){
   43540     rc = getAndInitPage(pBt, pgno, &apOld[i]);
   43541     if( rc ){
   43542       memset(apOld, 0, (i+1)*sizeof(MemPage*));
   43543       goto balance_cleanup;
   43544     }
   43545     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
   43546     if( (i--)==0 ) break;
   43547 
   43548     if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
   43549       apDiv[i] = pParent->aOvfl[0].pCell;
   43550       pgno = get4byte(apDiv[i]);
   43551       szNew[i] = cellSizePtr(pParent, apDiv[i]);
   43552       pParent->nOverflow = 0;
   43553     }else{
   43554       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
   43555       pgno = get4byte(apDiv[i]);
   43556       szNew[i] = cellSizePtr(pParent, apDiv[i]);
   43557 
   43558       /* Drop the cell from the parent page. apDiv[i] still points to
   43559       ** the cell within the parent, even though it has been dropped.
   43560       ** This is safe because dropping a cell only overwrites the first
   43561       ** four bytes of it, and this function does not need the first
   43562       ** four bytes of the divider cell. So the pointer is safe to use
   43563       ** later on.
   43564       **
   43565       ** Unless SQLite is compiled in secure-delete mode. In this case,
   43566       ** the dropCell() routine will overwrite the entire cell with zeroes.
   43567       ** In this case, temporarily copy the cell into the aOvflSpace[]
   43568       ** buffer. It will be copied out again as soon as the aSpace[] buffer
   43569       ** is allocated.  */
   43570 #ifdef SQLITE_SECURE_DELETE
   43571       memcpy(&aOvflSpace[apDiv[i]-pParent->aData], apDiv[i], szNew[i]);
   43572       apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
   43573 #endif
   43574       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
   43575     }
   43576   }
   43577 
   43578   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
   43579   ** alignment */
   43580   nMaxCells = (nMaxCells + 3)&~3;
   43581 
   43582   /*
   43583   ** Allocate space for memory structures
   43584   */
   43585   k = pBt->pageSize + ROUND8(sizeof(MemPage));
   43586   szScratch =
   43587        nMaxCells*sizeof(u8*)                       /* apCell */
   43588      + nMaxCells*sizeof(u16)                       /* szCell */
   43589      + pBt->pageSize                               /* aSpace1 */
   43590      + k*nOld;                                     /* Page copies (apCopy) */
   43591   apCell = sqlite3ScratchMalloc( szScratch );
   43592   if( apCell==0 ){
   43593     rc = SQLITE_NOMEM;
   43594     goto balance_cleanup;
   43595   }
   43596   szCell = (u16*)&apCell[nMaxCells];
   43597   aSpace1 = (u8*)&szCell[nMaxCells];
   43598   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
   43599 
   43600   /*
   43601   ** Load pointers to all cells on sibling pages and the divider cells
   43602   ** into the local apCell[] array.  Make copies of the divider cells
   43603   ** into space obtained from aSpace1[] and remove the the divider Cells
   43604   ** from pParent.
   43605   **
   43606   ** If the siblings are on leaf pages, then the child pointers of the
   43607   ** divider cells are stripped from the cells before they are copied
   43608   ** into aSpace1[].  In this way, all cells in apCell[] are without
   43609   ** child pointers.  If siblings are not leaves, then all cell in
   43610   ** apCell[] include child pointers.  Either way, all cells in apCell[]
   43611   ** are alike.
   43612   **
   43613   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
   43614   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
   43615   */
   43616   leafCorrection = apOld[0]->leaf*4;
   43617   leafData = apOld[0]->hasData;
   43618   for(i=0; i<nOld; i++){
   43619     int limit;
   43620 
   43621     /* Before doing anything else, take a copy of the i'th original sibling
   43622     ** The rest of this function will use data from the copies rather
   43623     ** that the original pages since the original pages will be in the
   43624     ** process of being overwritten.  */
   43625     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
   43626     memcpy(pOld, apOld[i], sizeof(MemPage));
   43627     pOld->aData = (void*)&pOld[1];
   43628     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
   43629 
   43630     limit = pOld->nCell+pOld->nOverflow;
   43631     for(j=0; j<limit; j++){
   43632       assert( nCell<nMaxCells );
   43633       apCell[nCell] = findOverflowCell(pOld, j);
   43634       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
   43635       nCell++;
   43636     }
   43637     if( i<nOld-1 && !leafData){
   43638       u16 sz = (u16)szNew[i];
   43639       u8 *pTemp;
   43640       assert( nCell<nMaxCells );
   43641       szCell[nCell] = sz;
   43642       pTemp = &aSpace1[iSpace1];
   43643       iSpace1 += sz;
   43644       assert( sz<=pBt->pageSize/4 );
   43645       assert( iSpace1<=pBt->pageSize );
   43646       memcpy(pTemp, apDiv[i], sz);
   43647       apCell[nCell] = pTemp+leafCorrection;
   43648       assert( leafCorrection==0 || leafCorrection==4 );
   43649       szCell[nCell] = szCell[nCell] - leafCorrection;
   43650       if( !pOld->leaf ){
   43651         assert( leafCorrection==0 );
   43652         assert( pOld->hdrOffset==0 );
   43653         /* The right pointer of the child page pOld becomes the left
   43654         ** pointer of the divider cell */
   43655         memcpy(apCell[nCell], &pOld->aData[8], 4);
   43656       }else{
   43657         assert( leafCorrection==4 );
   43658         if( szCell[nCell]<4 ){
   43659           /* Do not allow any cells smaller than 4 bytes. */
   43660           szCell[nCell] = 4;
   43661         }
   43662       }
   43663       nCell++;
   43664     }
   43665   }
   43666 
   43667   /*
   43668   ** Figure out the number of pages needed to hold all nCell cells.
   43669   ** Store this number in "k".  Also compute szNew[] which is the total
   43670   ** size of all cells on the i-th page and cntNew[] which is the index
   43671   ** in apCell[] of the cell that divides page i from page i+1.
   43672   ** cntNew[k] should equal nCell.
   43673   **
   43674   ** Values computed by this block:
   43675   **
   43676   **           k: The total number of sibling pages
   43677   **    szNew[i]: Spaced used on the i-th sibling page.
   43678   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
   43679   **              the right of the i-th sibling page.
   43680   ** usableSpace: Number of bytes of space available on each sibling.
   43681   **
   43682   */
   43683   usableSpace = pBt->usableSize - 12 + leafCorrection;
   43684   for(subtotal=k=i=0; i<nCell; i++){
   43685     assert( i<nMaxCells );
   43686     subtotal += szCell[i] + 2;
   43687     if( subtotal > usableSpace ){
   43688       szNew[k] = subtotal - szCell[i];
   43689       cntNew[k] = i;
   43690       if( leafData ){ i--; }
   43691       subtotal = 0;
   43692       k++;
   43693       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
   43694     }
   43695   }
   43696   szNew[k] = subtotal;
   43697   cntNew[k] = nCell;
   43698   k++;
   43699 
   43700   /*
   43701   ** The packing computed by the previous block is biased toward the siblings
   43702   ** on the left side.  The left siblings are always nearly full, while the
   43703   ** right-most sibling might be nearly empty.  This block of code attempts
   43704   ** to adjust the packing of siblings to get a better balance.
   43705   **
   43706   ** This adjustment is more than an optimization.  The packing above might
   43707   ** be so out of balance as to be illegal.  For example, the right-most
   43708   ** sibling might be completely empty.  This adjustment is not optional.
   43709   */
   43710   for(i=k-1; i>0; i--){
   43711     int szRight = szNew[i];  /* Size of sibling on the right */
   43712     int szLeft = szNew[i-1]; /* Size of sibling on the left */
   43713     int r;              /* Index of right-most cell in left sibling */
   43714     int d;              /* Index of first cell to the left of right sibling */
   43715 
   43716     r = cntNew[i-1] - 1;
   43717     d = r + 1 - leafData;
   43718     assert( d<nMaxCells );
   43719     assert( r<nMaxCells );
   43720     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
   43721       szRight += szCell[d] + 2;
   43722       szLeft -= szCell[r] + 2;
   43723       cntNew[i-1]--;
   43724       r = cntNew[i-1] - 1;
   43725       d = r + 1 - leafData;
   43726     }
   43727     szNew[i] = szRight;
   43728     szNew[i-1] = szLeft;
   43729   }
   43730 
   43731   /* Either we found one or more cells (cntnew[0])>0) or pPage is
   43732   ** a virtual root page.  A virtual root page is when the real root
   43733   ** page is page 1 and we are the only child of that page.
   43734   */
   43735   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
   43736 
   43737   TRACE(("BALANCE: old: %d %d %d  ",
   43738     apOld[0]->pgno,
   43739     nOld>=2 ? apOld[1]->pgno : 0,
   43740     nOld>=3 ? apOld[2]->pgno : 0
   43741   ));
   43742 
   43743   /*
   43744   ** Allocate k new pages.  Reuse old pages where possible.
   43745   */
   43746   if( apOld[0]->pgno<=1 ){
   43747     rc = SQLITE_CORRUPT_BKPT;
   43748     goto balance_cleanup;
   43749   }
   43750   pageFlags = apOld[0]->aData[0];
   43751   for(i=0; i<k; i++){
   43752     MemPage *pNew;
   43753     if( i<nOld ){
   43754       pNew = apNew[i] = apOld[i];
   43755       apOld[i] = 0;
   43756       rc = sqlite3PagerWrite(pNew->pDbPage);
   43757       nNew++;
   43758       if( rc ) goto balance_cleanup;
   43759     }else{
   43760       assert( i>0 );
   43761       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
   43762       if( rc ) goto balance_cleanup;
   43763       apNew[i] = pNew;
   43764       nNew++;
   43765 
   43766       /* Set the pointer-map entry for the new sibling page. */
   43767       if( ISAUTOVACUUM ){
   43768         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
   43769         if( rc!=SQLITE_OK ){
   43770           goto balance_cleanup;
   43771         }
   43772       }
   43773     }
   43774   }
   43775 
   43776   /* Free any old pages that were not reused as new pages.
   43777   */
   43778   while( i<nOld ){
   43779     freePage(apOld[i], &rc);
   43780     if( rc ) goto balance_cleanup;
   43781     releasePage(apOld[i]);
   43782     apOld[i] = 0;
   43783     i++;
   43784   }
   43785 
   43786   /*
   43787   ** Put the new pages in accending order.  This helps to
   43788   ** keep entries in the disk file in order so that a scan
   43789   ** of the table is a linear scan through the file.  That
   43790   ** in turn helps the operating system to deliver pages
   43791   ** from the disk more rapidly.
   43792   **
   43793   ** An O(n^2) insertion sort algorithm is used, but since
   43794   ** n is never more than NB (a small constant), that should
   43795   ** not be a problem.
   43796   **
   43797   ** When NB==3, this one optimization makes the database
   43798   ** about 25% faster for large insertions and deletions.
   43799   */
   43800   for(i=0; i<k-1; i++){
   43801     int minV = apNew[i]->pgno;
   43802     int minI = i;
   43803     for(j=i+1; j<k; j++){
   43804       if( apNew[j]->pgno<(unsigned)minV ){
   43805         minI = j;
   43806         minV = apNew[j]->pgno;
   43807       }
   43808     }
   43809     if( minI>i ){
   43810       int t;
   43811       MemPage *pT;
   43812       t = apNew[i]->pgno;
   43813       pT = apNew[i];
   43814       apNew[i] = apNew[minI];
   43815       apNew[minI] = pT;
   43816     }
   43817   }
   43818   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
   43819     apNew[0]->pgno, szNew[0],
   43820     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
   43821     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
   43822     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
   43823     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
   43824 
   43825   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   43826   put4byte(pRight, apNew[nNew-1]->pgno);
   43827 
   43828   /*
   43829   ** Evenly distribute the data in apCell[] across the new pages.
   43830   ** Insert divider cells into pParent as necessary.
   43831   */
   43832   j = 0;
   43833   for(i=0; i<nNew; i++){
   43834     /* Assemble the new sibling page. */
   43835     MemPage *pNew = apNew[i];
   43836     assert( j<nMaxCells );
   43837     zeroPage(pNew, pageFlags);
   43838     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
   43839     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
   43840     assert( pNew->nOverflow==0 );
   43841 
   43842     j = cntNew[i];
   43843 
   43844     /* If the sibling page assembled above was not the right-most sibling,
   43845     ** insert a divider cell into the parent page.
   43846     */
   43847     assert( i<nNew-1 || j==nCell );
   43848     if( j<nCell ){
   43849       u8 *pCell;
   43850       u8 *pTemp;
   43851       int sz;
   43852 
   43853       assert( j<nMaxCells );
   43854       pCell = apCell[j];
   43855       sz = szCell[j] + leafCorrection;
   43856       pTemp = &aOvflSpace[iOvflSpace];
   43857       if( !pNew->leaf ){
   43858         memcpy(&pNew->aData[8], pCell, 4);
   43859       }else if( leafData ){
   43860         /* If the tree is a leaf-data tree, and the siblings are leaves,
   43861         ** then there is no divider cell in apCell[]. Instead, the divider
   43862         ** cell consists of the integer key for the right-most cell of
   43863         ** the sibling-page assembled above only.
   43864         */
   43865         CellInfo info;
   43866         j--;
   43867         btreeParseCellPtr(pNew, apCell[j], &info);
   43868         pCell = pTemp;
   43869         sz = 4 + putVarint(&pCell[4], info.nKey);
   43870         pTemp = 0;
   43871       }else{
   43872         pCell -= 4;
   43873         /* Obscure case for non-leaf-data trees: If the cell at pCell was
   43874         ** previously stored on a leaf node, and its reported size was 4
   43875         ** bytes, then it may actually be smaller than this
   43876         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
   43877         ** any cell). But it is important to pass the correct size to
   43878         ** insertCell(), so reparse the cell now.
   43879         **
   43880         ** Note that this can never happen in an SQLite data file, as all
   43881         ** cells are at least 4 bytes. It only happens in b-trees used
   43882         ** to evaluate "IN (SELECT ...)" and similar clauses.
   43883         */
   43884         if( szCell[j]==4 ){
   43885           assert(leafCorrection==4);
   43886           sz = cellSizePtr(pParent, pCell);
   43887         }
   43888       }
   43889       iOvflSpace += sz;
   43890       assert( sz<=pBt->pageSize/4 );
   43891       assert( iOvflSpace<=pBt->pageSize );
   43892       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
   43893       if( rc!=SQLITE_OK ) goto balance_cleanup;
   43894       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   43895 
   43896       j++;
   43897       nxDiv++;
   43898     }
   43899   }
   43900   assert( j==nCell );
   43901   assert( nOld>0 );
   43902   assert( nNew>0 );
   43903   if( (pageFlags & PTF_LEAF)==0 ){
   43904     u8 *zChild = &apCopy[nOld-1]->aData[8];
   43905     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
   43906   }
   43907 
   43908   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
   43909     /* The root page of the b-tree now contains no cells. The only sibling
   43910     ** page is the right-child of the parent. Copy the contents of the
   43911     ** child page into the parent, decreasing the overall height of the
   43912     ** b-tree structure by one. This is described as the "balance-shallower"
   43913     ** sub-algorithm in some documentation.
   43914     **
   43915     ** If this is an auto-vacuum database, the call to copyNodeContent()
   43916     ** sets all pointer-map entries corresponding to database image pages
   43917     ** for which the pointer is stored within the content being copied.
   43918     **
   43919     ** The second assert below verifies that the child page is defragmented
   43920     ** (it must be, as it was just reconstructed using assemblePage()). This
   43921     ** is important if the parent page happens to be page 1 of the database
   43922     ** image.  */
   43923     assert( nNew==1 );
   43924     assert( apNew[0]->nFree ==
   43925         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
   43926     );
   43927     copyNodeContent(apNew[0], pParent, &rc);
   43928     freePage(apNew[0], &rc);
   43929   }else if( ISAUTOVACUUM ){
   43930     /* Fix the pointer-map entries for all the cells that were shifted around.
   43931     ** There are several different types of pointer-map entries that need to
   43932     ** be dealt with by this routine. Some of these have been set already, but
   43933     ** many have not. The following is a summary:
   43934     **
   43935     **   1) The entries associated with new sibling pages that were not
   43936     **      siblings when this function was called. These have already
   43937     **      been set. We don't need to worry about old siblings that were
   43938     **      moved to the free-list - the freePage() code has taken care
   43939     **      of those.
   43940     **
   43941     **   2) The pointer-map entries associated with the first overflow
   43942     **      page in any overflow chains used by new divider cells. These
   43943     **      have also already been taken care of by the insertCell() code.
   43944     **
   43945     **   3) If the sibling pages are not leaves, then the child pages of
   43946     **      cells stored on the sibling pages may need to be updated.
   43947     **
   43948     **   4) If the sibling pages are not internal intkey nodes, then any
   43949     **      overflow pages used by these cells may need to be updated
   43950     **      (internal intkey nodes never contain pointers to overflow pages).
   43951     **
   43952     **   5) If the sibling pages are not leaves, then the pointer-map
   43953     **      entries for the right-child pages of each sibling may need
   43954     **      to be updated.
   43955     **
   43956     ** Cases 1 and 2 are dealt with above by other code. The next
   43957     ** block deals with cases 3 and 4 and the one after that, case 5. Since
   43958     ** setting a pointer map entry is a relatively expensive operation, this
   43959     ** code only sets pointer map entries for child or overflow pages that have
   43960     ** actually moved between pages.  */
   43961     MemPage *pNew = apNew[0];
   43962     MemPage *pOld = apCopy[0];
   43963     int nOverflow = pOld->nOverflow;
   43964     int iNextOld = pOld->nCell + nOverflow;
   43965     int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
   43966     j = 0;                             /* Current 'old' sibling page */
   43967     k = 0;                             /* Current 'new' sibling page */
   43968     for(i=0; i<nCell; i++){
   43969       int isDivider = 0;
   43970       while( i==iNextOld ){
   43971         /* Cell i is the cell immediately following the last cell on old
   43972         ** sibling page j. If the siblings are not leaf pages of an
   43973         ** intkey b-tree, then cell i was a divider cell. */
   43974         pOld = apCopy[++j];
   43975         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
   43976         if( pOld->nOverflow ){
   43977           nOverflow = pOld->nOverflow;
   43978           iOverflow = i + !leafData + pOld->aOvfl[0].idx;
   43979         }
   43980         isDivider = !leafData;
   43981       }
   43982 
   43983       assert(nOverflow>0 || iOverflow<i );
   43984       assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
   43985       assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
   43986       if( i==iOverflow ){
   43987         isDivider = 1;
   43988         if( (--nOverflow)>0 ){
   43989           iOverflow++;
   43990         }
   43991       }
   43992 
   43993       if( i==cntNew[k] ){
   43994         /* Cell i is the cell immediately following the last cell on new
   43995         ** sibling page k. If the siblings are not leaf pages of an
   43996         ** intkey b-tree, then cell i is a divider cell.  */
   43997         pNew = apNew[++k];
   43998         if( !leafData ) continue;
   43999       }
   44000       assert( j<nOld );
   44001       assert( k<nNew );
   44002 
   44003       /* If the cell was originally divider cell (and is not now) or
   44004       ** an overflow cell, or if the cell was located on a different sibling
   44005       ** page before the balancing, then the pointer map entries associated
   44006       ** with any child or overflow pages need to be updated.  */
   44007       if( isDivider || pOld->pgno!=pNew->pgno ){
   44008         if( !leafCorrection ){
   44009           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
   44010         }
   44011         if( szCell[i]>pNew->minLocal ){
   44012           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
   44013         }
   44014       }
   44015     }
   44016 
   44017     if( !leafCorrection ){
   44018       for(i=0; i<nNew; i++){
   44019         u32 key = get4byte(&apNew[i]->aData[8]);
   44020         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
   44021       }
   44022     }
   44023 
   44024 #if 0
   44025     /* The ptrmapCheckPages() contains assert() statements that verify that
   44026     ** all pointer map pages are set correctly. This is helpful while
   44027     ** debugging. This is usually disabled because a corrupt database may
   44028     ** cause an assert() statement to fail.  */
   44029     ptrmapCheckPages(apNew, nNew);
   44030     ptrmapCheckPages(&pParent, 1);
   44031 #endif
   44032   }
   44033 
   44034   assert( pParent->isInit );
   44035   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
   44036           nOld, nNew, nCell));
   44037 
   44038   /*
   44039   ** Cleanup before returning.
   44040   */
   44041 balance_cleanup:
   44042   sqlite3ScratchFree(apCell);
   44043   for(i=0; i<nOld; i++){
   44044     releasePage(apOld[i]);
   44045   }
   44046   for(i=0; i<nNew; i++){
   44047     releasePage(apNew[i]);
   44048   }
   44049 
   44050   return rc;
   44051 }
   44052 
   44053 
   44054 /*
   44055 ** This function is called when the root page of a b-tree structure is
   44056 ** overfull (has one or more overflow pages).
   44057 **
   44058 ** A new child page is allocated and the contents of the current root
   44059 ** page, including overflow cells, are copied into the child. The root
   44060 ** page is then overwritten to make it an empty page with the right-child
   44061 ** pointer pointing to the new page.
   44062 **
   44063 ** Before returning, all pointer-map entries corresponding to pages
   44064 ** that the new child-page now contains pointers to are updated. The
   44065 ** entry corresponding to the new right-child pointer of the root
   44066 ** page is also updated.
   44067 **
   44068 ** If successful, *ppChild is set to contain a reference to the child
   44069 ** page and SQLITE_OK is returned. In this case the caller is required
   44070 ** to call releasePage() on *ppChild exactly once. If an error occurs,
   44071 ** an error code is returned and *ppChild is set to 0.
   44072 */
   44073 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
   44074   int rc;                        /* Return value from subprocedures */
   44075   MemPage *pChild = 0;           /* Pointer to a new child page */
   44076   Pgno pgnoChild = 0;            /* Page number of the new child page */
   44077   BtShared *pBt = pRoot->pBt;    /* The BTree */
   44078 
   44079   assert( pRoot->nOverflow>0 );
   44080   assert( sqlite3_mutex_held(pBt->mutex) );
   44081 
   44082   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
   44083   ** page that will become the new right-child of pPage. Copy the contents
   44084   ** of the node stored on pRoot into the new child page.
   44085   */
   44086   rc = sqlite3PagerWrite(pRoot->pDbPage);
   44087   if( rc==SQLITE_OK ){
   44088     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
   44089     copyNodeContent(pRoot, pChild, &rc);
   44090     if( ISAUTOVACUUM ){
   44091       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
   44092     }
   44093   }
   44094   if( rc ){
   44095     *ppChild = 0;
   44096     releasePage(pChild);
   44097     return rc;
   44098   }
   44099   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
   44100   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
   44101   assert( pChild->nCell==pRoot->nCell );
   44102 
   44103   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
   44104 
   44105   /* Copy the overflow cells from pRoot to pChild */
   44106   memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
   44107   pChild->nOverflow = pRoot->nOverflow;
   44108 
   44109   /* Zero the contents of pRoot. Then install pChild as the right-child. */
   44110   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
   44111   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
   44112 
   44113   *ppChild = pChild;
   44114   return SQLITE_OK;
   44115 }
   44116 
   44117 /*
   44118 ** The page that pCur currently points to has just been modified in
   44119 ** some way. This function figures out if this modification means the
   44120 ** tree needs to be balanced, and if so calls the appropriate balancing
   44121 ** routine. Balancing routines are:
   44122 **
   44123 **   balance_quick()
   44124 **   balance_deeper()
   44125 **   balance_nonroot()
   44126 */
   44127 static int balance(BtCursor *pCur){
   44128   int rc = SQLITE_OK;
   44129   const int nMin = pCur->pBt->usableSize * 2 / 3;
   44130   u8 aBalanceQuickSpace[13];
   44131   u8 *pFree = 0;
   44132 
   44133   TESTONLY( int balance_quick_called = 0 );
   44134   TESTONLY( int balance_deeper_called = 0 );
   44135 
   44136   do {
   44137     int iPage = pCur->iPage;
   44138     MemPage *pPage = pCur->apPage[iPage];
   44139 
   44140     if( iPage==0 ){
   44141       if( pPage->nOverflow ){
   44142         /* The root page of the b-tree is overfull. In this case call the
   44143         ** balance_deeper() function to create a new child for the root-page
   44144         ** and copy the current contents of the root-page to it. The
   44145         ** next iteration of the do-loop will balance the child page.
   44146         */
   44147         assert( (balance_deeper_called++)==0 );
   44148         rc = balance_deeper(pPage, &pCur->apPage[1]);
   44149         if( rc==SQLITE_OK ){
   44150           pCur->iPage = 1;
   44151           pCur->aiIdx[0] = 0;
   44152           pCur->aiIdx[1] = 0;
   44153           assert( pCur->apPage[1]->nOverflow );
   44154         }
   44155       }else{
   44156         break;
   44157       }
   44158     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
   44159       break;
   44160     }else{
   44161       MemPage * const pParent = pCur->apPage[iPage-1];
   44162       int const iIdx = pCur->aiIdx[iPage-1];
   44163 
   44164       rc = sqlite3PagerWrite(pParent->pDbPage);
   44165       if( rc==SQLITE_OK ){
   44166 #ifndef SQLITE_OMIT_QUICKBALANCE
   44167         if( pPage->hasData
   44168          && pPage->nOverflow==1
   44169          && pPage->aOvfl[0].idx==pPage->nCell
   44170          && pParent->pgno!=1
   44171          && pParent->nCell==iIdx
   44172         ){
   44173           /* Call balance_quick() to create a new sibling of pPage on which
   44174           ** to store the overflow cell. balance_quick() inserts a new cell
   44175           ** into pParent, which may cause pParent overflow. If this
   44176           ** happens, the next interation of the do-loop will balance pParent
   44177           ** use either balance_nonroot() or balance_deeper(). Until this
   44178           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
   44179           ** buffer.
   44180           **
   44181           ** The purpose of the following assert() is to check that only a
   44182           ** single call to balance_quick() is made for each call to this
   44183           ** function. If this were not verified, a subtle bug involving reuse
   44184           ** of the aBalanceQuickSpace[] might sneak in.
   44185           */
   44186           assert( (balance_quick_called++)==0 );
   44187           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
   44188         }else
   44189 #endif
   44190         {
   44191           /* In this case, call balance_nonroot() to redistribute cells
   44192           ** between pPage and up to 2 of its sibling pages. This involves
   44193           ** modifying the contents of pParent, which may cause pParent to
   44194           ** become overfull or underfull. The next iteration of the do-loop
   44195           ** will balance the parent page to correct this.
   44196           **
   44197           ** If the parent page becomes overfull, the overflow cell or cells
   44198           ** are stored in the pSpace buffer allocated immediately below.
   44199           ** A subsequent iteration of the do-loop will deal with this by
   44200           ** calling balance_nonroot() (balance_deeper() may be called first,
   44201           ** but it doesn't deal with overflow cells - just moves them to a
   44202           ** different page). Once this subsequent call to balance_nonroot()
   44203           ** has completed, it is safe to release the pSpace buffer used by
   44204           ** the previous call, as the overflow cell data will have been
   44205           ** copied either into the body of a database page or into the new
   44206           ** pSpace buffer passed to the latter call to balance_nonroot().
   44207           */
   44208           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
   44209           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
   44210           if( pFree ){
   44211             /* If pFree is not NULL, it points to the pSpace buffer used
   44212             ** by a previous call to balance_nonroot(). Its contents are
   44213             ** now stored either on real database pages or within the
   44214             ** new pSpace buffer, so it may be safely freed here. */
   44215             sqlite3PageFree(pFree);
   44216           }
   44217 
   44218           /* The pSpace buffer will be freed after the next call to
   44219           ** balance_nonroot(), or just before this function returns, whichever
   44220           ** comes first. */
   44221           pFree = pSpace;
   44222         }
   44223       }
   44224 
   44225       pPage->nOverflow = 0;
   44226 
   44227       /* The next iteration of the do-loop balances the parent page. */
   44228       releasePage(pPage);
   44229       pCur->iPage--;
   44230     }
   44231   }while( rc==SQLITE_OK );
   44232 
   44233   if( pFree ){
   44234     sqlite3PageFree(pFree);
   44235   }
   44236   return rc;
   44237 }
   44238 
   44239 
   44240 /*
   44241 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
   44242 ** and the data is given by (pData,nData).  The cursor is used only to
   44243 ** define what table the record should be inserted into.  The cursor
   44244 ** is left pointing at a random location.
   44245 **
   44246 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
   44247 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
   44248 **
   44249 ** If the seekResult parameter is non-zero, then a successful call to
   44250 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
   44251 ** been performed. seekResult is the search result returned (a negative
   44252 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
   44253 ** a positive value if pCur points at an etry that is larger than
   44254 ** (pKey, nKey)).
   44255 **
   44256 ** If the seekResult parameter is non-zero, then the caller guarantees that
   44257 ** cursor pCur is pointing at the existing copy of a row that is to be
   44258 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
   44259 ** point to any entry or to no entry at all and so this function has to seek
   44260 ** the cursor before the new key can be inserted.
   44261 */
   44262 SQLITE_PRIVATE int sqlite3BtreeInsert(
   44263   BtCursor *pCur,                /* Insert data into the table of this cursor */
   44264   const void *pKey, i64 nKey,    /* The key of the new record */
   44265   const void *pData, int nData,  /* The data of the new record */
   44266   int nZero,                     /* Number of extra 0 bytes to append to data */
   44267   int appendBias,                /* True if this is likely an append */
   44268   int seekResult                 /* Result of prior MovetoUnpacked() call */
   44269 ){
   44270   int rc;
   44271   int loc = seekResult;          /* -1: before desired location  +1: after */
   44272   int szNew = 0;
   44273   int idx;
   44274   MemPage *pPage;
   44275   Btree *p = pCur->pBtree;
   44276   BtShared *pBt = p->pBt;
   44277   unsigned char *oldCell;
   44278   unsigned char *newCell = 0;
   44279 
   44280   if( pCur->eState==CURSOR_FAULT ){
   44281     assert( pCur->skipNext!=SQLITE_OK );
   44282     return pCur->skipNext;
   44283   }
   44284 
   44285   assert( cursorHoldsMutex(pCur) );
   44286   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
   44287   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
   44288 
   44289   /* Assert that the caller has been consistent. If this cursor was opened
   44290   ** expecting an index b-tree, then the caller should be inserting blob
   44291   ** keys with no associated data. If the cursor was opened expecting an
   44292   ** intkey table, the caller should be inserting integer keys with a
   44293   ** blob of associated data.  */
   44294   assert( (pKey==0)==(pCur->pKeyInfo==0) );
   44295 
   44296   /* If this is an insert into a table b-tree, invalidate any incrblob
   44297   ** cursors open on the row being replaced (assuming this is a replace
   44298   ** operation - if it is not, the following is a no-op).  */
   44299   if( pCur->pKeyInfo==0 ){
   44300     invalidateIncrblobCursors(p, nKey, 0);
   44301   }
   44302 
   44303   /* Save the positions of any other cursors open on this table.
   44304   **
   44305   ** In some cases, the call to btreeMoveto() below is a no-op. For
   44306   ** example, when inserting data into a table with auto-generated integer
   44307   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
   44308   ** integer key to use. It then calls this function to actually insert the
   44309   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
   44310   ** that the cursor is already where it needs to be and returns without
   44311   ** doing any work. To avoid thwarting these optimizations, it is important
   44312   ** not to clear the cursor here.
   44313   */
   44314   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
   44315   if( rc ) return rc;
   44316   if( !loc ){
   44317     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
   44318     if( rc ) return rc;
   44319   }
   44320   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
   44321 
   44322   pPage = pCur->apPage[pCur->iPage];
   44323   assert( pPage->intKey || nKey>=0 );
   44324   assert( pPage->leaf || !pPage->intKey );
   44325 
   44326   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
   44327           pCur->pgnoRoot, nKey, nData, pPage->pgno,
   44328           loc==0 ? "overwrite" : "new entry"));
   44329   assert( pPage->isInit );
   44330   allocateTempSpace(pBt);
   44331   newCell = pBt->pTmpSpace;
   44332   if( newCell==0 ) return SQLITE_NOMEM;
   44333   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
   44334   if( rc ) goto end_insert;
   44335   assert( szNew==cellSizePtr(pPage, newCell) );
   44336   assert( szNew<=MX_CELL_SIZE(pBt) );
   44337   idx = pCur->aiIdx[pCur->iPage];
   44338   if( loc==0 ){
   44339     u16 szOld;
   44340     assert( idx<pPage->nCell );
   44341     rc = sqlite3PagerWrite(pPage->pDbPage);
   44342     if( rc ){
   44343       goto end_insert;
   44344     }
   44345     oldCell = findCell(pPage, idx);
   44346     if( !pPage->leaf ){
   44347       memcpy(newCell, oldCell, 4);
   44348     }
   44349     szOld = cellSizePtr(pPage, oldCell);
   44350     rc = clearCell(pPage, oldCell);
   44351     dropCell(pPage, idx, szOld, &rc);
   44352     if( rc ) goto end_insert;
   44353   }else if( loc<0 && pPage->nCell>0 ){
   44354     assert( pPage->leaf );
   44355     idx = ++pCur->aiIdx[pCur->iPage];
   44356   }else{
   44357     assert( pPage->leaf );
   44358   }
   44359   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
   44360   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
   44361 
   44362   /* If no error has occured and pPage has an overflow cell, call balance()
   44363   ** to redistribute the cells within the tree. Since balance() may move
   44364   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
   44365   ** variables.
   44366   **
   44367   ** Previous versions of SQLite called moveToRoot() to move the cursor
   44368   ** back to the root page as balance() used to invalidate the contents
   44369   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
   44370   ** set the cursor state to "invalid". This makes common insert operations
   44371   ** slightly faster.
   44372   **
   44373   ** There is a subtle but important optimization here too. When inserting
   44374   ** multiple records into an intkey b-tree using a single cursor (as can
   44375   ** happen while processing an "INSERT INTO ... SELECT" statement), it
   44376   ** is advantageous to leave the cursor pointing to the last entry in
   44377   ** the b-tree if possible. If the cursor is left pointing to the last
   44378   ** entry in the table, and the next row inserted has an integer key
   44379   ** larger than the largest existing key, it is possible to insert the
   44380   ** row without seeking the cursor. This can be a big performance boost.
   44381   */
   44382   pCur->info.nSize = 0;
   44383   pCur->validNKey = 0;
   44384   if( rc==SQLITE_OK && pPage->nOverflow ){
   44385     rc = balance(pCur);
   44386 
   44387     /* Must make sure nOverflow is reset to zero even if the balance()
   44388     ** fails. Internal data structure corruption will result otherwise.
   44389     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
   44390     ** from trying to save the current position of the cursor.  */
   44391     pCur->apPage[pCur->iPage]->nOverflow = 0;
   44392     pCur->eState = CURSOR_INVALID;
   44393   }
   44394   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
   44395 
   44396 end_insert:
   44397   return rc;
   44398 }
   44399 
   44400 /*
   44401 ** Delete the entry that the cursor is pointing to.  The cursor
   44402 ** is left pointing at a arbitrary location.
   44403 */
   44404 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
   44405   Btree *p = pCur->pBtree;
   44406   BtShared *pBt = p->pBt;
   44407   int rc;                              /* Return code */
   44408   MemPage *pPage;                      /* Page to delete cell from */
   44409   unsigned char *pCell;                /* Pointer to cell to delete */
   44410   int iCellIdx;                        /* Index of cell to delete */
   44411   int iCellDepth;                      /* Depth of node containing pCell */
   44412 
   44413   assert( cursorHoldsMutex(pCur) );
   44414   assert( pBt->inTransaction==TRANS_WRITE );
   44415   assert( !pBt->readOnly );
   44416   assert( pCur->wrFlag );
   44417   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
   44418   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
   44419 
   44420   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
   44421    || NEVER(pCur->eState!=CURSOR_VALID)
   44422   ){
   44423     return SQLITE_ERROR;  /* Something has gone awry. */
   44424   }
   44425 
   44426   /* If this is a delete operation to remove a row from a table b-tree,
   44427   ** invalidate any incrblob cursors open on the row being deleted.  */
   44428   if( pCur->pKeyInfo==0 ){
   44429     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
   44430   }
   44431 
   44432   iCellDepth = pCur->iPage;
   44433   iCellIdx = pCur->aiIdx[iCellDepth];
   44434   pPage = pCur->apPage[iCellDepth];
   44435   pCell = findCell(pPage, iCellIdx);
   44436 
   44437   /* If the page containing the entry to delete is not a leaf page, move
   44438   ** the cursor to the largest entry in the tree that is smaller than
   44439   ** the entry being deleted. This cell will replace the cell being deleted
   44440   ** from the internal node. The 'previous' entry is used for this instead
   44441   ** of the 'next' entry, as the previous entry is always a part of the
   44442   ** sub-tree headed by the child page of the cell being deleted. This makes
   44443   ** balancing the tree following the delete operation easier.  */
   44444   if( !pPage->leaf ){
   44445     int notUsed;
   44446     rc = sqlite3BtreePrevious(pCur, &notUsed);
   44447     if( rc ) return rc;
   44448   }
   44449 
   44450   /* Save the positions of any other cursors open on this table before
   44451   ** making any modifications. Make the page containing the entry to be
   44452   ** deleted writable. Then free any overflow pages associated with the
   44453   ** entry and finally remove the cell itself from within the page.
   44454   */
   44455   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
   44456   if( rc ) return rc;
   44457   rc = sqlite3PagerWrite(pPage->pDbPage);
   44458   if( rc ) return rc;
   44459   rc = clearCell(pPage, pCell);
   44460   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
   44461   if( rc ) return rc;
   44462 
   44463   /* If the cell deleted was not located on a leaf page, then the cursor
   44464   ** is currently pointing to the largest entry in the sub-tree headed
   44465   ** by the child-page of the cell that was just deleted from an internal
   44466   ** node. The cell from the leaf node needs to be moved to the internal
   44467   ** node to replace the deleted cell.  */
   44468   if( !pPage->leaf ){
   44469     MemPage *pLeaf = pCur->apPage[pCur->iPage];
   44470     int nCell;
   44471     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
   44472     unsigned char *pTmp;
   44473 
   44474     pCell = findCell(pLeaf, pLeaf->nCell-1);
   44475     nCell = cellSizePtr(pLeaf, pCell);
   44476     assert( MX_CELL_SIZE(pBt)>=nCell );
   44477 
   44478     allocateTempSpace(pBt);
   44479     pTmp = pBt->pTmpSpace;
   44480 
   44481     rc = sqlite3PagerWrite(pLeaf->pDbPage);
   44482     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
   44483     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
   44484     if( rc ) return rc;
   44485   }
   44486 
   44487   /* Balance the tree. If the entry deleted was located on a leaf page,
   44488   ** then the cursor still points to that page. In this case the first
   44489   ** call to balance() repairs the tree, and the if(...) condition is
   44490   ** never true.
   44491   **
   44492   ** Otherwise, if the entry deleted was on an internal node page, then
   44493   ** pCur is pointing to the leaf page from which a cell was removed to
   44494   ** replace the cell deleted from the internal node. This is slightly
   44495   ** tricky as the leaf node may be underfull, and the internal node may
   44496   ** be either under or overfull. In this case run the balancing algorithm
   44497   ** on the leaf node first. If the balance proceeds far enough up the
   44498   ** tree that we can be sure that any problem in the internal node has
   44499   ** been corrected, so be it. Otherwise, after balancing the leaf node,
   44500   ** walk the cursor up the tree to the internal node and balance it as
   44501   ** well.  */
   44502   rc = balance(pCur);
   44503   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
   44504     while( pCur->iPage>iCellDepth ){
   44505       releasePage(pCur->apPage[pCur->iPage--]);
   44506     }
   44507     rc = balance(pCur);
   44508   }
   44509 
   44510   if( rc==SQLITE_OK ){
   44511     moveToRoot(pCur);
   44512   }
   44513   return rc;
   44514 }
   44515 
   44516 /*
   44517 ** Create a new BTree table.  Write into *piTable the page
   44518 ** number for the root page of the new table.
   44519 **
   44520 ** The type of type is determined by the flags parameter.  Only the
   44521 ** following values of flags are currently in use.  Other values for
   44522 ** flags might not work:
   44523 **
   44524 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
   44525 **     BTREE_ZERODATA                  Used for SQL indices
   44526 */
   44527 static int btreeCreateTable(Btree *p, int *piTable, int flags){
   44528   BtShared *pBt = p->pBt;
   44529   MemPage *pRoot;
   44530   Pgno pgnoRoot;
   44531   int rc;
   44532 
   44533   assert( sqlite3BtreeHoldsMutex(p) );
   44534   assert( pBt->inTransaction==TRANS_WRITE );
   44535   assert( !pBt->readOnly );
   44536 
   44537 #ifdef SQLITE_OMIT_AUTOVACUUM
   44538   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
   44539   if( rc ){
   44540     return rc;
   44541   }
   44542 #else
   44543   if( pBt->autoVacuum ){
   44544     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
   44545     MemPage *pPageMove; /* The page to move to. */
   44546 
   44547     /* Creating a new table may probably require moving an existing database
   44548     ** to make room for the new tables root page. In case this page turns
   44549     ** out to be an overflow page, delete all overflow page-map caches
   44550     ** held by open cursors.
   44551     */
   44552     invalidateAllOverflowCache(pBt);
   44553 
   44554     /* Read the value of meta[3] from the database to determine where the
   44555     ** root page of the new table should go. meta[3] is the largest root-page
   44556     ** created so far, so the new root-page is (meta[3]+1).
   44557     */
   44558     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
   44559     pgnoRoot++;
   44560 
   44561     /* The new root-page may not be allocated on a pointer-map page, or the
   44562     ** PENDING_BYTE page.
   44563     */
   44564     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
   44565         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
   44566       pgnoRoot++;
   44567     }
   44568     assert( pgnoRoot>=3 );
   44569 
   44570     /* Allocate a page. The page that currently resides at pgnoRoot will
   44571     ** be moved to the allocated page (unless the allocated page happens
   44572     ** to reside at pgnoRoot).
   44573     */
   44574     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
   44575     if( rc!=SQLITE_OK ){
   44576       return rc;
   44577     }
   44578 
   44579     if( pgnoMove!=pgnoRoot ){
   44580       /* pgnoRoot is the page that will be used for the root-page of
   44581       ** the new table (assuming an error did not occur). But we were
   44582       ** allocated pgnoMove. If required (i.e. if it was not allocated
   44583       ** by extending the file), the current page at position pgnoMove
   44584       ** is already journaled.
   44585       */
   44586       u8 eType = 0;
   44587       Pgno iPtrPage = 0;
   44588 
   44589       releasePage(pPageMove);
   44590 
   44591       /* Move the page currently at pgnoRoot to pgnoMove. */
   44592       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
   44593       if( rc!=SQLITE_OK ){
   44594         return rc;
   44595       }
   44596       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
   44597       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
   44598         rc = SQLITE_CORRUPT_BKPT;
   44599       }
   44600       if( rc!=SQLITE_OK ){
   44601         releasePage(pRoot);
   44602         return rc;
   44603       }
   44604       assert( eType!=PTRMAP_ROOTPAGE );
   44605       assert( eType!=PTRMAP_FREEPAGE );
   44606       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
   44607       releasePage(pRoot);
   44608 
   44609       /* Obtain the page at pgnoRoot */
   44610       if( rc!=SQLITE_OK ){
   44611         return rc;
   44612       }
   44613       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
   44614       if( rc!=SQLITE_OK ){
   44615         return rc;
   44616       }
   44617       rc = sqlite3PagerWrite(pRoot->pDbPage);
   44618       if( rc!=SQLITE_OK ){
   44619         releasePage(pRoot);
   44620         return rc;
   44621       }
   44622     }else{
   44623       pRoot = pPageMove;
   44624     }
   44625 
   44626     /* Update the pointer-map and meta-data with the new root-page number. */
   44627     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
   44628     if( rc ){
   44629       releasePage(pRoot);
   44630       return rc;
   44631     }
   44632     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
   44633     if( rc ){
   44634       releasePage(pRoot);
   44635       return rc;
   44636     }
   44637 
   44638   }else{
   44639     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
   44640     if( rc ) return rc;
   44641   }
   44642 #endif
   44643   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
   44644   zeroPage(pRoot, flags | PTF_LEAF);
   44645   sqlite3PagerUnref(pRoot->pDbPage);
   44646   *piTable = (int)pgnoRoot;
   44647   return SQLITE_OK;
   44648 }
   44649 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
   44650   int rc;
   44651   sqlite3BtreeEnter(p);
   44652   rc = btreeCreateTable(p, piTable, flags);
   44653   sqlite3BtreeLeave(p);
   44654   return rc;
   44655 }
   44656 
   44657 /*
   44658 ** Erase the given database page and all its children.  Return
   44659 ** the page to the freelist.
   44660 */
   44661 static int clearDatabasePage(
   44662   BtShared *pBt,           /* The BTree that contains the table */
   44663   Pgno pgno,               /* Page number to clear */
   44664   int freePageFlag,        /* Deallocate page if true */
   44665   int *pnChange            /* Add number of Cells freed to this counter */
   44666 ){
   44667   MemPage *pPage;
   44668   int rc;
   44669   unsigned char *pCell;
   44670   int i;
   44671 
   44672   assert( sqlite3_mutex_held(pBt->mutex) );
   44673   if( pgno>pagerPagecount(pBt) ){
   44674     return SQLITE_CORRUPT_BKPT;
   44675   }
   44676 
   44677   rc = getAndInitPage(pBt, pgno, &pPage);
   44678   if( rc ) return rc;
   44679   for(i=0; i<pPage->nCell; i++){
   44680     pCell = findCell(pPage, i);
   44681     if( !pPage->leaf ){
   44682       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
   44683       if( rc ) goto cleardatabasepage_out;
   44684     }
   44685     rc = clearCell(pPage, pCell);
   44686     if( rc ) goto cleardatabasepage_out;
   44687   }
   44688   if( !pPage->leaf ){
   44689     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
   44690     if( rc ) goto cleardatabasepage_out;
   44691   }else if( pnChange ){
   44692     assert( pPage->intKey );
   44693     *pnChange += pPage->nCell;
   44694   }
   44695   if( freePageFlag ){
   44696     freePage(pPage, &rc);
   44697   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
   44698     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
   44699   }
   44700 
   44701 cleardatabasepage_out:
   44702   releasePage(pPage);
   44703   return rc;
   44704 }
   44705 
   44706 /*
   44707 ** Delete all information from a single table in the database.  iTable is
   44708 ** the page number of the root of the table.  After this routine returns,
   44709 ** the root page is empty, but still exists.
   44710 **
   44711 ** This routine will fail with SQLITE_LOCKED if there are any open
   44712 ** read cursors on the table.  Open write cursors are moved to the
   44713 ** root of the table.
   44714 **
   44715 ** If pnChange is not NULL, then table iTable must be an intkey table. The
   44716 ** integer value pointed to by pnChange is incremented by the number of
   44717 ** entries in the table.
   44718 */
   44719 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
   44720   int rc;
   44721   BtShared *pBt = p->pBt;
   44722   sqlite3BtreeEnter(p);
   44723   assert( p->inTrans==TRANS_WRITE );
   44724 
   44725   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
   44726   ** is the root of a table b-tree - if it is not, the following call is
   44727   ** a no-op).  */
   44728   invalidateIncrblobCursors(p, 0, 1);
   44729 
   44730   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
   44731   if( SQLITE_OK==rc ){
   44732     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
   44733   }
   44734   sqlite3BtreeLeave(p);
   44735   return rc;
   44736 }
   44737 
   44738 /*
   44739 ** Erase all information in a table and add the root of the table to
   44740 ** the freelist.  Except, the root of the principle table (the one on
   44741 ** page 1) is never added to the freelist.
   44742 **
   44743 ** This routine will fail with SQLITE_LOCKED if there are any open
   44744 ** cursors on the table.
   44745 **
   44746 ** If AUTOVACUUM is enabled and the page at iTable is not the last
   44747 ** root page in the database file, then the last root page
   44748 ** in the database file is moved into the slot formerly occupied by
   44749 ** iTable and that last slot formerly occupied by the last root page
   44750 ** is added to the freelist instead of iTable.  In this say, all
   44751 ** root pages are kept at the beginning of the database file, which
   44752 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
   44753 ** page number that used to be the last root page in the file before
   44754 ** the move.  If no page gets moved, *piMoved is set to 0.
   44755 ** The last root page is recorded in meta[3] and the value of
   44756 ** meta[3] is updated by this procedure.
   44757 */
   44758 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
   44759   int rc;
   44760   MemPage *pPage = 0;
   44761   BtShared *pBt = p->pBt;
   44762 
   44763   assert( sqlite3BtreeHoldsMutex(p) );
   44764   assert( p->inTrans==TRANS_WRITE );
   44765 
   44766   /* It is illegal to drop a table if any cursors are open on the
   44767   ** database. This is because in auto-vacuum mode the backend may
   44768   ** need to move another root-page to fill a gap left by the deleted
   44769   ** root page. If an open cursor was using this page a problem would
   44770   ** occur.
   44771   **
   44772   ** This error is caught long before control reaches this point.
   44773   */
   44774   if( NEVER(pBt->pCursor) ){
   44775     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
   44776     return SQLITE_LOCKED_SHAREDCACHE;
   44777   }
   44778 
   44779   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
   44780   if( rc ) return rc;
   44781   rc = sqlite3BtreeClearTable(p, iTable, 0);
   44782   if( rc ){
   44783     releasePage(pPage);
   44784     return rc;
   44785   }
   44786 
   44787   *piMoved = 0;
   44788 
   44789   if( iTable>1 ){
   44790 #ifdef SQLITE_OMIT_AUTOVACUUM
   44791     freePage(pPage, &rc);
   44792     releasePage(pPage);
   44793 #else
   44794     if( pBt->autoVacuum ){
   44795       Pgno maxRootPgno;
   44796       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
   44797 
   44798       if( iTable==maxRootPgno ){
   44799         /* If the table being dropped is the table with the largest root-page
   44800         ** number in the database, put the root page on the free list.
   44801         */
   44802         freePage(pPage, &rc);
   44803         releasePage(pPage);
   44804         if( rc!=SQLITE_OK ){
   44805           return rc;
   44806         }
   44807       }else{
   44808         /* The table being dropped does not have the largest root-page
   44809         ** number in the database. So move the page that does into the
   44810         ** gap left by the deleted root-page.
   44811         */
   44812         MemPage *pMove;
   44813         releasePage(pPage);
   44814         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
   44815         if( rc!=SQLITE_OK ){
   44816           return rc;
   44817         }
   44818         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
   44819         releasePage(pMove);
   44820         if( rc!=SQLITE_OK ){
   44821           return rc;
   44822         }
   44823         pMove = 0;
   44824         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
   44825         freePage(pMove, &rc);
   44826         releasePage(pMove);
   44827         if( rc!=SQLITE_OK ){
   44828           return rc;
   44829         }
   44830         *piMoved = maxRootPgno;
   44831       }
   44832 
   44833       /* Set the new 'max-root-page' value in the database header. This
   44834       ** is the old value less one, less one more if that happens to
   44835       ** be a root-page number, less one again if that is the
   44836       ** PENDING_BYTE_PAGE.
   44837       */
   44838       maxRootPgno--;
   44839       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
   44840              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
   44841         maxRootPgno--;
   44842       }
   44843       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
   44844 
   44845       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
   44846     }else{
   44847       freePage(pPage, &rc);
   44848       releasePage(pPage);
   44849     }
   44850 #endif
   44851   }else{
   44852     /* If sqlite3BtreeDropTable was called on page 1.
   44853     ** This really never should happen except in a corrupt
   44854     ** database.
   44855     */
   44856     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
   44857     releasePage(pPage);
   44858   }
   44859   return rc;
   44860 }
   44861 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
   44862   int rc;
   44863   sqlite3BtreeEnter(p);
   44864   rc = btreeDropTable(p, iTable, piMoved);
   44865   sqlite3BtreeLeave(p);
   44866   return rc;
   44867 }
   44868 
   44869 
   44870 /*
   44871 ** This function may only be called if the b-tree connection already
   44872 ** has a read or write transaction open on the database.
   44873 **
   44874 ** Read the meta-information out of a database file.  Meta[0]
   44875 ** is the number of free pages currently in the database.  Meta[1]
   44876 ** through meta[15] are available for use by higher layers.  Meta[0]
   44877 ** is read-only, the others are read/write.
   44878 **
   44879 ** The schema layer numbers meta values differently.  At the schema
   44880 ** layer (and the SetCookie and ReadCookie opcodes) the number of
   44881 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
   44882 */
   44883 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
   44884   BtShared *pBt = p->pBt;
   44885 
   44886   sqlite3BtreeEnter(p);
   44887   assert( p->inTrans>TRANS_NONE );
   44888   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
   44889   assert( pBt->pPage1 );
   44890   assert( idx>=0 && idx<=15 );
   44891 
   44892   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
   44893 
   44894   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
   44895   ** database, mark the database as read-only.  */
   44896 #ifdef SQLITE_OMIT_AUTOVACUUM
   44897   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
   44898 #endif
   44899 
   44900   sqlite3BtreeLeave(p);
   44901 }
   44902 
   44903 /*
   44904 ** Write meta-information back into the database.  Meta[0] is
   44905 ** read-only and may not be written.
   44906 */
   44907 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
   44908   BtShared *pBt = p->pBt;
   44909   unsigned char *pP1;
   44910   int rc;
   44911   assert( idx>=1 && idx<=15 );
   44912   sqlite3BtreeEnter(p);
   44913   assert( p->inTrans==TRANS_WRITE );
   44914   assert( pBt->pPage1!=0 );
   44915   pP1 = pBt->pPage1->aData;
   44916   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   44917   if( rc==SQLITE_OK ){
   44918     put4byte(&pP1[36 + idx*4], iMeta);
   44919 #ifndef SQLITE_OMIT_AUTOVACUUM
   44920     if( idx==BTREE_INCR_VACUUM ){
   44921       assert( pBt->autoVacuum || iMeta==0 );
   44922       assert( iMeta==0 || iMeta==1 );
   44923       pBt->incrVacuum = (u8)iMeta;
   44924     }
   44925 #endif
   44926   }
   44927   sqlite3BtreeLeave(p);
   44928   return rc;
   44929 }
   44930 
   44931 #ifndef SQLITE_OMIT_BTREECOUNT
   44932 /*
   44933 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
   44934 ** number of entries in the b-tree and write the result to *pnEntry.
   44935 **
   44936 ** SQLITE_OK is returned if the operation is successfully executed.
   44937 ** Otherwise, if an error is encountered (i.e. an IO error or database
   44938 ** corruption) an SQLite error code is returned.
   44939 */
   44940 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
   44941   i64 nEntry = 0;                      /* Value to return in *pnEntry */
   44942   int rc;                              /* Return code */
   44943   rc = moveToRoot(pCur);
   44944 
   44945   /* Unless an error occurs, the following loop runs one iteration for each
   44946   ** page in the B-Tree structure (not including overflow pages).
   44947   */
   44948   while( rc==SQLITE_OK ){
   44949     int iIdx;                          /* Index of child node in parent */
   44950     MemPage *pPage;                    /* Current page of the b-tree */
   44951 
   44952     /* If this is a leaf page or the tree is not an int-key tree, then
   44953     ** this page contains countable entries. Increment the entry counter
   44954     ** accordingly.
   44955     */
   44956     pPage = pCur->apPage[pCur->iPage];
   44957     if( pPage->leaf || !pPage->intKey ){
   44958       nEntry += pPage->nCell;
   44959     }
   44960 
   44961     /* pPage is a leaf node. This loop navigates the cursor so that it
   44962     ** points to the first interior cell that it points to the parent of
   44963     ** the next page in the tree that has not yet been visited. The
   44964     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
   44965     ** of the page, or to the number of cells in the page if the next page
   44966     ** to visit is the right-child of its parent.
   44967     **
   44968     ** If all pages in the tree have been visited, return SQLITE_OK to the
   44969     ** caller.
   44970     */
   44971     if( pPage->leaf ){
   44972       do {
   44973         if( pCur->iPage==0 ){
   44974           /* All pages of the b-tree have been visited. Return successfully. */
   44975           *pnEntry = nEntry;
   44976           return SQLITE_OK;
   44977         }
   44978         moveToParent(pCur);
   44979       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
   44980 
   44981       pCur->aiIdx[pCur->iPage]++;
   44982       pPage = pCur->apPage[pCur->iPage];
   44983     }
   44984 
   44985     /* Descend to the child node of the cell that the cursor currently
   44986     ** points at. This is the right-child if (iIdx==pPage->nCell).
   44987     */
   44988     iIdx = pCur->aiIdx[pCur->iPage];
   44989     if( iIdx==pPage->nCell ){
   44990       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
   44991     }else{
   44992       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
   44993     }
   44994   }
   44995 
   44996   /* An error has occurred. Return an error code. */
   44997   return rc;
   44998 }
   44999 #endif
   45000 
   45001 /*
   45002 ** Return the pager associated with a BTree.  This routine is used for
   45003 ** testing and debugging only.
   45004 */
   45005 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
   45006   return p->pBt->pPager;
   45007 }
   45008 
   45009 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   45010 /*
   45011 ** Append a message to the error message string.
   45012 */
   45013 static void checkAppendMsg(
   45014   IntegrityCk *pCheck,
   45015   char *zMsg1,
   45016   const char *zFormat,
   45017   ...
   45018 ){
   45019   va_list ap;
   45020   if( !pCheck->mxErr ) return;
   45021   pCheck->mxErr--;
   45022   pCheck->nErr++;
   45023   va_start(ap, zFormat);
   45024   if( pCheck->errMsg.nChar ){
   45025     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
   45026   }
   45027   if( zMsg1 ){
   45028     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
   45029   }
   45030   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
   45031   va_end(ap);
   45032   if( pCheck->errMsg.mallocFailed ){
   45033     pCheck->mallocFailed = 1;
   45034   }
   45035 }
   45036 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   45037 
   45038 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   45039 /*
   45040 ** Add 1 to the reference count for page iPage.  If this is the second
   45041 ** reference to the page, add an error message to pCheck->zErrMsg.
   45042 ** Return 1 if there are 2 ore more references to the page and 0 if
   45043 ** if this is the first reference to the page.
   45044 **
   45045 ** Also check that the page number is in bounds.
   45046 */
   45047 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
   45048   if( iPage==0 ) return 1;
   45049   if( iPage>pCheck->nPage ){
   45050     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
   45051     return 1;
   45052   }
   45053   if( pCheck->anRef[iPage]==1 ){
   45054     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
   45055     return 1;
   45056   }
   45057   return  (pCheck->anRef[iPage]++)>1;
   45058 }
   45059 
   45060 #ifndef SQLITE_OMIT_AUTOVACUUM
   45061 /*
   45062 ** Check that the entry in the pointer-map for page iChild maps to
   45063 ** page iParent, pointer type ptrType. If not, append an error message
   45064 ** to pCheck.
   45065 */
   45066 static void checkPtrmap(
   45067   IntegrityCk *pCheck,   /* Integrity check context */
   45068   Pgno iChild,           /* Child page number */
   45069   u8 eType,              /* Expected pointer map type */
   45070   Pgno iParent,          /* Expected pointer map parent page number */
   45071   char *zContext         /* Context description (used for error msg) */
   45072 ){
   45073   int rc;
   45074   u8 ePtrmapType;
   45075   Pgno iPtrmapParent;
   45076 
   45077   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
   45078   if( rc!=SQLITE_OK ){
   45079     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
   45080     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
   45081     return;
   45082   }
   45083 
   45084   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
   45085     checkAppendMsg(pCheck, zContext,
   45086       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
   45087       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
   45088   }
   45089 }
   45090 #endif
   45091 
   45092 /*
   45093 ** Check the integrity of the freelist or of an overflow page list.
   45094 ** Verify that the number of pages on the list is N.
   45095 */
   45096 static void checkList(
   45097   IntegrityCk *pCheck,  /* Integrity checking context */
   45098   int isFreeList,       /* True for a freelist.  False for overflow page list */
   45099   int iPage,            /* Page number for first page in the list */
   45100   int N,                /* Expected number of pages in the list */
   45101   char *zContext        /* Context for error messages */
   45102 ){
   45103   int i;
   45104   int expected = N;
   45105   int iFirst = iPage;
   45106   while( N-- > 0 && pCheck->mxErr ){
   45107     DbPage *pOvflPage;
   45108     unsigned char *pOvflData;
   45109     if( iPage<1 ){
   45110       checkAppendMsg(pCheck, zContext,
   45111          "%d of %d pages missing from overflow list starting at %d",
   45112           N+1, expected, iFirst);
   45113       break;
   45114     }
   45115     if( checkRef(pCheck, iPage, zContext) ) break;
   45116     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
   45117       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
   45118       break;
   45119     }
   45120     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
   45121     if( isFreeList ){
   45122       int n = get4byte(&pOvflData[4]);
   45123 #ifndef SQLITE_OMIT_AUTOVACUUM
   45124       if( pCheck->pBt->autoVacuum ){
   45125         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
   45126       }
   45127 #endif
   45128       if( n>pCheck->pBt->usableSize/4-2 ){
   45129         checkAppendMsg(pCheck, zContext,
   45130            "freelist leaf count too big on page %d", iPage);
   45131         N--;
   45132       }else{
   45133         for(i=0; i<n; i++){
   45134           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
   45135 #ifndef SQLITE_OMIT_AUTOVACUUM
   45136           if( pCheck->pBt->autoVacuum ){
   45137             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
   45138           }
   45139 #endif
   45140           checkRef(pCheck, iFreePage, zContext);
   45141         }
   45142         N -= n;
   45143       }
   45144     }
   45145 #ifndef SQLITE_OMIT_AUTOVACUUM
   45146     else{
   45147       /* If this database supports auto-vacuum and iPage is not the last
   45148       ** page in this overflow list, check that the pointer-map entry for
   45149       ** the following page matches iPage.
   45150       */
   45151       if( pCheck->pBt->autoVacuum && N>0 ){
   45152         i = get4byte(pOvflData);
   45153         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
   45154       }
   45155     }
   45156 #endif
   45157     iPage = get4byte(pOvflData);
   45158     sqlite3PagerUnref(pOvflPage);
   45159   }
   45160 }
   45161 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   45162 
   45163 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   45164 /*
   45165 ** Do various sanity checks on a single page of a tree.  Return
   45166 ** the tree depth.  Root pages return 0.  Parents of root pages
   45167 ** return 1, and so forth.
   45168 **
   45169 ** These checks are done:
   45170 **
   45171 **      1.  Make sure that cells and freeblocks do not overlap
   45172 **          but combine to completely cover the page.
   45173 **  NO  2.  Make sure cell keys are in order.
   45174 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
   45175 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
   45176 **      5.  Check the integrity of overflow pages.
   45177 **      6.  Recursively call checkTreePage on all children.
   45178 **      7.  Verify that the depth of all children is the same.
   45179 **      8.  Make sure this page is at least 33% full or else it is
   45180 **          the root of the tree.
   45181 */
   45182 static int checkTreePage(
   45183   IntegrityCk *pCheck,  /* Context for the sanity check */
   45184   int iPage,            /* Page number of the page to check */
   45185   char *zParentContext, /* Parent context */
   45186   i64 *pnParentMinKey,
   45187   i64 *pnParentMaxKey
   45188 ){
   45189   MemPage *pPage;
   45190   int i, rc, depth, d2, pgno, cnt;
   45191   int hdr, cellStart;
   45192   int nCell;
   45193   u8 *data;
   45194   BtShared *pBt;
   45195   int usableSize;
   45196   char zContext[100];
   45197   char *hit = 0;
   45198   i64 nMinKey = 0;
   45199   i64 nMaxKey = 0;
   45200 
   45201   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
   45202 
   45203   /* Check that the page exists
   45204   */
   45205   pBt = pCheck->pBt;
   45206   usableSize = pBt->usableSize;
   45207   if( iPage==0 ) return 0;
   45208   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
   45209   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
   45210     checkAppendMsg(pCheck, zContext,
   45211        "unable to get the page. error code=%d", rc);
   45212     return 0;
   45213   }
   45214 
   45215   /* Clear MemPage.isInit to make sure the corruption detection code in
   45216   ** btreeInitPage() is executed.  */
   45217   pPage->isInit = 0;
   45218   if( (rc = btreeInitPage(pPage))!=0 ){
   45219     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
   45220     checkAppendMsg(pCheck, zContext,
   45221                    "btreeInitPage() returns error code %d", rc);
   45222     releasePage(pPage);
   45223     return 0;
   45224   }
   45225 
   45226   /* Check out all the cells.
   45227   */
   45228   depth = 0;
   45229   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
   45230     u8 *pCell;
   45231     u32 sz;
   45232     CellInfo info;
   45233 
   45234     /* Check payload overflow pages
   45235     */
   45236     sqlite3_snprintf(sizeof(zContext), zContext,
   45237              "On tree page %d cell %d: ", iPage, i);
   45238     pCell = findCell(pPage,i);
   45239     btreeParseCellPtr(pPage, pCell, &info);
   45240     sz = info.nData;
   45241     if( !pPage->intKey ) sz += (int)info.nKey;
   45242     /* For intKey pages, check that the keys are in order.
   45243     */
   45244     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
   45245     else{
   45246       if( info.nKey <= nMaxKey ){
   45247         checkAppendMsg(pCheck, zContext,
   45248             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
   45249       }
   45250       nMaxKey = info.nKey;
   45251     }
   45252     assert( sz==info.nPayload );
   45253     if( (sz>info.nLocal)
   45254      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
   45255     ){
   45256       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
   45257       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
   45258 #ifndef SQLITE_OMIT_AUTOVACUUM
   45259       if( pBt->autoVacuum ){
   45260         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
   45261       }
   45262 #endif
   45263       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
   45264     }
   45265 
   45266     /* Check sanity of left child page.
   45267     */
   45268     if( !pPage->leaf ){
   45269       pgno = get4byte(pCell);
   45270 #ifndef SQLITE_OMIT_AUTOVACUUM
   45271       if( pBt->autoVacuum ){
   45272         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
   45273       }
   45274 #endif
   45275       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
   45276       if( i>0 && d2!=depth ){
   45277         checkAppendMsg(pCheck, zContext, "Child page depth differs");
   45278       }
   45279       depth = d2;
   45280     }
   45281   }
   45282 
   45283   if( !pPage->leaf ){
   45284     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   45285     sqlite3_snprintf(sizeof(zContext), zContext,
   45286                      "On page %d at right child: ", iPage);
   45287 #ifndef SQLITE_OMIT_AUTOVACUUM
   45288     if( pBt->autoVacuum ){
   45289       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
   45290     }
   45291 #endif
   45292     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
   45293   }
   45294 
   45295   /* For intKey leaf pages, check that the min/max keys are in order
   45296   ** with any left/parent/right pages.
   45297   */
   45298   if( pPage->leaf && pPage->intKey ){
   45299     /* if we are a left child page */
   45300     if( pnParentMinKey ){
   45301       /* if we are the left most child page */
   45302       if( !pnParentMaxKey ){
   45303         if( nMaxKey > *pnParentMinKey ){
   45304           checkAppendMsg(pCheck, zContext,
   45305               "Rowid %lld out of order (max larger than parent min of %lld)",
   45306               nMaxKey, *pnParentMinKey);
   45307         }
   45308       }else{
   45309         if( nMinKey <= *pnParentMinKey ){
   45310           checkAppendMsg(pCheck, zContext,
   45311               "Rowid %lld out of order (min less than parent min of %lld)",
   45312               nMinKey, *pnParentMinKey);
   45313         }
   45314         if( nMaxKey > *pnParentMaxKey ){
   45315           checkAppendMsg(pCheck, zContext,
   45316               "Rowid %lld out of order (max larger than parent max of %lld)",
   45317               nMaxKey, *pnParentMaxKey);
   45318         }
   45319         *pnParentMinKey = nMaxKey;
   45320       }
   45321     /* else if we're a right child page */
   45322     } else if( pnParentMaxKey ){
   45323       if( nMinKey <= *pnParentMaxKey ){
   45324         checkAppendMsg(pCheck, zContext,
   45325             "Rowid %lld out of order (min less than parent max of %lld)",
   45326             nMinKey, *pnParentMaxKey);
   45327       }
   45328     }
   45329   }
   45330 
   45331   /* Check for complete coverage of the page
   45332   */
   45333   data = pPage->aData;
   45334   hdr = pPage->hdrOffset;
   45335   hit = sqlite3PageMalloc( pBt->pageSize );
   45336   if( hit==0 ){
   45337     pCheck->mallocFailed = 1;
   45338   }else{
   45339     u16 contentOffset = get2byte(&data[hdr+5]);
   45340     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
   45341     memset(hit+contentOffset, 0, usableSize-contentOffset);
   45342     memset(hit, 1, contentOffset);
   45343     nCell = get2byte(&data[hdr+3]);
   45344     cellStart = hdr + 12 - 4*pPage->leaf;
   45345     for(i=0; i<nCell; i++){
   45346       int pc = get2byte(&data[cellStart+i*2]);
   45347       u16 size = 1024;
   45348       int j;
   45349       if( pc<=usableSize-4 ){
   45350         size = cellSizePtr(pPage, &data[pc]);
   45351       }
   45352       if( (pc+size-1)>=usableSize ){
   45353         checkAppendMsg(pCheck, 0,
   45354             "Corruption detected in cell %d on page %d",i,iPage);
   45355       }else{
   45356         for(j=pc+size-1; j>=pc; j--) hit[j]++;
   45357       }
   45358     }
   45359     i = get2byte(&data[hdr+1]);
   45360     while( i>0 ){
   45361       int size, j;
   45362       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
   45363       size = get2byte(&data[i+2]);
   45364       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
   45365       for(j=i+size-1; j>=i; j--) hit[j]++;
   45366       j = get2byte(&data[i]);
   45367       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
   45368       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
   45369       i = j;
   45370     }
   45371     for(i=cnt=0; i<usableSize; i++){
   45372       if( hit[i]==0 ){
   45373         cnt++;
   45374       }else if( hit[i]>1 ){
   45375         checkAppendMsg(pCheck, 0,
   45376           "Multiple uses for byte %d of page %d", i, iPage);
   45377         break;
   45378       }
   45379     }
   45380     if( cnt!=data[hdr+7] ){
   45381       checkAppendMsg(pCheck, 0,
   45382           "Fragmentation of %d bytes reported as %d on page %d",
   45383           cnt, data[hdr+7], iPage);
   45384     }
   45385   }
   45386   sqlite3PageFree(hit);
   45387   releasePage(pPage);
   45388   return depth+1;
   45389 }
   45390 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   45391 
   45392 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   45393 /*
   45394 ** This routine does a complete check of the given BTree file.  aRoot[] is
   45395 ** an array of pages numbers were each page number is the root page of
   45396 ** a table.  nRoot is the number of entries in aRoot.
   45397 **
   45398 ** A read-only or read-write transaction must be opened before calling
   45399 ** this function.
   45400 **
   45401 ** Write the number of error seen in *pnErr.  Except for some memory
   45402 ** allocation errors,  an error message held in memory obtained from
   45403 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
   45404 ** returned.  If a memory allocation error occurs, NULL is returned.
   45405 */
   45406 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
   45407   Btree *p,     /* The btree to be checked */
   45408   int *aRoot,   /* An array of root pages numbers for individual trees */
   45409   int nRoot,    /* Number of entries in aRoot[] */
   45410   int mxErr,    /* Stop reporting errors after this many */
   45411   int *pnErr    /* Write number of errors seen to this variable */
   45412 ){
   45413   Pgno i;
   45414   int nRef;
   45415   IntegrityCk sCheck;
   45416   BtShared *pBt = p->pBt;
   45417   char zErr[100];
   45418 
   45419   sqlite3BtreeEnter(p);
   45420   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
   45421   nRef = sqlite3PagerRefcount(pBt->pPager);
   45422   sCheck.pBt = pBt;
   45423   sCheck.pPager = pBt->pPager;
   45424   sCheck.nPage = pagerPagecount(sCheck.pBt);
   45425   sCheck.mxErr = mxErr;
   45426   sCheck.nErr = 0;
   45427   sCheck.mallocFailed = 0;
   45428   *pnErr = 0;
   45429   if( sCheck.nPage==0 ){
   45430     sqlite3BtreeLeave(p);
   45431     return 0;
   45432   }
   45433   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
   45434   if( !sCheck.anRef ){
   45435     *pnErr = 1;
   45436     sqlite3BtreeLeave(p);
   45437     return 0;
   45438   }
   45439   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
   45440   i = PENDING_BYTE_PAGE(pBt);
   45441   if( i<=sCheck.nPage ){
   45442     sCheck.anRef[i] = 1;
   45443   }
   45444   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
   45445 
   45446   /* Check the integrity of the freelist
   45447   */
   45448   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
   45449             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
   45450 
   45451   /* Check all the tables.
   45452   */
   45453   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
   45454     if( aRoot[i]==0 ) continue;
   45455 #ifndef SQLITE_OMIT_AUTOVACUUM
   45456     if( pBt->autoVacuum && aRoot[i]>1 ){
   45457       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
   45458     }
   45459 #endif
   45460     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
   45461   }
   45462 
   45463   /* Make sure every page in the file is referenced
   45464   */
   45465   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
   45466 #ifdef SQLITE_OMIT_AUTOVACUUM
   45467     if( sCheck.anRef[i]==0 ){
   45468       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
   45469     }
   45470 #else
   45471     /* If the database supports auto-vacuum, make sure no tables contain
   45472     ** references to pointer-map pages.
   45473     */
   45474     if( sCheck.anRef[i]==0 &&
   45475        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
   45476       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
   45477     }
   45478     if( sCheck.anRef[i]!=0 &&
   45479        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
   45480       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
   45481     }
   45482 #endif
   45483   }
   45484 
   45485   /* Make sure this analysis did not leave any unref() pages.
   45486   ** This is an internal consistency check; an integrity check
   45487   ** of the integrity check.
   45488   */
   45489   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
   45490     checkAppendMsg(&sCheck, 0,
   45491       "Outstanding page count goes from %d to %d during this analysis",
   45492       nRef, sqlite3PagerRefcount(pBt->pPager)
   45493     );
   45494   }
   45495 
   45496   /* Clean  up and report errors.
   45497   */
   45498   sqlite3BtreeLeave(p);
   45499   sqlite3_free(sCheck.anRef);
   45500   if( sCheck.mallocFailed ){
   45501     sqlite3StrAccumReset(&sCheck.errMsg);
   45502     *pnErr = sCheck.nErr+1;
   45503     return 0;
   45504   }
   45505   *pnErr = sCheck.nErr;
   45506   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
   45507   return sqlite3StrAccumFinish(&sCheck.errMsg);
   45508 }
   45509 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   45510 
   45511 /*
   45512 ** Return the full pathname of the underlying database file.
   45513 **
   45514 ** The pager filename is invariant as long as the pager is
   45515 ** open so it is safe to access without the BtShared mutex.
   45516 */
   45517 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
   45518   assert( p->pBt->pPager!=0 );
   45519   return sqlite3PagerFilename(p->pBt->pPager);
   45520 }
   45521 
   45522 /*
   45523 ** Return the pathname of the journal file for this database. The return
   45524 ** value of this routine is the same regardless of whether the journal file
   45525 ** has been created or not.
   45526 **
   45527 ** The pager journal filename is invariant as long as the pager is
   45528 ** open so it is safe to access without the BtShared mutex.
   45529 */
   45530 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
   45531   assert( p->pBt->pPager!=0 );
   45532   return sqlite3PagerJournalname(p->pBt->pPager);
   45533 }
   45534 
   45535 /*
   45536 ** Return non-zero if a transaction is active.
   45537 */
   45538 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
   45539   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
   45540   return (p && (p->inTrans==TRANS_WRITE));
   45541 }
   45542 
   45543 /*
   45544 ** Return non-zero if a read (or write) transaction is active.
   45545 */
   45546 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
   45547   assert( p );
   45548   assert( sqlite3_mutex_held(p->db->mutex) );
   45549   return p->inTrans!=TRANS_NONE;
   45550 }
   45551 
   45552 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
   45553   assert( p );
   45554   assert( sqlite3_mutex_held(p->db->mutex) );
   45555   return p->nBackup!=0;
   45556 }
   45557 
   45558 /*
   45559 ** This function returns a pointer to a blob of memory associated with
   45560 ** a single shared-btree. The memory is used by client code for its own
   45561 ** purposes (for example, to store a high-level schema associated with
   45562 ** the shared-btree). The btree layer manages reference counting issues.
   45563 **
   45564 ** The first time this is called on a shared-btree, nBytes bytes of memory
   45565 ** are allocated, zeroed, and returned to the caller. For each subsequent
   45566 ** call the nBytes parameter is ignored and a pointer to the same blob
   45567 ** of memory returned.
   45568 **
   45569 ** If the nBytes parameter is 0 and the blob of memory has not yet been
   45570 ** allocated, a null pointer is returned. If the blob has already been
   45571 ** allocated, it is returned as normal.
   45572 **
   45573 ** Just before the shared-btree is closed, the function passed as the
   45574 ** xFree argument when the memory allocation was made is invoked on the
   45575 ** blob of allocated memory. This function should not call sqlite3_free()
   45576 ** on the memory, the btree layer does that.
   45577 */
   45578 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
   45579   BtShared *pBt = p->pBt;
   45580   sqlite3BtreeEnter(p);
   45581   if( !pBt->pSchema && nBytes ){
   45582     pBt->pSchema = sqlite3MallocZero(nBytes);
   45583     pBt->xFreeSchema = xFree;
   45584   }
   45585   sqlite3BtreeLeave(p);
   45586   return pBt->pSchema;
   45587 }
   45588 
   45589 /*
   45590 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
   45591 ** btree as the argument handle holds an exclusive lock on the
   45592 ** sqlite_master table. Otherwise SQLITE_OK.
   45593 */
   45594 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
   45595   int rc;
   45596   assert( sqlite3_mutex_held(p->db->mutex) );
   45597   sqlite3BtreeEnter(p);
   45598   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
   45599   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
   45600   sqlite3BtreeLeave(p);
   45601   return rc;
   45602 }
   45603 
   45604 
   45605 #ifndef SQLITE_OMIT_SHARED_CACHE
   45606 /*
   45607 ** Obtain a lock on the table whose root page is iTab.  The
   45608 ** lock is a write lock if isWritelock is true or a read lock
   45609 ** if it is false.
   45610 */
   45611 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
   45612   int rc = SQLITE_OK;
   45613   assert( p->inTrans!=TRANS_NONE );
   45614   if( p->sharable ){
   45615     u8 lockType = READ_LOCK + isWriteLock;
   45616     assert( READ_LOCK+1==WRITE_LOCK );
   45617     assert( isWriteLock==0 || isWriteLock==1 );
   45618 
   45619     sqlite3BtreeEnter(p);
   45620     rc = querySharedCacheTableLock(p, iTab, lockType);
   45621     if( rc==SQLITE_OK ){
   45622       rc = setSharedCacheTableLock(p, iTab, lockType);
   45623     }
   45624     sqlite3BtreeLeave(p);
   45625   }
   45626   return rc;
   45627 }
   45628 #endif
   45629 
   45630 #ifndef SQLITE_OMIT_INCRBLOB
   45631 /*
   45632 ** Argument pCsr must be a cursor opened for writing on an
   45633 ** INTKEY table currently pointing at a valid table entry.
   45634 ** This function modifies the data stored as part of that entry.
   45635 **
   45636 ** Only the data content may only be modified, it is not possible to
   45637 ** change the length of the data stored. If this function is called with
   45638 ** parameters that attempt to write past the end of the existing data,
   45639 ** no modifications are made and SQLITE_CORRUPT is returned.
   45640 */
   45641 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
   45642   int rc;
   45643   assert( cursorHoldsMutex(pCsr) );
   45644   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
   45645   assert( pCsr->isIncrblobHandle );
   45646 
   45647   rc = restoreCursorPosition(pCsr);
   45648   if( rc!=SQLITE_OK ){
   45649     return rc;
   45650   }
   45651   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
   45652   if( pCsr->eState!=CURSOR_VALID ){
   45653     return SQLITE_ABORT;
   45654   }
   45655 
   45656   /* Check some assumptions:
   45657   **   (a) the cursor is open for writing,
   45658   **   (b) there is a read/write transaction open,
   45659   **   (c) the connection holds a write-lock on the table (if required),
   45660   **   (d) there are no conflicting read-locks, and
   45661   **   (e) the cursor points at a valid row of an intKey table.
   45662   */
   45663   if( !pCsr->wrFlag ){
   45664     return SQLITE_READONLY;
   45665   }
   45666   assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
   45667   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
   45668   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
   45669   assert( pCsr->apPage[pCsr->iPage]->intKey );
   45670 
   45671   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
   45672 }
   45673 
   45674 /*
   45675 ** Set a flag on this cursor to cache the locations of pages from the
   45676 ** overflow list for the current row. This is used by cursors opened
   45677 ** for incremental blob IO only.
   45678 **
   45679 ** This function sets a flag only. The actual page location cache
   45680 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
   45681 ** accessPayload() (the worker function for sqlite3BtreeData() and
   45682 ** sqlite3BtreePutData()).
   45683 */
   45684 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
   45685   assert( cursorHoldsMutex(pCur) );
   45686   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   45687   assert(!pCur->isIncrblobHandle);
   45688   assert(!pCur->aOverflow);
   45689   pCur->isIncrblobHandle = 1;
   45690 }
   45691 #endif
   45692 
   45693 /************** End of btree.c ***********************************************/
   45694 /************** Begin file backup.c ******************************************/
   45695 /*
   45696 ** 2009 January 28
   45697 **
   45698 ** The author disclaims copyright to this source code.  In place of
   45699 ** a legal notice, here is a blessing:
   45700 **
   45701 **    May you do good and not evil.
   45702 **    May you find forgiveness for yourself and forgive others.
   45703 **    May you share freely, never taking more than you give.
   45704 **
   45705 *************************************************************************
   45706 ** This file contains the implementation of the sqlite3_backup_XXX()
   45707 ** API functions and the related features.
   45708 */
   45709 
   45710 /* Macro to find the minimum of two numeric values.
   45711 */
   45712 #ifndef MIN
   45713 # define MIN(x,y) ((x)<(y)?(x):(y))
   45714 #endif
   45715 
   45716 /*
   45717 ** Structure allocated for each backup operation.
   45718 */
   45719 struct sqlite3_backup {
   45720   sqlite3* pDestDb;        /* Destination database handle */
   45721   Btree *pDest;            /* Destination b-tree file */
   45722   u32 iDestSchema;         /* Original schema cookie in destination */
   45723   int bDestLocked;         /* True once a write-transaction is open on pDest */
   45724 
   45725   Pgno iNext;              /* Page number of the next source page to copy */
   45726   sqlite3* pSrcDb;         /* Source database handle */
   45727   Btree *pSrc;             /* Source b-tree file */
   45728 
   45729   int rc;                  /* Backup process error code */
   45730 
   45731   /* These two variables are set by every call to backup_step(). They are
   45732   ** read by calls to backup_remaining() and backup_pagecount().
   45733   */
   45734   Pgno nRemaining;         /* Number of pages left to copy */
   45735   Pgno nPagecount;         /* Total number of pages to copy */
   45736 
   45737   int isAttached;          /* True once backup has been registered with pager */
   45738   sqlite3_backup *pNext;   /* Next backup associated with source pager */
   45739 };
   45740 
   45741 /*
   45742 ** THREAD SAFETY NOTES:
   45743 **
   45744 **   Once it has been created using backup_init(), a single sqlite3_backup
   45745 **   structure may be accessed via two groups of thread-safe entry points:
   45746 **
   45747 **     * Via the sqlite3_backup_XXX() API function backup_step() and
   45748 **       backup_finish(). Both these functions obtain the source database
   45749 **       handle mutex and the mutex associated with the source BtShared
   45750 **       structure, in that order.
   45751 **
   45752 **     * Via the BackupUpdate() and BackupRestart() functions, which are
   45753 **       invoked by the pager layer to report various state changes in
   45754 **       the page cache associated with the source database. The mutex
   45755 **       associated with the source database BtShared structure will always
   45756 **       be held when either of these functions are invoked.
   45757 **
   45758 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
   45759 **   backup_pagecount() are not thread-safe functions. If they are called
   45760 **   while some other thread is calling backup_step() or backup_finish(),
   45761 **   the values returned may be invalid. There is no way for a call to
   45762 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
   45763 **   or backup_pagecount().
   45764 **
   45765 **   Depending on the SQLite configuration, the database handles and/or
   45766 **   the Btree objects may have their own mutexes that require locking.
   45767 **   Non-sharable Btrees (in-memory databases for example), do not have
   45768 **   associated mutexes.
   45769 */
   45770 
   45771 /*
   45772 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
   45773 ** in connection handle pDb. If such a database cannot be found, return
   45774 ** a NULL pointer and write an error message to pErrorDb.
   45775 **
   45776 ** If the "temp" database is requested, it may need to be opened by this
   45777 ** function. If an error occurs while doing so, return 0 and write an
   45778 ** error message to pErrorDb.
   45779 */
   45780 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
   45781   int i = sqlite3FindDbName(pDb, zDb);
   45782 
   45783   if( i==1 ){
   45784     Parse *pParse;
   45785     int rc = 0;
   45786     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
   45787     if( pParse==0 ){
   45788       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
   45789       rc = SQLITE_NOMEM;
   45790     }else{
   45791       pParse->db = pDb;
   45792       if( sqlite3OpenTempDatabase(pParse) ){
   45793         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
   45794         rc = SQLITE_ERROR;
   45795       }
   45796       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
   45797       sqlite3StackFree(pErrorDb, pParse);
   45798     }
   45799     if( rc ){
   45800       return 0;
   45801     }
   45802   }
   45803 
   45804   if( i<0 ){
   45805     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
   45806     return 0;
   45807   }
   45808 
   45809   return pDb->aDb[i].pBt;
   45810 }
   45811 
   45812 /*
   45813 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
   45814 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
   45815 ** a pointer to the new sqlite3_backup object.
   45816 **
   45817 ** If an error occurs, NULL is returned and an error code and error message
   45818 ** stored in database handle pDestDb.
   45819 */
   45820 SQLITE_API sqlite3_backup *sqlite3_backup_init(
   45821   sqlite3* pDestDb,                     /* Database to write to */
   45822   const char *zDestDb,                  /* Name of database within pDestDb */
   45823   sqlite3* pSrcDb,                      /* Database connection to read from */
   45824   const char *zSrcDb                    /* Name of database within pSrcDb */
   45825 ){
   45826   sqlite3_backup *p;                    /* Value to return */
   45827 
   45828   /* Lock the source database handle. The destination database
   45829   ** handle is not locked in this routine, but it is locked in
   45830   ** sqlite3_backup_step(). The user is required to ensure that no
   45831   ** other thread accesses the destination handle for the duration
   45832   ** of the backup operation.  Any attempt to use the destination
   45833   ** database connection while a backup is in progress may cause
   45834   ** a malfunction or a deadlock.
   45835   */
   45836   sqlite3_mutex_enter(pSrcDb->mutex);
   45837   sqlite3_mutex_enter(pDestDb->mutex);
   45838 
   45839   if( pSrcDb==pDestDb ){
   45840     sqlite3Error(
   45841         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
   45842     );
   45843     p = 0;
   45844   }else {
   45845     /* Allocate space for a new sqlite3_backup object */
   45846     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
   45847     if( !p ){
   45848       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
   45849     }
   45850   }
   45851 
   45852   /* If the allocation succeeded, populate the new object. */
   45853   if( p ){
   45854     memset(p, 0, sizeof(sqlite3_backup));
   45855     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
   45856     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
   45857     p->pDestDb = pDestDb;
   45858     p->pSrcDb = pSrcDb;
   45859     p->iNext = 1;
   45860     p->isAttached = 0;
   45861 
   45862     if( 0==p->pSrc || 0==p->pDest ){
   45863       /* One (or both) of the named databases did not exist. An error has
   45864       ** already been written into the pDestDb handle. All that is left
   45865       ** to do here is free the sqlite3_backup structure.
   45866       */
   45867       sqlite3_free(p);
   45868       p = 0;
   45869     }
   45870   }
   45871   if( p ){
   45872     p->pSrc->nBackup++;
   45873   }
   45874 
   45875   sqlite3_mutex_leave(pDestDb->mutex);
   45876   sqlite3_mutex_leave(pSrcDb->mutex);
   45877   return p;
   45878 }
   45879 
   45880 /*
   45881 ** Argument rc is an SQLite error code. Return true if this error is
   45882 ** considered fatal if encountered during a backup operation. All errors
   45883 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
   45884 */
   45885 static int isFatalError(int rc){
   45886   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
   45887 }
   45888 
   45889 /*
   45890 ** Parameter zSrcData points to a buffer containing the data for
   45891 ** page iSrcPg from the source database. Copy this data into the
   45892 ** destination database.
   45893 */
   45894 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
   45895   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
   45896   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
   45897   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
   45898   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
   45899   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
   45900 
   45901   int rc = SQLITE_OK;
   45902   i64 iOff;
   45903 
   45904   assert( p->bDestLocked );
   45905   assert( !isFatalError(p->rc) );
   45906   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
   45907   assert( zSrcData );
   45908 
   45909   /* Catch the case where the destination is an in-memory database and the
   45910   ** page sizes of the source and destination differ.
   45911   */
   45912   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(sqlite3BtreePager(p->pDest)) ){
   45913     rc = SQLITE_READONLY;
   45914   }
   45915 
   45916   /* This loop runs once for each destination page spanned by the source
   45917   ** page. For each iteration, variable iOff is set to the byte offset
   45918   ** of the destination page.
   45919   */
   45920   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
   45921     DbPage *pDestPg = 0;
   45922     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
   45923     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
   45924     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
   45925      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
   45926     ){
   45927       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
   45928       u8 *zDestData = sqlite3PagerGetData(pDestPg);
   45929       u8 *zOut = &zDestData[iOff%nDestPgsz];
   45930 
   45931       /* Copy the data from the source page into the destination page.
   45932       ** Then clear the Btree layer MemPage.isInit flag. Both this module
   45933       ** and the pager code use this trick (clearing the first byte
   45934       ** of the page 'extra' space to invalidate the Btree layers
   45935       ** cached parse of the page). MemPage.isInit is marked
   45936       ** "MUST BE FIRST" for this purpose.
   45937       */
   45938       memcpy(zOut, zIn, nCopy);
   45939       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
   45940     }
   45941     sqlite3PagerUnref(pDestPg);
   45942   }
   45943 
   45944   return rc;
   45945 }
   45946 
   45947 /*
   45948 ** If pFile is currently larger than iSize bytes, then truncate it to
   45949 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
   45950 ** this function is a no-op.
   45951 **
   45952 ** Return SQLITE_OK if everything is successful, or an SQLite error
   45953 ** code if an error occurs.
   45954 */
   45955 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
   45956   i64 iCurrent;
   45957   int rc = sqlite3OsFileSize(pFile, &iCurrent);
   45958   if( rc==SQLITE_OK && iCurrent>iSize ){
   45959     rc = sqlite3OsTruncate(pFile, iSize);
   45960   }
   45961   return rc;
   45962 }
   45963 
   45964 /*
   45965 ** Register this backup object with the associated source pager for
   45966 ** callbacks when pages are changed or the cache invalidated.
   45967 */
   45968 static void attachBackupObject(sqlite3_backup *p){
   45969   sqlite3_backup **pp;
   45970   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
   45971   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
   45972   p->pNext = *pp;
   45973   *pp = p;
   45974   p->isAttached = 1;
   45975 }
   45976 
   45977 /*
   45978 ** Copy nPage pages from the source b-tree to the destination.
   45979 */
   45980 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
   45981   int rc;
   45982 
   45983   sqlite3_mutex_enter(p->pSrcDb->mutex);
   45984   sqlite3BtreeEnter(p->pSrc);
   45985   if( p->pDestDb ){
   45986     sqlite3_mutex_enter(p->pDestDb->mutex);
   45987   }
   45988 
   45989   rc = p->rc;
   45990   if( !isFatalError(rc) ){
   45991     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
   45992     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
   45993     int ii;                            /* Iterator variable */
   45994     int nSrcPage = -1;                 /* Size of source db in pages */
   45995     int bCloseTrans = 0;               /* True if src db requires unlocking */
   45996 
   45997     /* If the source pager is currently in a write-transaction, return
   45998     ** SQLITE_BUSY immediately.
   45999     */
   46000     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
   46001       rc = SQLITE_BUSY;
   46002     }else{
   46003       rc = SQLITE_OK;
   46004     }
   46005 
   46006     /* Lock the destination database, if it is not locked already. */
   46007     if( SQLITE_OK==rc && p->bDestLocked==0
   46008      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
   46009     ){
   46010       p->bDestLocked = 1;
   46011       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
   46012     }
   46013 
   46014     /* If there is no open read-transaction on the source database, open
   46015     ** one now. If a transaction is opened here, then it will be closed
   46016     ** before this function exits.
   46017     */
   46018     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
   46019       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
   46020       bCloseTrans = 1;
   46021     }
   46022 
   46023     /* Now that there is a read-lock on the source database, query the
   46024     ** source pager for the number of pages in the database.
   46025     */
   46026     if( rc==SQLITE_OK ){
   46027       rc = sqlite3PagerPagecount(pSrcPager, &nSrcPage);
   46028     }
   46029     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
   46030       const Pgno iSrcPg = p->iNext;                 /* Source page number */
   46031       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
   46032         DbPage *pSrcPg;                             /* Source page object */
   46033         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
   46034         if( rc==SQLITE_OK ){
   46035           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
   46036           sqlite3PagerUnref(pSrcPg);
   46037         }
   46038       }
   46039       p->iNext++;
   46040     }
   46041     if( rc==SQLITE_OK ){
   46042       p->nPagecount = nSrcPage;
   46043       p->nRemaining = nSrcPage+1-p->iNext;
   46044       if( p->iNext>(Pgno)nSrcPage ){
   46045         rc = SQLITE_DONE;
   46046       }else if( !p->isAttached ){
   46047         attachBackupObject(p);
   46048       }
   46049     }
   46050 
   46051     /* Update the schema version field in the destination database. This
   46052     ** is to make sure that the schema-version really does change in
   46053     ** the case where the source and destination databases have the
   46054     ** same schema version.
   46055     */
   46056     if( rc==SQLITE_DONE
   46057      && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
   46058     ){
   46059       const int nSrcPagesize = sqlite3BtreeGetPageSize(p->pSrc);
   46060       const int nDestPagesize = sqlite3BtreeGetPageSize(p->pDest);
   46061       int nDestTruncate;
   46062 
   46063       if( p->pDestDb ){
   46064         sqlite3ResetInternalSchema(p->pDestDb, 0);
   46065       }
   46066 
   46067       /* Set nDestTruncate to the final number of pages in the destination
   46068       ** database. The complication here is that the destination page
   46069       ** size may be different to the source page size.
   46070       **
   46071       ** If the source page size is smaller than the destination page size,
   46072       ** round up. In this case the call to sqlite3OsTruncate() below will
   46073       ** fix the size of the file. However it is important to call
   46074       ** sqlite3PagerTruncateImage() here so that any pages in the
   46075       ** destination file that lie beyond the nDestTruncate page mark are
   46076       ** journalled by PagerCommitPhaseOne() before they are destroyed
   46077       ** by the file truncation.
   46078       */
   46079       if( nSrcPagesize<nDestPagesize ){
   46080         int ratio = nDestPagesize/nSrcPagesize;
   46081         nDestTruncate = (nSrcPage+ratio-1)/ratio;
   46082         if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
   46083           nDestTruncate--;
   46084         }
   46085       }else{
   46086         nDestTruncate = nSrcPage * (nSrcPagesize/nDestPagesize);
   46087       }
   46088       sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
   46089 
   46090       if( nSrcPagesize<nDestPagesize ){
   46091         /* If the source page-size is smaller than the destination page-size,
   46092         ** two extra things may need to happen:
   46093         **
   46094         **   * The destination may need to be truncated, and
   46095         **
   46096         **   * Data stored on the pages immediately following the
   46097         **     pending-byte page in the source database may need to be
   46098         **     copied into the destination database.
   46099         */
   46100         const i64 iSize = (i64)nSrcPagesize * (i64)nSrcPage;
   46101         sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
   46102 
   46103         assert( pFile );
   46104         assert( (i64)nDestTruncate*(i64)nDestPagesize >= iSize || (
   46105               nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
   46106            && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+nDestPagesize
   46107         ));
   46108         if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
   46109          && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
   46110          && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
   46111         ){
   46112           i64 iOff;
   46113           i64 iEnd = MIN(PENDING_BYTE + nDestPagesize, iSize);
   46114           for(
   46115             iOff=PENDING_BYTE+nSrcPagesize;
   46116             rc==SQLITE_OK && iOff<iEnd;
   46117             iOff+=nSrcPagesize
   46118           ){
   46119             PgHdr *pSrcPg = 0;
   46120             const Pgno iSrcPg = (Pgno)((iOff/nSrcPagesize)+1);
   46121             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
   46122             if( rc==SQLITE_OK ){
   46123               u8 *zData = sqlite3PagerGetData(pSrcPg);
   46124               rc = sqlite3OsWrite(pFile, zData, nSrcPagesize, iOff);
   46125             }
   46126             sqlite3PagerUnref(pSrcPg);
   46127           }
   46128         }
   46129       }else{
   46130         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
   46131       }
   46132 
   46133       /* Finish committing the transaction to the destination database. */
   46134       if( SQLITE_OK==rc
   46135        && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
   46136       ){
   46137         rc = SQLITE_DONE;
   46138       }
   46139     }
   46140 
   46141     /* If bCloseTrans is true, then this function opened a read transaction
   46142     ** on the source database. Close the read transaction here. There is
   46143     ** no need to check the return values of the btree methods here, as
   46144     ** "committing" a read-only transaction cannot fail.
   46145     */
   46146     if( bCloseTrans ){
   46147       TESTONLY( int rc2 );
   46148       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
   46149       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
   46150       assert( rc2==SQLITE_OK );
   46151     }
   46152 
   46153     p->rc = rc;
   46154   }
   46155   if( p->pDestDb ){
   46156     sqlite3_mutex_leave(p->pDestDb->mutex);
   46157   }
   46158   sqlite3BtreeLeave(p->pSrc);
   46159   sqlite3_mutex_leave(p->pSrcDb->mutex);
   46160   return rc;
   46161 }
   46162 
   46163 /*
   46164 ** Release all resources associated with an sqlite3_backup* handle.
   46165 */
   46166 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
   46167   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
   46168   sqlite3_mutex *mutex;                /* Mutex to protect source database */
   46169   int rc;                              /* Value to return */
   46170 
   46171   /* Enter the mutexes */
   46172   if( p==0 ) return SQLITE_OK;
   46173   sqlite3_mutex_enter(p->pSrcDb->mutex);
   46174   sqlite3BtreeEnter(p->pSrc);
   46175   mutex = p->pSrcDb->mutex;
   46176   if( p->pDestDb ){
   46177     sqlite3_mutex_enter(p->pDestDb->mutex);
   46178   }
   46179 
   46180   /* Detach this backup from the source pager. */
   46181   if( p->pDestDb ){
   46182     p->pSrc->nBackup--;
   46183   }
   46184   if( p->isAttached ){
   46185     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
   46186     while( *pp!=p ){
   46187       pp = &(*pp)->pNext;
   46188     }
   46189     *pp = p->pNext;
   46190   }
   46191 
   46192   /* If a transaction is still open on the Btree, roll it back. */
   46193   sqlite3BtreeRollback(p->pDest);
   46194 
   46195   /* Set the error code of the destination database handle. */
   46196   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
   46197   sqlite3Error(p->pDestDb, rc, 0);
   46198 
   46199   /* Exit the mutexes and free the backup context structure. */
   46200   if( p->pDestDb ){
   46201     sqlite3_mutex_leave(p->pDestDb->mutex);
   46202   }
   46203   sqlite3BtreeLeave(p->pSrc);
   46204   if( p->pDestDb ){
   46205     sqlite3_free(p);
   46206   }
   46207   sqlite3_mutex_leave(mutex);
   46208   return rc;
   46209 }
   46210 
   46211 /*
   46212 ** Return the number of pages still to be backed up as of the most recent
   46213 ** call to sqlite3_backup_step().
   46214 */
   46215 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
   46216   return p->nRemaining;
   46217 }
   46218 
   46219 /*
   46220 ** Return the total number of pages in the source database as of the most
   46221 ** recent call to sqlite3_backup_step().
   46222 */
   46223 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
   46224   return p->nPagecount;
   46225 }
   46226 
   46227 /*
   46228 ** This function is called after the contents of page iPage of the
   46229 ** source database have been modified. If page iPage has already been
   46230 ** copied into the destination database, then the data written to the
   46231 ** destination is now invalidated. The destination copy of iPage needs
   46232 ** to be updated with the new data before the backup operation is
   46233 ** complete.
   46234 **
   46235 ** It is assumed that the mutex associated with the BtShared object
   46236 ** corresponding to the source database is held when this function is
   46237 ** called.
   46238 */
   46239 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
   46240   sqlite3_backup *p;                   /* Iterator variable */
   46241   for(p=pBackup; p; p=p->pNext){
   46242     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
   46243     if( !isFatalError(p->rc) && iPage<p->iNext ){
   46244       /* The backup process p has already copied page iPage. But now it
   46245       ** has been modified by a transaction on the source pager. Copy
   46246       ** the new data into the backup.
   46247       */
   46248       int rc = backupOnePage(p, iPage, aData);
   46249       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
   46250       if( rc!=SQLITE_OK ){
   46251         p->rc = rc;
   46252       }
   46253     }
   46254   }
   46255 }
   46256 
   46257 /*
   46258 ** Restart the backup process. This is called when the pager layer
   46259 ** detects that the database has been modified by an external database
   46260 ** connection. In this case there is no way of knowing which of the
   46261 ** pages that have been copied into the destination database are still
   46262 ** valid and which are not, so the entire process needs to be restarted.
   46263 **
   46264 ** It is assumed that the mutex associated with the BtShared object
   46265 ** corresponding to the source database is held when this function is
   46266 ** called.
   46267 */
   46268 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
   46269   sqlite3_backup *p;                   /* Iterator variable */
   46270   for(p=pBackup; p; p=p->pNext){
   46271     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
   46272     p->iNext = 1;
   46273   }
   46274 }
   46275 
   46276 #ifndef SQLITE_OMIT_VACUUM
   46277 /*
   46278 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
   46279 ** must be active for both files.
   46280 **
   46281 ** The size of file pTo may be reduced by this operation. If anything
   46282 ** goes wrong, the transaction on pTo is rolled back. If successful, the
   46283 ** transaction is committed before returning.
   46284 */
   46285 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
   46286   int rc;
   46287   sqlite3_backup b;
   46288   sqlite3BtreeEnter(pTo);
   46289   sqlite3BtreeEnter(pFrom);
   46290 
   46291   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
   46292   ** to 0. This is used by the implementations of sqlite3_backup_step()
   46293   ** and sqlite3_backup_finish() to detect that they are being called
   46294   ** from this function, not directly by the user.
   46295   */
   46296   memset(&b, 0, sizeof(b));
   46297   b.pSrcDb = pFrom->db;
   46298   b.pSrc = pFrom;
   46299   b.pDest = pTo;
   46300   b.iNext = 1;
   46301 
   46302   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
   46303   ** file. By passing this as the number of pages to copy to
   46304   ** sqlite3_backup_step(), we can guarantee that the copy finishes
   46305   ** within a single call (unless an error occurs). The assert() statement
   46306   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
   46307   ** or an error code.
   46308   */
   46309   sqlite3_backup_step(&b, 0x7FFFFFFF);
   46310   assert( b.rc!=SQLITE_OK );
   46311   rc = sqlite3_backup_finish(&b);
   46312   if( rc==SQLITE_OK ){
   46313     pTo->pBt->pageSizeFixed = 0;
   46314   }
   46315 
   46316   sqlite3BtreeLeave(pFrom);
   46317   sqlite3BtreeLeave(pTo);
   46318   return rc;
   46319 }
   46320 #endif /* SQLITE_OMIT_VACUUM */
   46321 
   46322 /************** End of backup.c **********************************************/
   46323 /************** Begin file vdbemem.c *****************************************/
   46324 /*
   46325 ** 2004 May 26
   46326 **
   46327 ** The author disclaims copyright to this source code.  In place of
   46328 ** a legal notice, here is a blessing:
   46329 **
   46330 **    May you do good and not evil.
   46331 **    May you find forgiveness for yourself and forgive others.
   46332 **    May you share freely, never taking more than you give.
   46333 **
   46334 *************************************************************************
   46335 **
   46336 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
   46337 ** stores a single value in the VDBE.  Mem is an opaque structure visible
   46338 ** only within the VDBE.  Interface routines refer to a Mem using the
   46339 ** name sqlite_value
   46340 */
   46341 
   46342 /*
   46343 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
   46344 ** P if required.
   46345 */
   46346 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
   46347 
   46348 /*
   46349 ** If pMem is an object with a valid string representation, this routine
   46350 ** ensures the internal encoding for the string representation is
   46351 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
   46352 **
   46353 ** If pMem is not a string object, or the encoding of the string
   46354 ** representation is already stored using the requested encoding, then this
   46355 ** routine is a no-op.
   46356 **
   46357 ** SQLITE_OK is returned if the conversion is successful (or not required).
   46358 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
   46359 ** between formats.
   46360 */
   46361 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
   46362   int rc;
   46363   assert( (pMem->flags&MEM_RowSet)==0 );
   46364   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
   46365            || desiredEnc==SQLITE_UTF16BE );
   46366   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
   46367     return SQLITE_OK;
   46368   }
   46369   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   46370 #ifdef SQLITE_OMIT_UTF16
   46371   return SQLITE_ERROR;
   46372 #else
   46373 
   46374   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
   46375   ** then the encoding of the value may not have changed.
   46376   */
   46377   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
   46378   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
   46379   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
   46380   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
   46381   return rc;
   46382 #endif
   46383 }
   46384 
   46385 /*
   46386 ** Make sure pMem->z points to a writable allocation of at least
   46387 ** n bytes.
   46388 **
   46389 ** If the memory cell currently contains string or blob data
   46390 ** and the third argument passed to this function is true, the
   46391 ** current content of the cell is preserved. Otherwise, it may
   46392 ** be discarded.
   46393 **
   46394 ** This function sets the MEM_Dyn flag and clears any xDel callback.
   46395 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
   46396 ** not set, Mem.n is zeroed.
   46397 */
   46398 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
   46399   assert( 1 >=
   46400     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
   46401     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
   46402     ((pMem->flags&MEM_Ephem) ? 1 : 0) +
   46403     ((pMem->flags&MEM_Static) ? 1 : 0)
   46404   );
   46405   assert( (pMem->flags&MEM_RowSet)==0 );
   46406 
   46407   if( n<32 ) n = 32;
   46408   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
   46409     if( preserve && pMem->z==pMem->zMalloc ){
   46410       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
   46411       preserve = 0;
   46412     }else{
   46413       sqlite3DbFree(pMem->db, pMem->zMalloc);
   46414       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
   46415     }
   46416   }
   46417 
   46418   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
   46419     memcpy(pMem->zMalloc, pMem->z, pMem->n);
   46420   }
   46421   if( pMem->flags&MEM_Dyn && pMem->xDel ){
   46422     pMem->xDel((void *)(pMem->z));
   46423   }
   46424 
   46425   pMem->z = pMem->zMalloc;
   46426   if( pMem->z==0 ){
   46427     pMem->flags = MEM_Null;
   46428   }else{
   46429     pMem->flags &= ~(MEM_Ephem|MEM_Static);
   46430   }
   46431   pMem->xDel = 0;
   46432   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
   46433 }
   46434 
   46435 /*
   46436 ** Make the given Mem object MEM_Dyn.  In other words, make it so
   46437 ** that any TEXT or BLOB content is stored in memory obtained from
   46438 ** malloc().  In this way, we know that the memory is safe to be
   46439 ** overwritten or altered.
   46440 **
   46441 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
   46442 */
   46443 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
   46444   int f;
   46445   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   46446   assert( (pMem->flags&MEM_RowSet)==0 );
   46447   expandBlob(pMem);
   46448   f = pMem->flags;
   46449   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
   46450     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
   46451       return SQLITE_NOMEM;
   46452     }
   46453     pMem->z[pMem->n] = 0;
   46454     pMem->z[pMem->n+1] = 0;
   46455     pMem->flags |= MEM_Term;
   46456   }
   46457 
   46458   return SQLITE_OK;
   46459 }
   46460 
   46461 /*
   46462 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
   46463 ** blob stored in dynamically allocated space.
   46464 */
   46465 #ifndef SQLITE_OMIT_INCRBLOB
   46466 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
   46467   if( pMem->flags & MEM_Zero ){
   46468     int nByte;
   46469     assert( pMem->flags&MEM_Blob );
   46470     assert( (pMem->flags&MEM_RowSet)==0 );
   46471     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   46472 
   46473     /* Set nByte to the number of bytes required to store the expanded blob. */
   46474     nByte = pMem->n + pMem->u.nZero;
   46475     if( nByte<=0 ){
   46476       nByte = 1;
   46477     }
   46478     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
   46479       return SQLITE_NOMEM;
   46480     }
   46481 
   46482     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
   46483     pMem->n += pMem->u.nZero;
   46484     pMem->flags &= ~(MEM_Zero|MEM_Term);
   46485   }
   46486   return SQLITE_OK;
   46487 }
   46488 #endif
   46489 
   46490 
   46491 /*
   46492 ** Make sure the given Mem is \u0000 terminated.
   46493 */
   46494 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
   46495   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   46496   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
   46497     return SQLITE_OK;   /* Nothing to do */
   46498   }
   46499   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
   46500     return SQLITE_NOMEM;
   46501   }
   46502   pMem->z[pMem->n] = 0;
   46503   pMem->z[pMem->n+1] = 0;
   46504   pMem->flags |= MEM_Term;
   46505   return SQLITE_OK;
   46506 }
   46507 
   46508 /*
   46509 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
   46510 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
   46511 ** is a no-op.
   46512 **
   46513 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
   46514 **
   46515 ** A MEM_Null value will never be passed to this function. This function is
   46516 ** used for converting values to text for returning to the user (i.e. via
   46517 ** sqlite3_value_text()), or for ensuring that values to be used as btree
   46518 ** keys are strings. In the former case a NULL pointer is returned the
   46519 ** user and the later is an internal programming error.
   46520 */
   46521 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
   46522   int rc = SQLITE_OK;
   46523   int fg = pMem->flags;
   46524   const int nByte = 32;
   46525 
   46526   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   46527   assert( !(fg&MEM_Zero) );
   46528   assert( !(fg&(MEM_Str|MEM_Blob)) );
   46529   assert( fg&(MEM_Int|MEM_Real) );
   46530   assert( (pMem->flags&MEM_RowSet)==0 );
   46531   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   46532 
   46533 
   46534   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
   46535     return SQLITE_NOMEM;
   46536   }
   46537 
   46538   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
   46539   ** string representation of the value. Then, if the required encoding
   46540   ** is UTF-16le or UTF-16be do a translation.
   46541   **
   46542   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
   46543   */
   46544   if( fg & MEM_Int ){
   46545     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
   46546   }else{
   46547     assert( fg & MEM_Real );
   46548     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
   46549   }
   46550   pMem->n = sqlite3Strlen30(pMem->z);
   46551   pMem->enc = SQLITE_UTF8;
   46552   pMem->flags |= MEM_Str|MEM_Term;
   46553   sqlite3VdbeChangeEncoding(pMem, enc);
   46554   return rc;
   46555 }
   46556 
   46557 /*
   46558 ** Memory cell pMem contains the context of an aggregate function.
   46559 ** This routine calls the finalize method for that function.  The
   46560 ** result of the aggregate is stored back into pMem.
   46561 **
   46562 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
   46563 ** otherwise.
   46564 */
   46565 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
   46566   int rc = SQLITE_OK;
   46567   if( ALWAYS(pFunc && pFunc->xFinalize) ){
   46568     sqlite3_context ctx;
   46569     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
   46570     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   46571     memset(&ctx, 0, sizeof(ctx));
   46572     ctx.s.flags = MEM_Null;
   46573     ctx.s.db = pMem->db;
   46574     ctx.pMem = pMem;
   46575     ctx.pFunc = pFunc;
   46576     pFunc->xFinalize(&ctx);
   46577     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
   46578     sqlite3DbFree(pMem->db, pMem->zMalloc);
   46579     memcpy(pMem, &ctx.s, sizeof(ctx.s));
   46580     rc = ctx.isError;
   46581   }
   46582   return rc;
   46583 }
   46584 
   46585 /*
   46586 ** If the memory cell contains a string value that must be freed by
   46587 ** invoking an external callback, free it now. Calling this function
   46588 ** does not free any Mem.zMalloc buffer.
   46589 */
   46590 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
   46591   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
   46592   testcase( p->flags & MEM_Agg );
   46593   testcase( p->flags & MEM_Dyn );
   46594   testcase( p->flags & MEM_RowSet );
   46595   testcase( p->flags & MEM_Frame );
   46596   if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
   46597     if( p->flags&MEM_Agg ){
   46598       sqlite3VdbeMemFinalize(p, p->u.pDef);
   46599       assert( (p->flags & MEM_Agg)==0 );
   46600       sqlite3VdbeMemRelease(p);
   46601     }else if( p->flags&MEM_Dyn && p->xDel ){
   46602       assert( (p->flags&MEM_RowSet)==0 );
   46603       p->xDel((void *)p->z);
   46604       p->xDel = 0;
   46605     }else if( p->flags&MEM_RowSet ){
   46606       sqlite3RowSetClear(p->u.pRowSet);
   46607     }else if( p->flags&MEM_Frame ){
   46608       sqlite3VdbeMemSetNull(p);
   46609     }
   46610   }
   46611 }
   46612 
   46613 /*
   46614 ** Release any memory held by the Mem. This may leave the Mem in an
   46615 ** inconsistent state, for example with (Mem.z==0) and
   46616 ** (Mem.type==SQLITE_TEXT).
   46617 */
   46618 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
   46619   sqlite3VdbeMemReleaseExternal(p);
   46620   sqlite3DbFree(p->db, p->zMalloc);
   46621   p->z = 0;
   46622   p->zMalloc = 0;
   46623   p->xDel = 0;
   46624 }
   46625 
   46626 /*
   46627 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
   46628 ** If the double is too large, return 0x8000000000000000.
   46629 **
   46630 ** Most systems appear to do this simply by assigning
   46631 ** variables and without the extra range tests.  But
   46632 ** there are reports that windows throws an expection
   46633 ** if the floating point value is out of range. (See ticket #2880.)
   46634 ** Because we do not completely understand the problem, we will
   46635 ** take the conservative approach and always do range tests
   46636 ** before attempting the conversion.
   46637 */
   46638 static i64 doubleToInt64(double r){
   46639   /*
   46640   ** Many compilers we encounter do not define constants for the
   46641   ** minimum and maximum 64-bit integers, or they define them
   46642   ** inconsistently.  And many do not understand the "LL" notation.
   46643   ** So we define our own static constants here using nothing
   46644   ** larger than a 32-bit integer constant.
   46645   */
   46646   static const i64 maxInt = LARGEST_INT64;
   46647   static const i64 minInt = SMALLEST_INT64;
   46648 
   46649   if( r<(double)minInt ){
   46650     return minInt;
   46651   }else if( r>(double)maxInt ){
   46652     /* minInt is correct here - not maxInt.  It turns out that assigning
   46653     ** a very large positive number to an integer results in a very large
   46654     ** negative integer.  This makes no sense, but it is what x86 hardware
   46655     ** does so for compatibility we will do the same in software. */
   46656     return minInt;
   46657   }else{
   46658     return (i64)r;
   46659   }
   46660 }
   46661 
   46662 /*
   46663 ** Return some kind of integer value which is the best we can do
   46664 ** at representing the value that *pMem describes as an integer.
   46665 ** If pMem is an integer, then the value is exact.  If pMem is
   46666 ** a floating-point then the value returned is the integer part.
   46667 ** If pMem is a string or blob, then we make an attempt to convert
   46668 ** it into a integer and return that.  If pMem represents an
   46669 ** an SQL-NULL value, return 0.
   46670 **
   46671 ** If pMem represents a string value, its encoding might be changed.
   46672 */
   46673 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
   46674   int flags;
   46675   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   46676   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   46677   flags = pMem->flags;
   46678   if( flags & MEM_Int ){
   46679     return pMem->u.i;
   46680   }else if( flags & MEM_Real ){
   46681     return doubleToInt64(pMem->r);
   46682   }else if( flags & (MEM_Str|MEM_Blob) ){
   46683     i64 value;
   46684     pMem->flags |= MEM_Str;
   46685     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
   46686        || sqlite3VdbeMemNulTerminate(pMem) ){
   46687       return 0;
   46688     }
   46689     assert( pMem->z );
   46690     sqlite3Atoi64(pMem->z, &value);
   46691     return value;
   46692   }else{
   46693     return 0;
   46694   }
   46695 }
   46696 
   46697 /*
   46698 ** Return the best representation of pMem that we can get into a
   46699 ** double.  If pMem is already a double or an integer, return its
   46700 ** value.  If it is a string or blob, try to convert it to a double.
   46701 ** If it is a NULL, return 0.0.
   46702 */
   46703 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
   46704   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   46705   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   46706   if( pMem->flags & MEM_Real ){
   46707     return pMem->r;
   46708   }else if( pMem->flags & MEM_Int ){
   46709     return (double)pMem->u.i;
   46710   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
   46711     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   46712     double val = (double)0;
   46713     pMem->flags |= MEM_Str;
   46714     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
   46715        || sqlite3VdbeMemNulTerminate(pMem) ){
   46716       /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   46717       return (double)0;
   46718     }
   46719     assert( pMem->z );
   46720     sqlite3AtoF(pMem->z, &val);
   46721     return val;
   46722   }else{
   46723     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   46724     return (double)0;
   46725   }
   46726 }
   46727 
   46728 /*
   46729 ** The MEM structure is already a MEM_Real.  Try to also make it a
   46730 ** MEM_Int if we can.
   46731 */
   46732 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
   46733   assert( pMem->flags & MEM_Real );
   46734   assert( (pMem->flags & MEM_RowSet)==0 );
   46735   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   46736   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   46737 
   46738   pMem->u.i = doubleToInt64(pMem->r);
   46739 
   46740   /* Only mark the value as an integer if
   46741   **
   46742   **    (1) the round-trip conversion real->int->real is a no-op, and
   46743   **    (2) The integer is neither the largest nor the smallest
   46744   **        possible integer (ticket #3922)
   46745   **
   46746   ** The second and third terms in the following conditional enforces
   46747   ** the second condition under the assumption that addition overflow causes
   46748   ** values to wrap around.  On x86 hardware, the third term is always
   46749   ** true and could be omitted.  But we leave it in because other
   46750   ** architectures might behave differently.
   46751   */
   46752   if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
   46753       && ALWAYS(pMem->u.i<LARGEST_INT64) ){
   46754     pMem->flags |= MEM_Int;
   46755   }
   46756 }
   46757 
   46758 /*
   46759 ** Convert pMem to type integer.  Invalidate any prior representations.
   46760 */
   46761 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
   46762   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   46763   assert( (pMem->flags & MEM_RowSet)==0 );
   46764   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   46765 
   46766   pMem->u.i = sqlite3VdbeIntValue(pMem);
   46767   MemSetTypeFlag(pMem, MEM_Int);
   46768   return SQLITE_OK;
   46769 }
   46770 
   46771 /*
   46772 ** Convert pMem so that it is of type MEM_Real.
   46773 ** Invalidate any prior representations.
   46774 */
   46775 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
   46776   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   46777   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   46778 
   46779   pMem->r = sqlite3VdbeRealValue(pMem);
   46780   MemSetTypeFlag(pMem, MEM_Real);
   46781   return SQLITE_OK;
   46782 }
   46783 
   46784 /*
   46785 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
   46786 ** Invalidate any prior representations.
   46787 */
   46788 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
   46789   double r1, r2;
   46790   i64 i;
   46791   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
   46792   assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
   46793   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   46794   r1 = sqlite3VdbeRealValue(pMem);
   46795   i = doubleToInt64(r1);
   46796   r2 = (double)i;
   46797   if( r1==r2 ){
   46798     sqlite3VdbeMemIntegerify(pMem);
   46799   }else{
   46800     pMem->r = r1;
   46801     MemSetTypeFlag(pMem, MEM_Real);
   46802   }
   46803   return SQLITE_OK;
   46804 }
   46805 
   46806 /*
   46807 ** Delete any previous value and set the value stored in *pMem to NULL.
   46808 */
   46809 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
   46810   if( pMem->flags & MEM_Frame ){
   46811     sqlite3VdbeFrameDelete(pMem->u.pFrame);
   46812   }
   46813   if( pMem->flags & MEM_RowSet ){
   46814     sqlite3RowSetClear(pMem->u.pRowSet);
   46815   }
   46816   MemSetTypeFlag(pMem, MEM_Null);
   46817   pMem->type = SQLITE_NULL;
   46818 }
   46819 
   46820 /*
   46821 ** Delete any previous value and set the value to be a BLOB of length
   46822 ** n containing all zeros.
   46823 */
   46824 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
   46825   sqlite3VdbeMemRelease(pMem);
   46826   pMem->flags = MEM_Blob|MEM_Zero;
   46827   pMem->type = SQLITE_BLOB;
   46828   pMem->n = 0;
   46829   if( n<0 ) n = 0;
   46830   pMem->u.nZero = n;
   46831   pMem->enc = SQLITE_UTF8;
   46832 
   46833 #ifdef SQLITE_OMIT_INCRBLOB
   46834   sqlite3VdbeMemGrow(pMem, n, 0);
   46835   if( pMem->z ){
   46836     pMem->n = n;
   46837     memset(pMem->z, 0, n);
   46838   }
   46839 #endif
   46840 }
   46841 
   46842 /*
   46843 ** Delete any previous value and set the value stored in *pMem to val,
   46844 ** manifest type INTEGER.
   46845 */
   46846 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
   46847   sqlite3VdbeMemRelease(pMem);
   46848   pMem->u.i = val;
   46849   pMem->flags = MEM_Int;
   46850   pMem->type = SQLITE_INTEGER;
   46851 }
   46852 
   46853 /*
   46854 ** Delete any previous value and set the value stored in *pMem to val,
   46855 ** manifest type REAL.
   46856 */
   46857 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
   46858   if( sqlite3IsNaN(val) ){
   46859     sqlite3VdbeMemSetNull(pMem);
   46860   }else{
   46861     sqlite3VdbeMemRelease(pMem);
   46862     pMem->r = val;
   46863     pMem->flags = MEM_Real;
   46864     pMem->type = SQLITE_FLOAT;
   46865   }
   46866 }
   46867 
   46868 /*
   46869 ** Delete any previous value and set the value of pMem to be an
   46870 ** empty boolean index.
   46871 */
   46872 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
   46873   sqlite3 *db = pMem->db;
   46874   assert( db!=0 );
   46875   assert( (pMem->flags & MEM_RowSet)==0 );
   46876   sqlite3VdbeMemRelease(pMem);
   46877   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
   46878   if( db->mallocFailed ){
   46879     pMem->flags = MEM_Null;
   46880   }else{
   46881     assert( pMem->zMalloc );
   46882     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
   46883                                        sqlite3DbMallocSize(db, pMem->zMalloc));
   46884     assert( pMem->u.pRowSet!=0 );
   46885     pMem->flags = MEM_RowSet;
   46886   }
   46887 }
   46888 
   46889 /*
   46890 ** Return true if the Mem object contains a TEXT or BLOB that is
   46891 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
   46892 */
   46893 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
   46894   assert( p->db!=0 );
   46895   if( p->flags & (MEM_Str|MEM_Blob) ){
   46896     int n = p->n;
   46897     if( p->flags & MEM_Zero ){
   46898       n += p->u.nZero;
   46899     }
   46900     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
   46901   }
   46902   return 0;
   46903 }
   46904 
   46905 /*
   46906 ** Size of struct Mem not including the Mem.zMalloc member.
   46907 */
   46908 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
   46909 
   46910 /*
   46911 ** Make an shallow copy of pFrom into pTo.  Prior contents of
   46912 ** pTo are freed.  The pFrom->z field is not duplicated.  If
   46913 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
   46914 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
   46915 */
   46916 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
   46917   assert( (pFrom->flags & MEM_RowSet)==0 );
   46918   sqlite3VdbeMemReleaseExternal(pTo);
   46919   memcpy(pTo, pFrom, MEMCELLSIZE);
   46920   pTo->xDel = 0;
   46921   if( (pFrom->flags&MEM_Dyn)!=0 || pFrom->z==pFrom->zMalloc ){
   46922     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
   46923     assert( srcType==MEM_Ephem || srcType==MEM_Static );
   46924     pTo->flags |= srcType;
   46925   }
   46926 }
   46927 
   46928 /*
   46929 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
   46930 ** freed before the copy is made.
   46931 */
   46932 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
   46933   int rc = SQLITE_OK;
   46934 
   46935   assert( (pFrom->flags & MEM_RowSet)==0 );
   46936   sqlite3VdbeMemReleaseExternal(pTo);
   46937   memcpy(pTo, pFrom, MEMCELLSIZE);
   46938   pTo->flags &= ~MEM_Dyn;
   46939 
   46940   if( pTo->flags&(MEM_Str|MEM_Blob) ){
   46941     if( 0==(pFrom->flags&MEM_Static) ){
   46942       pTo->flags |= MEM_Ephem;
   46943       rc = sqlite3VdbeMemMakeWriteable(pTo);
   46944     }
   46945   }
   46946 
   46947   return rc;
   46948 }
   46949 
   46950 /*
   46951 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
   46952 ** freed. If pFrom contains ephemeral data, a copy is made.
   46953 **
   46954 ** pFrom contains an SQL NULL when this routine returns.
   46955 */
   46956 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
   46957   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
   46958   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
   46959   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
   46960 
   46961   sqlite3VdbeMemRelease(pTo);
   46962   memcpy(pTo, pFrom, sizeof(Mem));
   46963   pFrom->flags = MEM_Null;
   46964   pFrom->xDel = 0;
   46965   pFrom->zMalloc = 0;
   46966 }
   46967 
   46968 /*
   46969 ** Change the value of a Mem to be a string or a BLOB.
   46970 **
   46971 ** The memory management strategy depends on the value of the xDel
   46972 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
   46973 ** string is copied into a (possibly existing) buffer managed by the
   46974 ** Mem structure. Otherwise, any existing buffer is freed and the
   46975 ** pointer copied.
   46976 **
   46977 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
   46978 ** size limit) then no memory allocation occurs.  If the string can be
   46979 ** stored without allocating memory, then it is.  If a memory allocation
   46980 ** is required to store the string, then value of pMem is unchanged.  In
   46981 ** either case, SQLITE_TOOBIG is returned.
   46982 */
   46983 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
   46984   Mem *pMem,          /* Memory cell to set to string value */
   46985   const char *z,      /* String pointer */
   46986   int n,              /* Bytes in string, or negative */
   46987   u8 enc,             /* Encoding of z.  0 for BLOBs */
   46988   void (*xDel)(void*) /* Destructor function */
   46989 ){
   46990   int nByte = n;      /* New value for pMem->n */
   46991   int iLimit;         /* Maximum allowed string or blob size */
   46992   u16 flags = 0;      /* New value for pMem->flags */
   46993 
   46994   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   46995   assert( (pMem->flags & MEM_RowSet)==0 );
   46996 
   46997   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
   46998   if( !z ){
   46999     sqlite3VdbeMemSetNull(pMem);
   47000     return SQLITE_OK;
   47001   }
   47002 
   47003   if( pMem->db ){
   47004     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
   47005   }else{
   47006     iLimit = SQLITE_MAX_LENGTH;
   47007   }
   47008   flags = (enc==0?MEM_Blob:MEM_Str);
   47009   if( nByte<0 ){
   47010     assert( enc!=0 );
   47011     if( enc==SQLITE_UTF8 ){
   47012       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
   47013     }else{
   47014       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
   47015     }
   47016     flags |= MEM_Term;
   47017   }
   47018 
   47019   /* The following block sets the new values of Mem.z and Mem.xDel. It
   47020   ** also sets a flag in local variable "flags" to indicate the memory
   47021   ** management (one of MEM_Dyn or MEM_Static).
   47022   */
   47023   if( xDel==SQLITE_TRANSIENT ){
   47024     int nAlloc = nByte;
   47025     if( flags&MEM_Term ){
   47026       nAlloc += (enc==SQLITE_UTF8?1:2);
   47027     }
   47028     if( nByte>iLimit ){
   47029       return SQLITE_TOOBIG;
   47030     }
   47031     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
   47032       return SQLITE_NOMEM;
   47033     }
   47034     memcpy(pMem->z, z, nAlloc);
   47035   }else if( xDel==SQLITE_DYNAMIC ){
   47036     sqlite3VdbeMemRelease(pMem);
   47037     pMem->zMalloc = pMem->z = (char *)z;
   47038     pMem->xDel = 0;
   47039   }else{
   47040     sqlite3VdbeMemRelease(pMem);
   47041     pMem->z = (char *)z;
   47042     pMem->xDel = xDel;
   47043     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
   47044   }
   47045 
   47046   pMem->n = nByte;
   47047   pMem->flags = flags;
   47048   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
   47049   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
   47050 
   47051 #ifndef SQLITE_OMIT_UTF16
   47052   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
   47053     return SQLITE_NOMEM;
   47054   }
   47055 #endif
   47056 
   47057   if( nByte>iLimit ){
   47058     return SQLITE_TOOBIG;
   47059   }
   47060 
   47061   return SQLITE_OK;
   47062 }
   47063 
   47064 /*
   47065 ** Compare the values contained by the two memory cells, returning
   47066 ** negative, zero or positive if pMem1 is less than, equal to, or greater
   47067 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
   47068 ** and reals) sorted numerically, followed by text ordered by the collating
   47069 ** sequence pColl and finally blob's ordered by memcmp().
   47070 **
   47071 ** Two NULL values are considered equal by this function.
   47072 */
   47073 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
   47074   int rc;
   47075   int f1, f2;
   47076   int combined_flags;
   47077 
   47078   f1 = pMem1->flags;
   47079   f2 = pMem2->flags;
   47080   combined_flags = f1|f2;
   47081   assert( (combined_flags & MEM_RowSet)==0 );
   47082 
   47083   /* If one value is NULL, it is less than the other. If both values
   47084   ** are NULL, return 0.
   47085   */
   47086   if( combined_flags&MEM_Null ){
   47087     return (f2&MEM_Null) - (f1&MEM_Null);
   47088   }
   47089 
   47090   /* If one value is a number and the other is not, the number is less.
   47091   ** If both are numbers, compare as reals if one is a real, or as integers
   47092   ** if both values are integers.
   47093   */
   47094   if( combined_flags&(MEM_Int|MEM_Real) ){
   47095     if( !(f1&(MEM_Int|MEM_Real)) ){
   47096       return 1;
   47097     }
   47098     if( !(f2&(MEM_Int|MEM_Real)) ){
   47099       return -1;
   47100     }
   47101     if( (f1 & f2 & MEM_Int)==0 ){
   47102       double r1, r2;
   47103       if( (f1&MEM_Real)==0 ){
   47104         r1 = (double)pMem1->u.i;
   47105       }else{
   47106         r1 = pMem1->r;
   47107       }
   47108       if( (f2&MEM_Real)==0 ){
   47109         r2 = (double)pMem2->u.i;
   47110       }else{
   47111         r2 = pMem2->r;
   47112       }
   47113       if( r1<r2 ) return -1;
   47114       if( r1>r2 ) return 1;
   47115       return 0;
   47116     }else{
   47117       assert( f1&MEM_Int );
   47118       assert( f2&MEM_Int );
   47119       if( pMem1->u.i < pMem2->u.i ) return -1;
   47120       if( pMem1->u.i > pMem2->u.i ) return 1;
   47121       return 0;
   47122     }
   47123   }
   47124 
   47125   /* If one value is a string and the other is a blob, the string is less.
   47126   ** If both are strings, compare using the collating functions.
   47127   */
   47128   if( combined_flags&MEM_Str ){
   47129     if( (f1 & MEM_Str)==0 ){
   47130       return 1;
   47131     }
   47132     if( (f2 & MEM_Str)==0 ){
   47133       return -1;
   47134     }
   47135 
   47136     assert( pMem1->enc==pMem2->enc );
   47137     assert( pMem1->enc==SQLITE_UTF8 ||
   47138             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
   47139 
   47140     /* The collation sequence must be defined at this point, even if
   47141     ** the user deletes the collation sequence after the vdbe program is
   47142     ** compiled (this was not always the case).
   47143     */
   47144     assert( !pColl || pColl->xCmp );
   47145 
   47146     if( pColl ){
   47147       if( pMem1->enc==pColl->enc ){
   47148         /* The strings are already in the correct encoding.  Call the
   47149         ** comparison function directly */
   47150         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
   47151       }else{
   47152         const void *v1, *v2;
   47153         int n1, n2;
   47154         Mem c1;
   47155         Mem c2;
   47156         memset(&c1, 0, sizeof(c1));
   47157         memset(&c2, 0, sizeof(c2));
   47158         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
   47159         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
   47160         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
   47161         n1 = v1==0 ? 0 : c1.n;
   47162         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
   47163         n2 = v2==0 ? 0 : c2.n;
   47164         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
   47165         sqlite3VdbeMemRelease(&c1);
   47166         sqlite3VdbeMemRelease(&c2);
   47167         return rc;
   47168       }
   47169     }
   47170     /* If a NULL pointer was passed as the collate function, fall through
   47171     ** to the blob case and use memcmp().  */
   47172   }
   47173 
   47174   /* Both values must be blobs.  Compare using memcmp().  */
   47175   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
   47176   if( rc==0 ){
   47177     rc = pMem1->n - pMem2->n;
   47178   }
   47179   return rc;
   47180 }
   47181 
   47182 /*
   47183 ** Move data out of a btree key or data field and into a Mem structure.
   47184 ** The data or key is taken from the entry that pCur is currently pointing
   47185 ** to.  offset and amt determine what portion of the data or key to retrieve.
   47186 ** key is true to get the key or false to get data.  The result is written
   47187 ** into the pMem element.
   47188 **
   47189 ** The pMem structure is assumed to be uninitialized.  Any prior content
   47190 ** is overwritten without being freed.
   47191 **
   47192 ** If this routine fails for any reason (malloc returns NULL or unable
   47193 ** to read from the disk) then the pMem is left in an inconsistent state.
   47194 */
   47195 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
   47196   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
   47197   int offset,       /* Offset from the start of data to return bytes from. */
   47198   int amt,          /* Number of bytes to return. */
   47199   int key,          /* If true, retrieve from the btree key, not data. */
   47200   Mem *pMem         /* OUT: Return data in this Mem structure. */
   47201 ){
   47202   char *zData;        /* Data from the btree layer */
   47203   int available = 0;  /* Number of bytes available on the local btree page */
   47204   int rc = SQLITE_OK; /* Return code */
   47205 
   47206   assert( sqlite3BtreeCursorIsValid(pCur) );
   47207 
   47208   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
   47209   ** that both the BtShared and database handle mutexes are held. */
   47210   assert( (pMem->flags & MEM_RowSet)==0 );
   47211   if( key ){
   47212     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
   47213   }else{
   47214     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
   47215   }
   47216   assert( zData!=0 );
   47217 
   47218   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
   47219     sqlite3VdbeMemRelease(pMem);
   47220     pMem->z = &zData[offset];
   47221     pMem->flags = MEM_Blob|MEM_Ephem;
   47222   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
   47223     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
   47224     pMem->enc = 0;
   47225     pMem->type = SQLITE_BLOB;
   47226     if( key ){
   47227       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
   47228     }else{
   47229       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
   47230     }
   47231     pMem->z[amt] = 0;
   47232     pMem->z[amt+1] = 0;
   47233     if( rc!=SQLITE_OK ){
   47234       sqlite3VdbeMemRelease(pMem);
   47235     }
   47236   }
   47237   pMem->n = amt;
   47238 
   47239   return rc;
   47240 }
   47241 
   47242 /* This function is only available internally, it is not part of the
   47243 ** external API. It works in a similar way to sqlite3_value_text(),
   47244 ** except the data returned is in the encoding specified by the second
   47245 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
   47246 ** SQLITE_UTF8.
   47247 **
   47248 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
   47249 ** If that is the case, then the result must be aligned on an even byte
   47250 ** boundary.
   47251 */
   47252 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
   47253   if( !pVal ) return 0;
   47254 
   47255   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
   47256   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
   47257   assert( (pVal->flags & MEM_RowSet)==0 );
   47258 
   47259   if( pVal->flags&MEM_Null ){
   47260     return 0;
   47261   }
   47262   assert( (MEM_Blob>>3) == MEM_Str );
   47263   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
   47264   expandBlob(pVal);
   47265   if( pVal->flags&MEM_Str ){
   47266     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
   47267     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
   47268       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
   47269       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
   47270         return 0;
   47271       }
   47272     }
   47273     sqlite3VdbeMemNulTerminate(pVal);
   47274   }else{
   47275     assert( (pVal->flags&MEM_Blob)==0 );
   47276     sqlite3VdbeMemStringify(pVal, enc);
   47277     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
   47278   }
   47279   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
   47280               || pVal->db->mallocFailed );
   47281   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
   47282     return pVal->z;
   47283   }else{
   47284     return 0;
   47285   }
   47286 }
   47287 
   47288 /*
   47289 ** Create a new sqlite3_value object.
   47290 */
   47291 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
   47292   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
   47293   if( p ){
   47294     p->flags = MEM_Null;
   47295     p->type = SQLITE_NULL;
   47296     p->db = db;
   47297   }
   47298   return p;
   47299 }
   47300 
   47301 /*
   47302 ** Create a new sqlite3_value object, containing the value of pExpr.
   47303 **
   47304 ** This only works for very simple expressions that consist of one constant
   47305 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
   47306 ** be converted directly into a value, then the value is allocated and
   47307 ** a pointer written to *ppVal. The caller is responsible for deallocating
   47308 ** the value by passing it to sqlite3ValueFree() later on. If the expression
   47309 ** cannot be converted to a value, then *ppVal is set to NULL.
   47310 */
   47311 SQLITE_PRIVATE int sqlite3ValueFromExpr(
   47312   sqlite3 *db,              /* The database connection */
   47313   Expr *pExpr,              /* The expression to evaluate */
   47314   u8 enc,                   /* Encoding to use */
   47315   u8 affinity,              /* Affinity to use */
   47316   sqlite3_value **ppVal     /* Write the new value here */
   47317 ){
   47318   int op;
   47319   char *zVal = 0;
   47320   sqlite3_value *pVal = 0;
   47321 
   47322   if( !pExpr ){
   47323     *ppVal = 0;
   47324     return SQLITE_OK;
   47325   }
   47326   op = pExpr->op;
   47327   if( op==TK_REGISTER ){
   47328     op = pExpr->op2;  /* This only happens with SQLITE_ENABLE_STAT2 */
   47329   }
   47330 
   47331   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
   47332     pVal = sqlite3ValueNew(db);
   47333     if( pVal==0 ) goto no_mem;
   47334     if( ExprHasProperty(pExpr, EP_IntValue) ){
   47335       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue);
   47336     }else{
   47337       zVal = sqlite3DbStrDup(db, pExpr->u.zToken);
   47338       if( zVal==0 ) goto no_mem;
   47339       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
   47340       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
   47341     }
   47342     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
   47343       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
   47344     }else{
   47345       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
   47346     }
   47347     if( enc!=SQLITE_UTF8 ){
   47348       sqlite3VdbeChangeEncoding(pVal, enc);
   47349     }
   47350   }else if( op==TK_UMINUS ) {
   47351     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
   47352       pVal->u.i = -1 * pVal->u.i;
   47353       /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
   47354       pVal->r = (double)-1 * pVal->r;
   47355     }
   47356   }
   47357 #ifndef SQLITE_OMIT_BLOB_LITERAL
   47358   else if( op==TK_BLOB ){
   47359     int nVal;
   47360     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
   47361     assert( pExpr->u.zToken[1]=='\'' );
   47362     pVal = sqlite3ValueNew(db);
   47363     if( !pVal ) goto no_mem;
   47364     zVal = &pExpr->u.zToken[2];
   47365     nVal = sqlite3Strlen30(zVal)-1;
   47366     assert( zVal[nVal]=='\'' );
   47367     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
   47368                          0, SQLITE_DYNAMIC);
   47369   }
   47370 #endif
   47371 
   47372   if( pVal ){
   47373     sqlite3VdbeMemStoreType(pVal);
   47374   }
   47375   *ppVal = pVal;
   47376   return SQLITE_OK;
   47377 
   47378 no_mem:
   47379   db->mallocFailed = 1;
   47380   sqlite3DbFree(db, zVal);
   47381   sqlite3ValueFree(pVal);
   47382   *ppVal = 0;
   47383   return SQLITE_NOMEM;
   47384 }
   47385 
   47386 /*
   47387 ** Change the string value of an sqlite3_value object
   47388 */
   47389 SQLITE_PRIVATE void sqlite3ValueSetStr(
   47390   sqlite3_value *v,     /* Value to be set */
   47391   int n,                /* Length of string z */
   47392   const void *z,        /* Text of the new string */
   47393   u8 enc,               /* Encoding to use */
   47394   void (*xDel)(void*)   /* Destructor for the string */
   47395 ){
   47396   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
   47397 }
   47398 
   47399 /*
   47400 ** Free an sqlite3_value object
   47401 */
   47402 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
   47403   if( !v ) return;
   47404   sqlite3VdbeMemRelease((Mem *)v);
   47405   sqlite3DbFree(((Mem*)v)->db, v);
   47406 }
   47407 
   47408 /*
   47409 ** Return the number of bytes in the sqlite3_value object assuming
   47410 ** that it uses the encoding "enc"
   47411 */
   47412 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
   47413   Mem *p = (Mem*)pVal;
   47414   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
   47415     if( p->flags & MEM_Zero ){
   47416       return p->n + p->u.nZero;
   47417     }else{
   47418       return p->n;
   47419     }
   47420   }
   47421   return 0;
   47422 }
   47423 
   47424 /************** End of vdbemem.c *********************************************/
   47425 /************** Begin file vdbeaux.c *****************************************/
   47426 /*
   47427 ** 2003 September 6
   47428 **
   47429 ** The author disclaims copyright to this source code.  In place of
   47430 ** a legal notice, here is a blessing:
   47431 **
   47432 **    May you do good and not evil.
   47433 **    May you find forgiveness for yourself and forgive others.
   47434 **    May you share freely, never taking more than you give.
   47435 **
   47436 *************************************************************************
   47437 ** This file contains code used for creating, destroying, and populating
   47438 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
   47439 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
   47440 ** But that file was getting too big so this subroutines were split out.
   47441 */
   47442 
   47443 
   47444 
   47445 /*
   47446 ** When debugging the code generator in a symbolic debugger, one can
   47447 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
   47448 ** as they are added to the instruction stream.
   47449 */
   47450 #ifdef SQLITE_DEBUG
   47451 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
   47452 #endif
   47453 
   47454 
   47455 /*
   47456 ** Create a new virtual database engine.
   47457 */
   47458 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
   47459   Vdbe *p;
   47460   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
   47461   if( p==0 ) return 0;
   47462   p->db = db;
   47463   if( db->pVdbe ){
   47464     db->pVdbe->pPrev = p;
   47465   }
   47466   p->pNext = db->pVdbe;
   47467   p->pPrev = 0;
   47468   db->pVdbe = p;
   47469   p->magic = VDBE_MAGIC_INIT;
   47470   return p;
   47471 }
   47472 
   47473 /*
   47474 ** Remember the SQL string for a prepared statement.
   47475 */
   47476 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
   47477   assert( isPrepareV2==1 || isPrepareV2==0 );
   47478   if( p==0 ) return;
   47479 #ifdef SQLITE_OMIT_TRACE
   47480   if( !isPrepareV2 ) return;
   47481 #endif
   47482   assert( p->zSql==0 );
   47483   p->zSql = sqlite3DbStrNDup(p->db, z, n);
   47484   p->isPrepareV2 = (u8)isPrepareV2;
   47485 }
   47486 
   47487 /*
   47488 ** Return the SQL associated with a prepared statement
   47489 */
   47490 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
   47491   Vdbe *p = (Vdbe *)pStmt;
   47492   return (p->isPrepareV2 ? p->zSql : 0);
   47493 }
   47494 
   47495 /*
   47496 ** Swap all content between two VDBE structures.
   47497 */
   47498 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
   47499   Vdbe tmp, *pTmp;
   47500   char *zTmp;
   47501   tmp = *pA;
   47502   *pA = *pB;
   47503   *pB = tmp;
   47504   pTmp = pA->pNext;
   47505   pA->pNext = pB->pNext;
   47506   pB->pNext = pTmp;
   47507   pTmp = pA->pPrev;
   47508   pA->pPrev = pB->pPrev;
   47509   pB->pPrev = pTmp;
   47510   zTmp = pA->zSql;
   47511   pA->zSql = pB->zSql;
   47512   pB->zSql = zTmp;
   47513   pB->isPrepareV2 = pA->isPrepareV2;
   47514 }
   47515 
   47516 #ifdef SQLITE_DEBUG
   47517 /*
   47518 ** Turn tracing on or off
   47519 */
   47520 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
   47521   p->trace = trace;
   47522 }
   47523 #endif
   47524 
   47525 /*
   47526 ** Resize the Vdbe.aOp array so that it is at least one op larger than
   47527 ** it was.
   47528 **
   47529 ** If an out-of-memory error occurs while resizing the array, return
   47530 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
   47531 ** unchanged (this is so that any opcodes already allocated can be
   47532 ** correctly deallocated along with the rest of the Vdbe).
   47533 */
   47534 static int growOpArray(Vdbe *p){
   47535   VdbeOp *pNew;
   47536   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
   47537   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
   47538   if( pNew ){
   47539     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
   47540     p->aOp = pNew;
   47541   }
   47542   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
   47543 }
   47544 
   47545 /*
   47546 ** Add a new instruction to the list of instructions current in the
   47547 ** VDBE.  Return the address of the new instruction.
   47548 **
   47549 ** Parameters:
   47550 **
   47551 **    p               Pointer to the VDBE
   47552 **
   47553 **    op              The opcode for this instruction
   47554 **
   47555 **    p1, p2, p3      Operands
   47556 **
   47557 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
   47558 ** the sqlite3VdbeChangeP4() function to change the value of the P4
   47559 ** operand.
   47560 */
   47561 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
   47562   int i;
   47563   VdbeOp *pOp;
   47564 
   47565   i = p->nOp;
   47566   assert( p->magic==VDBE_MAGIC_INIT );
   47567   assert( op>0 && op<0xff );
   47568   if( p->nOpAlloc<=i ){
   47569     if( growOpArray(p) ){
   47570       return 1;
   47571     }
   47572   }
   47573   p->nOp++;
   47574   pOp = &p->aOp[i];
   47575   pOp->opcode = (u8)op;
   47576   pOp->p5 = 0;
   47577   pOp->p1 = p1;
   47578   pOp->p2 = p2;
   47579   pOp->p3 = p3;
   47580   pOp->p4.p = 0;
   47581   pOp->p4type = P4_NOTUSED;
   47582   p->expired = 0;
   47583 #ifdef SQLITE_DEBUG
   47584   pOp->zComment = 0;
   47585   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
   47586 #endif
   47587 #ifdef VDBE_PROFILE
   47588   pOp->cycles = 0;
   47589   pOp->cnt = 0;
   47590 #endif
   47591   return i;
   47592 }
   47593 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
   47594   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
   47595 }
   47596 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
   47597   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
   47598 }
   47599 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
   47600   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
   47601 }
   47602 
   47603 
   47604 /*
   47605 ** Add an opcode that includes the p4 value as a pointer.
   47606 */
   47607 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
   47608   Vdbe *p,            /* Add the opcode to this VM */
   47609   int op,             /* The new opcode */
   47610   int p1,             /* The P1 operand */
   47611   int p2,             /* The P2 operand */
   47612   int p3,             /* The P3 operand */
   47613   const char *zP4,    /* The P4 operand */
   47614   int p4type          /* P4 operand type */
   47615 ){
   47616   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
   47617   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
   47618   return addr;
   47619 }
   47620 
   47621 /*
   47622 ** Add an opcode that includes the p4 value as an integer.
   47623 */
   47624 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
   47625   Vdbe *p,            /* Add the opcode to this VM */
   47626   int op,             /* The new opcode */
   47627   int p1,             /* The P1 operand */
   47628   int p2,             /* The P2 operand */
   47629   int p3,             /* The P3 operand */
   47630   int p4              /* The P4 operand as an integer */
   47631 ){
   47632   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
   47633   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
   47634   return addr;
   47635 }
   47636 
   47637 /*
   47638 ** Create a new symbolic label for an instruction that has yet to be
   47639 ** coded.  The symbolic label is really just a negative number.  The
   47640 ** label can be used as the P2 value of an operation.  Later, when
   47641 ** the label is resolved to a specific address, the VDBE will scan
   47642 ** through its operation list and change all values of P2 which match
   47643 ** the label into the resolved address.
   47644 **
   47645 ** The VDBE knows that a P2 value is a label because labels are
   47646 ** always negative and P2 values are suppose to be non-negative.
   47647 ** Hence, a negative P2 value is a label that has yet to be resolved.
   47648 **
   47649 ** Zero is returned if a malloc() fails.
   47650 */
   47651 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
   47652   int i;
   47653   i = p->nLabel++;
   47654   assert( p->magic==VDBE_MAGIC_INIT );
   47655   if( i>=p->nLabelAlloc ){
   47656     int n = p->nLabelAlloc*2 + 5;
   47657     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
   47658                                        n*sizeof(p->aLabel[0]));
   47659     p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
   47660   }
   47661   if( p->aLabel ){
   47662     p->aLabel[i] = -1;
   47663   }
   47664   return -1-i;
   47665 }
   47666 
   47667 /*
   47668 ** Resolve label "x" to be the address of the next instruction to
   47669 ** be inserted.  The parameter "x" must have been obtained from
   47670 ** a prior call to sqlite3VdbeMakeLabel().
   47671 */
   47672 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
   47673   int j = -1-x;
   47674   assert( p->magic==VDBE_MAGIC_INIT );
   47675   assert( j>=0 && j<p->nLabel );
   47676   if( p->aLabel ){
   47677     p->aLabel[j] = p->nOp;
   47678   }
   47679 }
   47680 
   47681 /*
   47682 ** Mark the VDBE as one that can only be run one time.
   47683 */
   47684 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
   47685   p->runOnlyOnce = 1;
   47686 }
   47687 
   47688 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
   47689 
   47690 /*
   47691 ** The following type and function are used to iterate through all opcodes
   47692 ** in a Vdbe main program and each of the sub-programs (triggers) it may
   47693 ** invoke directly or indirectly. It should be used as follows:
   47694 **
   47695 **   Op *pOp;
   47696 **   VdbeOpIter sIter;
   47697 **
   47698 **   memset(&sIter, 0, sizeof(sIter));
   47699 **   sIter.v = v;                            // v is of type Vdbe*
   47700 **   while( (pOp = opIterNext(&sIter)) ){
   47701 **     // Do something with pOp
   47702 **   }
   47703 **   sqlite3DbFree(v->db, sIter.apSub);
   47704 **
   47705 */
   47706 typedef struct VdbeOpIter VdbeOpIter;
   47707 struct VdbeOpIter {
   47708   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
   47709   SubProgram **apSub;        /* Array of subprograms */
   47710   int nSub;                  /* Number of entries in apSub */
   47711   int iAddr;                 /* Address of next instruction to return */
   47712   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
   47713 };
   47714 static Op *opIterNext(VdbeOpIter *p){
   47715   Vdbe *v = p->v;
   47716   Op *pRet = 0;
   47717   Op *aOp;
   47718   int nOp;
   47719 
   47720   if( p->iSub<=p->nSub ){
   47721 
   47722     if( p->iSub==0 ){
   47723       aOp = v->aOp;
   47724       nOp = v->nOp;
   47725     }else{
   47726       aOp = p->apSub[p->iSub-1]->aOp;
   47727       nOp = p->apSub[p->iSub-1]->nOp;
   47728     }
   47729     assert( p->iAddr<nOp );
   47730 
   47731     pRet = &aOp[p->iAddr];
   47732     p->iAddr++;
   47733     if( p->iAddr==nOp ){
   47734       p->iSub++;
   47735       p->iAddr = 0;
   47736     }
   47737 
   47738     if( pRet->p4type==P4_SUBPROGRAM ){
   47739       int nByte = (p->nSub+1)*sizeof(SubProgram*);
   47740       int j;
   47741       for(j=0; j<p->nSub; j++){
   47742         if( p->apSub[j]==pRet->p4.pProgram ) break;
   47743       }
   47744       if( j==p->nSub ){
   47745         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
   47746         if( !p->apSub ){
   47747           pRet = 0;
   47748         }else{
   47749           p->apSub[p->nSub++] = pRet->p4.pProgram;
   47750         }
   47751       }
   47752     }
   47753   }
   47754 
   47755   return pRet;
   47756 }
   47757 
   47758 /*
   47759 ** Check if the program stored in the VM associated with pParse may
   47760 ** throw an ABORT exception (causing the statement, but not entire transaction
   47761 ** to be rolled back). This condition is true if the main program or any
   47762 ** sub-programs contains any of the following:
   47763 **
   47764 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
   47765 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
   47766 **   *  OP_Destroy
   47767 **   *  OP_VUpdate
   47768 **   *  OP_VRename
   47769 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
   47770 **
   47771 ** Then check that the value of Parse.mayAbort is true if an
   47772 ** ABORT may be thrown, or false otherwise. Return true if it does
   47773 ** match, or false otherwise. This function is intended to be used as
   47774 ** part of an assert statement in the compiler. Similar to:
   47775 **
   47776 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
   47777 */
   47778 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
   47779   int hasAbort = 0;
   47780   Op *pOp;
   47781   VdbeOpIter sIter;
   47782   memset(&sIter, 0, sizeof(sIter));
   47783   sIter.v = v;
   47784 
   47785   while( (pOp = opIterNext(&sIter))!=0 ){
   47786     int opcode = pOp->opcode;
   47787     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
   47788 #ifndef SQLITE_OMIT_FOREIGN_KEY
   47789      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
   47790 #endif
   47791      || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
   47792       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
   47793     ){
   47794       hasAbort = 1;
   47795       break;
   47796     }
   47797   }
   47798   sqlite3DbFree(v->db, sIter.apSub);
   47799 
   47800   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
   47801   ** If malloc failed, then the while() loop above may not have iterated
   47802   ** through all opcodes and hasAbort may be set incorrectly. Return
   47803   ** true for this case to prevent the assert() in the callers frame
   47804   ** from failing.  */
   47805   return ( v->db->mallocFailed || hasAbort==mayAbort );
   47806 }
   47807 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
   47808 
   47809 /*
   47810 ** Loop through the program looking for P2 values that are negative
   47811 ** on jump instructions.  Each such value is a label.  Resolve the
   47812 ** label by setting the P2 value to its correct non-zero value.
   47813 **
   47814 ** This routine is called once after all opcodes have been inserted.
   47815 **
   47816 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
   47817 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
   47818 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
   47819 **
   47820 ** The Op.opflags field is set on all opcodes.
   47821 */
   47822 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
   47823   int i;
   47824   int nMaxArgs = *pMaxFuncArgs;
   47825   Op *pOp;
   47826   int *aLabel = p->aLabel;
   47827   p->readOnly = 1;
   47828   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
   47829     u8 opcode = pOp->opcode;
   47830 
   47831     pOp->opflags = sqlite3OpcodeProperty[opcode];
   47832     if( opcode==OP_Function || opcode==OP_AggStep ){
   47833       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
   47834     }else if( opcode==OP_Transaction && pOp->p2!=0 ){
   47835       p->readOnly = 0;
   47836 #ifndef SQLITE_OMIT_VIRTUALTABLE
   47837     }else if( opcode==OP_VUpdate ){
   47838       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
   47839     }else if( opcode==OP_VFilter ){
   47840       int n;
   47841       assert( p->nOp - i >= 3 );
   47842       assert( pOp[-1].opcode==OP_Integer );
   47843       n = pOp[-1].p1;
   47844       if( n>nMaxArgs ) nMaxArgs = n;
   47845 #endif
   47846     }
   47847 
   47848     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
   47849       assert( -1-pOp->p2<p->nLabel );
   47850       pOp->p2 = aLabel[-1-pOp->p2];
   47851     }
   47852   }
   47853   sqlite3DbFree(p->db, p->aLabel);
   47854   p->aLabel = 0;
   47855 
   47856   *pMaxFuncArgs = nMaxArgs;
   47857 }
   47858 
   47859 /*
   47860 ** Return the address of the next instruction to be inserted.
   47861 */
   47862 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
   47863   assert( p->magic==VDBE_MAGIC_INIT );
   47864   return p->nOp;
   47865 }
   47866 
   47867 /*
   47868 ** This function returns a pointer to the array of opcodes associated with
   47869 ** the Vdbe passed as the first argument. It is the callers responsibility
   47870 ** to arrange for the returned array to be eventually freed using the
   47871 ** vdbeFreeOpArray() function.
   47872 **
   47873 ** Before returning, *pnOp is set to the number of entries in the returned
   47874 ** array. Also, *pnMaxArg is set to the larger of its current value and
   47875 ** the number of entries in the Vdbe.apArg[] array required to execute the
   47876 ** returned program.
   47877 */
   47878 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
   47879   VdbeOp *aOp = p->aOp;
   47880   assert( aOp && !p->db->mallocFailed );
   47881 
   47882   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
   47883   assert( p->aMutex.nMutex==0 );
   47884 
   47885   resolveP2Values(p, pnMaxArg);
   47886   *pnOp = p->nOp;
   47887   p->aOp = 0;
   47888   return aOp;
   47889 }
   47890 
   47891 /*
   47892 ** Add a whole list of operations to the operation stack.  Return the
   47893 ** address of the first operation added.
   47894 */
   47895 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
   47896   int addr;
   47897   assert( p->magic==VDBE_MAGIC_INIT );
   47898   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
   47899     return 0;
   47900   }
   47901   addr = p->nOp;
   47902   if( ALWAYS(nOp>0) ){
   47903     int i;
   47904     VdbeOpList const *pIn = aOp;
   47905     for(i=0; i<nOp; i++, pIn++){
   47906       int p2 = pIn->p2;
   47907       VdbeOp *pOut = &p->aOp[i+addr];
   47908       pOut->opcode = pIn->opcode;
   47909       pOut->p1 = pIn->p1;
   47910       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
   47911         pOut->p2 = addr + ADDR(p2);
   47912       }else{
   47913         pOut->p2 = p2;
   47914       }
   47915       pOut->p3 = pIn->p3;
   47916       pOut->p4type = P4_NOTUSED;
   47917       pOut->p4.p = 0;
   47918       pOut->p5 = 0;
   47919 #ifdef SQLITE_DEBUG
   47920       pOut->zComment = 0;
   47921       if( sqlite3VdbeAddopTrace ){
   47922         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
   47923       }
   47924 #endif
   47925     }
   47926     p->nOp += nOp;
   47927   }
   47928   return addr;
   47929 }
   47930 
   47931 /*
   47932 ** Change the value of the P1 operand for a specific instruction.
   47933 ** This routine is useful when a large program is loaded from a
   47934 ** static array using sqlite3VdbeAddOpList but we want to make a
   47935 ** few minor changes to the program.
   47936 */
   47937 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
   47938   assert( p!=0 );
   47939   assert( addr>=0 );
   47940   if( p->nOp>addr ){
   47941     p->aOp[addr].p1 = val;
   47942   }
   47943 }
   47944 
   47945 /*
   47946 ** Change the value of the P2 operand for a specific instruction.
   47947 ** This routine is useful for setting a jump destination.
   47948 */
   47949 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
   47950   assert( p!=0 );
   47951   assert( addr>=0 );
   47952   if( p->nOp>addr ){
   47953     p->aOp[addr].p2 = val;
   47954   }
   47955 }
   47956 
   47957 /*
   47958 ** Change the value of the P3 operand for a specific instruction.
   47959 */
   47960 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
   47961   assert( p!=0 );
   47962   assert( addr>=0 );
   47963   if( p->nOp>addr ){
   47964     p->aOp[addr].p3 = val;
   47965   }
   47966 }
   47967 
   47968 /*
   47969 ** Change the value of the P5 operand for the most recently
   47970 ** added operation.
   47971 */
   47972 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
   47973   assert( p!=0 );
   47974   if( p->aOp ){
   47975     assert( p->nOp>0 );
   47976     p->aOp[p->nOp-1].p5 = val;
   47977   }
   47978 }
   47979 
   47980 /*
   47981 ** Change the P2 operand of instruction addr so that it points to
   47982 ** the address of the next instruction to be coded.
   47983 */
   47984 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
   47985   sqlite3VdbeChangeP2(p, addr, p->nOp);
   47986 }
   47987 
   47988 
   47989 /*
   47990 ** If the input FuncDef structure is ephemeral, then free it.  If
   47991 ** the FuncDef is not ephermal, then do nothing.
   47992 */
   47993 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
   47994   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
   47995     sqlite3DbFree(db, pDef);
   47996   }
   47997 }
   47998 
   47999 /*
   48000 ** Delete a P4 value if necessary.
   48001 */
   48002 static void freeP4(sqlite3 *db, int p4type, void *p4){
   48003   if( p4 ){
   48004     switch( p4type ){
   48005       case P4_REAL:
   48006       case P4_INT64:
   48007       case P4_MPRINTF:
   48008       case P4_DYNAMIC:
   48009       case P4_KEYINFO:
   48010       case P4_INTARRAY:
   48011       case P4_KEYINFO_HANDOFF: {
   48012         sqlite3DbFree(db, p4);
   48013         break;
   48014       }
   48015       case P4_VDBEFUNC: {
   48016         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
   48017         freeEphemeralFunction(db, pVdbeFunc->pFunc);
   48018         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
   48019         sqlite3DbFree(db, pVdbeFunc);
   48020         break;
   48021       }
   48022       case P4_FUNCDEF: {
   48023         freeEphemeralFunction(db, (FuncDef*)p4);
   48024         break;
   48025       }
   48026       case P4_MEM: {
   48027         sqlite3ValueFree((sqlite3_value*)p4);
   48028         break;
   48029       }
   48030       case P4_VTAB : {
   48031         sqlite3VtabUnlock((VTable *)p4);
   48032         break;
   48033       }
   48034       case P4_SUBPROGRAM : {
   48035         sqlite3VdbeProgramDelete(db, (SubProgram *)p4, 1);
   48036         break;
   48037       }
   48038     }
   48039   }
   48040 }
   48041 
   48042 /*
   48043 ** Free the space allocated for aOp and any p4 values allocated for the
   48044 ** opcodes contained within. If aOp is not NULL it is assumed to contain
   48045 ** nOp entries.
   48046 */
   48047 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
   48048   if( aOp ){
   48049     Op *pOp;
   48050     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
   48051       freeP4(db, pOp->p4type, pOp->p4.p);
   48052 #ifdef SQLITE_DEBUG
   48053       sqlite3DbFree(db, pOp->zComment);
   48054 #endif
   48055     }
   48056   }
   48057   sqlite3DbFree(db, aOp);
   48058 }
   48059 
   48060 /*
   48061 ** Decrement the ref-count on the SubProgram structure passed as the
   48062 ** second argument. If the ref-count reaches zero, free the structure.
   48063 **
   48064 ** The array of VDBE opcodes stored as SubProgram.aOp is freed if
   48065 ** either the ref-count reaches zero or parameter freeop is non-zero.
   48066 **
   48067 ** Since the array of opcodes pointed to by SubProgram.aOp may directly
   48068 ** or indirectly contain a reference to the SubProgram structure itself.
   48069 ** By passing a non-zero freeop parameter, the caller may ensure that all
   48070 ** SubProgram structures and their aOp arrays are freed, even when there
   48071 ** are such circular references.
   48072 */
   48073 SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *db, SubProgram *p, int freeop){
   48074   if( p ){
   48075     assert( p->nRef>0 );
   48076     if( freeop || p->nRef==1 ){
   48077       Op *aOp = p->aOp;
   48078       p->aOp = 0;
   48079       vdbeFreeOpArray(db, aOp, p->nOp);
   48080       p->nOp = 0;
   48081     }
   48082     p->nRef--;
   48083     if( p->nRef==0 ){
   48084       sqlite3DbFree(db, p);
   48085     }
   48086   }
   48087 }
   48088 
   48089 
   48090 /*
   48091 ** Change N opcodes starting at addr to No-ops.
   48092 */
   48093 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
   48094   if( p->aOp ){
   48095     VdbeOp *pOp = &p->aOp[addr];
   48096     sqlite3 *db = p->db;
   48097     while( N-- ){
   48098       freeP4(db, pOp->p4type, pOp->p4.p);
   48099       memset(pOp, 0, sizeof(pOp[0]));
   48100       pOp->opcode = OP_Noop;
   48101       pOp++;
   48102     }
   48103   }
   48104 }
   48105 
   48106 /*
   48107 ** Change the value of the P4 operand for a specific instruction.
   48108 ** This routine is useful when a large program is loaded from a
   48109 ** static array using sqlite3VdbeAddOpList but we want to make a
   48110 ** few minor changes to the program.
   48111 **
   48112 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
   48113 ** the string is made into memory obtained from sqlite3_malloc().
   48114 ** A value of n==0 means copy bytes of zP4 up to and including the
   48115 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
   48116 **
   48117 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
   48118 ** A copy is made of the KeyInfo structure into memory obtained from
   48119 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
   48120 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
   48121 ** stored in memory that the caller has obtained from sqlite3_malloc. The
   48122 ** caller should not free the allocation, it will be freed when the Vdbe is
   48123 ** finalized.
   48124 **
   48125 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
   48126 ** to a string or structure that is guaranteed to exist for the lifetime of
   48127 ** the Vdbe. In these cases we can just copy the pointer.
   48128 **
   48129 ** If addr<0 then change P4 on the most recently inserted instruction.
   48130 */
   48131 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
   48132   Op *pOp;
   48133   sqlite3 *db;
   48134   assert( p!=0 );
   48135   db = p->db;
   48136   assert( p->magic==VDBE_MAGIC_INIT );
   48137   if( p->aOp==0 || db->mallocFailed ){
   48138     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
   48139       freeP4(db, n, (void*)*(char**)&zP4);
   48140     }
   48141     return;
   48142   }
   48143   assert( p->nOp>0 );
   48144   assert( addr<p->nOp );
   48145   if( addr<0 ){
   48146     addr = p->nOp - 1;
   48147   }
   48148   pOp = &p->aOp[addr];
   48149   freeP4(db, pOp->p4type, pOp->p4.p);
   48150   pOp->p4.p = 0;
   48151   if( n==P4_INT32 ){
   48152     /* Note: this cast is safe, because the origin data point was an int
   48153     ** that was cast to a (const char *). */
   48154     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
   48155     pOp->p4type = P4_INT32;
   48156   }else if( zP4==0 ){
   48157     pOp->p4.p = 0;
   48158     pOp->p4type = P4_NOTUSED;
   48159   }else if( n==P4_KEYINFO ){
   48160     KeyInfo *pKeyInfo;
   48161     int nField, nByte;
   48162 
   48163     nField = ((KeyInfo*)zP4)->nField;
   48164     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
   48165     pKeyInfo = sqlite3Malloc( nByte );
   48166     pOp->p4.pKeyInfo = pKeyInfo;
   48167     if( pKeyInfo ){
   48168       u8 *aSortOrder;
   48169       memcpy(pKeyInfo, zP4, nByte);
   48170       aSortOrder = pKeyInfo->aSortOrder;
   48171       if( aSortOrder ){
   48172         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
   48173         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
   48174       }
   48175       pOp->p4type = P4_KEYINFO;
   48176     }else{
   48177       p->db->mallocFailed = 1;
   48178       pOp->p4type = P4_NOTUSED;
   48179     }
   48180   }else if( n==P4_KEYINFO_HANDOFF ){
   48181     pOp->p4.p = (void*)zP4;
   48182     pOp->p4type = P4_KEYINFO;
   48183   }else if( n==P4_VTAB ){
   48184     pOp->p4.p = (void*)zP4;
   48185     pOp->p4type = P4_VTAB;
   48186     sqlite3VtabLock((VTable *)zP4);
   48187     assert( ((VTable *)zP4)->db==p->db );
   48188   }else if( n<0 ){
   48189     pOp->p4.p = (void*)zP4;
   48190     pOp->p4type = (signed char)n;
   48191   }else{
   48192     if( n==0 ) n = sqlite3Strlen30(zP4);
   48193     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
   48194     pOp->p4type = P4_DYNAMIC;
   48195   }
   48196 }
   48197 
   48198 #ifndef NDEBUG
   48199 /*
   48200 ** Change the comment on the the most recently coded instruction.  Or
   48201 ** insert a No-op and add the comment to that new instruction.  This
   48202 ** makes the code easier to read during debugging.  None of this happens
   48203 ** in a production build.
   48204 */
   48205 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
   48206   va_list ap;
   48207   if( !p ) return;
   48208   assert( p->nOp>0 || p->aOp==0 );
   48209   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
   48210   if( p->nOp ){
   48211     char **pz = &p->aOp[p->nOp-1].zComment;
   48212     va_start(ap, zFormat);
   48213     sqlite3DbFree(p->db, *pz);
   48214     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
   48215     va_end(ap);
   48216   }
   48217 }
   48218 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
   48219   va_list ap;
   48220   if( !p ) return;
   48221   sqlite3VdbeAddOp0(p, OP_Noop);
   48222   assert( p->nOp>0 || p->aOp==0 );
   48223   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
   48224   if( p->nOp ){
   48225     char **pz = &p->aOp[p->nOp-1].zComment;
   48226     va_start(ap, zFormat);
   48227     sqlite3DbFree(p->db, *pz);
   48228     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
   48229     va_end(ap);
   48230   }
   48231 }
   48232 #endif  /* NDEBUG */
   48233 
   48234 /*
   48235 ** Return the opcode for a given address.  If the address is -1, then
   48236 ** return the most recently inserted opcode.
   48237 **
   48238 ** If a memory allocation error has occurred prior to the calling of this
   48239 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
   48240 ** is readable and writable, but it has no effect.  The return of a dummy
   48241 ** opcode allows the call to continue functioning after a OOM fault without
   48242 ** having to check to see if the return from this routine is a valid pointer.
   48243 **
   48244 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
   48245 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
   48246 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
   48247 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
   48248 ** having to double-check to make sure that the result is non-negative. But
   48249 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
   48250 ** check the value of p->nOp-1 before continuing.
   48251 */
   48252 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
   48253   static VdbeOp dummy;
   48254   assert( p->magic==VDBE_MAGIC_INIT );
   48255   if( addr<0 ){
   48256 #ifdef SQLITE_OMIT_TRACE
   48257     if( p->nOp==0 ) return &dummy;
   48258 #endif
   48259     addr = p->nOp - 1;
   48260   }
   48261   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
   48262   if( p->db->mallocFailed ){
   48263     return &dummy;
   48264   }else{
   48265     return &p->aOp[addr];
   48266   }
   48267 }
   48268 
   48269 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
   48270      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   48271 /*
   48272 ** Compute a string that describes the P4 parameter for an opcode.
   48273 ** Use zTemp for any required temporary buffer space.
   48274 */
   48275 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
   48276   char *zP4 = zTemp;
   48277   assert( nTemp>=20 );
   48278   switch( pOp->p4type ){
   48279     case P4_KEYINFO_STATIC:
   48280     case P4_KEYINFO: {
   48281       int i, j;
   48282       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
   48283       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
   48284       i = sqlite3Strlen30(zTemp);
   48285       for(j=0; j<pKeyInfo->nField; j++){
   48286         CollSeq *pColl = pKeyInfo->aColl[j];
   48287         if( pColl ){
   48288           int n = sqlite3Strlen30(pColl->zName);
   48289           if( i+n>nTemp-6 ){
   48290             memcpy(&zTemp[i],",...",4);
   48291             break;
   48292           }
   48293           zTemp[i++] = ',';
   48294           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
   48295             zTemp[i++] = '-';
   48296           }
   48297           memcpy(&zTemp[i], pColl->zName,n+1);
   48298           i += n;
   48299         }else if( i+4<nTemp-6 ){
   48300           memcpy(&zTemp[i],",nil",4);
   48301           i += 4;
   48302         }
   48303       }
   48304       zTemp[i++] = ')';
   48305       zTemp[i] = 0;
   48306       assert( i<nTemp );
   48307       break;
   48308     }
   48309     case P4_COLLSEQ: {
   48310       CollSeq *pColl = pOp->p4.pColl;
   48311       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
   48312       break;
   48313     }
   48314     case P4_FUNCDEF: {
   48315       FuncDef *pDef = pOp->p4.pFunc;
   48316       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
   48317       break;
   48318     }
   48319     case P4_INT64: {
   48320       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
   48321       break;
   48322     }
   48323     case P4_INT32: {
   48324       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
   48325       break;
   48326     }
   48327     case P4_REAL: {
   48328       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
   48329       break;
   48330     }
   48331     case P4_MEM: {
   48332       Mem *pMem = pOp->p4.pMem;
   48333       assert( (pMem->flags & MEM_Null)==0 );
   48334       if( pMem->flags & MEM_Str ){
   48335         zP4 = pMem->z;
   48336       }else if( pMem->flags & MEM_Int ){
   48337         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
   48338       }else if( pMem->flags & MEM_Real ){
   48339         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
   48340       }else{
   48341         assert( pMem->flags & MEM_Blob );
   48342         zP4 = "(blob)";
   48343       }
   48344       break;
   48345     }
   48346 #ifndef SQLITE_OMIT_VIRTUALTABLE
   48347     case P4_VTAB: {
   48348       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
   48349       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
   48350       break;
   48351     }
   48352 #endif
   48353     case P4_INTARRAY: {
   48354       sqlite3_snprintf(nTemp, zTemp, "intarray");
   48355       break;
   48356     }
   48357     case P4_SUBPROGRAM: {
   48358       sqlite3_snprintf(nTemp, zTemp, "program");
   48359       break;
   48360     }
   48361     default: {
   48362       zP4 = pOp->p4.z;
   48363       if( zP4==0 ){
   48364         zP4 = zTemp;
   48365         zTemp[0] = 0;
   48366       }
   48367     }
   48368   }
   48369   assert( zP4!=0 );
   48370   return zP4;
   48371 }
   48372 #endif
   48373 
   48374 /*
   48375 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
   48376 */
   48377 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
   48378   int mask;
   48379   assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
   48380   assert( i<(int)sizeof(p->btreeMask)*8 );
   48381   mask = ((u32)1)<<i;
   48382   if( (p->btreeMask & mask)==0 ){
   48383     p->btreeMask |= mask;
   48384     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
   48385   }
   48386 }
   48387 
   48388 
   48389 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   48390 /*
   48391 ** Print a single opcode.  This routine is used for debugging only.
   48392 */
   48393 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
   48394   char *zP4;
   48395   char zPtr[50];
   48396   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
   48397   if( pOut==0 ) pOut = stdout;
   48398   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
   48399   fprintf(pOut, zFormat1, pc,
   48400       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
   48401 #ifdef SQLITE_DEBUG
   48402       pOp->zComment ? pOp->zComment : ""
   48403 #else
   48404       ""
   48405 #endif
   48406   );
   48407   fflush(pOut);
   48408 }
   48409 #endif
   48410 
   48411 /*
   48412 ** Release an array of N Mem elements
   48413 */
   48414 static void releaseMemArray(Mem *p, int N){
   48415   if( p && N ){
   48416     Mem *pEnd;
   48417     sqlite3 *db = p->db;
   48418     u8 malloc_failed = db->mallocFailed;
   48419     for(pEnd=&p[N]; p<pEnd; p++){
   48420       assert( (&p[1])==pEnd || p[0].db==p[1].db );
   48421 
   48422       /* This block is really an inlined version of sqlite3VdbeMemRelease()
   48423       ** that takes advantage of the fact that the memory cell value is
   48424       ** being set to NULL after releasing any dynamic resources.
   48425       **
   48426       ** The justification for duplicating code is that according to
   48427       ** callgrind, this causes a certain test case to hit the CPU 4.7
   48428       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
   48429       ** sqlite3MemRelease() were called from here. With -O2, this jumps
   48430       ** to 6.6 percent. The test case is inserting 1000 rows into a table
   48431       ** with no indexes using a single prepared INSERT statement, bind()
   48432       ** and reset(). Inserts are grouped into a transaction.
   48433       */
   48434       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
   48435         sqlite3VdbeMemRelease(p);
   48436       }else if( p->zMalloc ){
   48437         sqlite3DbFree(db, p->zMalloc);
   48438         p->zMalloc = 0;
   48439       }
   48440 
   48441       p->flags = MEM_Null;
   48442     }
   48443     db->mallocFailed = malloc_failed;
   48444   }
   48445 }
   48446 
   48447 /*
   48448 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
   48449 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
   48450 */
   48451 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
   48452   int i;
   48453   Mem *aMem = VdbeFrameMem(p);
   48454   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
   48455   for(i=0; i<p->nChildCsr; i++){
   48456     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
   48457   }
   48458   releaseMemArray(aMem, p->nChildMem);
   48459   sqlite3DbFree(p->v->db, p);
   48460 }
   48461 
   48462 #ifndef SQLITE_OMIT_EXPLAIN
   48463 /*
   48464 ** Give a listing of the program in the virtual machine.
   48465 **
   48466 ** The interface is the same as sqlite3VdbeExec().  But instead of
   48467 ** running the code, it invokes the callback once for each instruction.
   48468 ** This feature is used to implement "EXPLAIN".
   48469 **
   48470 ** When p->explain==1, each instruction is listed.  When
   48471 ** p->explain==2, only OP_Explain instructions are listed and these
   48472 ** are shown in a different format.  p->explain==2 is used to implement
   48473 ** EXPLAIN QUERY PLAN.
   48474 **
   48475 ** When p->explain==1, first the main program is listed, then each of
   48476 ** the trigger subprograms are listed one by one.
   48477 */
   48478 SQLITE_PRIVATE int sqlite3VdbeList(
   48479   Vdbe *p                   /* The VDBE */
   48480 ){
   48481   int nRow;                            /* Stop when row count reaches this */
   48482   int nSub = 0;                        /* Number of sub-vdbes seen so far */
   48483   SubProgram **apSub = 0;              /* Array of sub-vdbes */
   48484   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
   48485   sqlite3 *db = p->db;                 /* The database connection */
   48486   int i;                               /* Loop counter */
   48487   int rc = SQLITE_OK;                  /* Return code */
   48488   Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
   48489 
   48490   assert( p->explain );
   48491   assert( p->magic==VDBE_MAGIC_RUN );
   48492   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
   48493 
   48494   /* Even though this opcode does not use dynamic strings for
   48495   ** the result, result columns may become dynamic if the user calls
   48496   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
   48497   */
   48498   releaseMemArray(pMem, 8);
   48499 
   48500   if( p->rc==SQLITE_NOMEM ){
   48501     /* This happens if a malloc() inside a call to sqlite3_column_text() or
   48502     ** sqlite3_column_text16() failed.  */
   48503     db->mallocFailed = 1;
   48504     return SQLITE_ERROR;
   48505   }
   48506 
   48507   /* When the number of output rows reaches nRow, that means the
   48508   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
   48509   ** nRow is the sum of the number of rows in the main program, plus
   48510   ** the sum of the number of rows in all trigger subprograms encountered
   48511   ** so far.  The nRow value will increase as new trigger subprograms are
   48512   ** encountered, but p->pc will eventually catch up to nRow.
   48513   */
   48514   nRow = p->nOp;
   48515   if( p->explain==1 ){
   48516     /* The first 8 memory cells are used for the result set.  So we will
   48517     ** commandeer the 9th cell to use as storage for an array of pointers
   48518     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
   48519     ** cells.  */
   48520     assert( p->nMem>9 );
   48521     pSub = &p->aMem[9];
   48522     if( pSub->flags&MEM_Blob ){
   48523       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
   48524       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
   48525       nSub = pSub->n/sizeof(Vdbe*);
   48526       apSub = (SubProgram **)pSub->z;
   48527     }
   48528     for(i=0; i<nSub; i++){
   48529       nRow += apSub[i]->nOp;
   48530     }
   48531   }
   48532 
   48533   do{
   48534     i = p->pc++;
   48535   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
   48536   if( i>=nRow ){
   48537     p->rc = SQLITE_OK;
   48538     rc = SQLITE_DONE;
   48539   }else if( db->u1.isInterrupted ){
   48540     p->rc = SQLITE_INTERRUPT;
   48541     rc = SQLITE_ERROR;
   48542     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
   48543   }else{
   48544     char *z;
   48545     Op *pOp;
   48546     if( i<p->nOp ){
   48547       /* The output line number is small enough that we are still in the
   48548       ** main program. */
   48549       pOp = &p->aOp[i];
   48550     }else{
   48551       /* We are currently listing subprograms.  Figure out which one and
   48552       ** pick up the appropriate opcode. */
   48553       int j;
   48554       i -= p->nOp;
   48555       for(j=0; i>=apSub[j]->nOp; j++){
   48556         i -= apSub[j]->nOp;
   48557       }
   48558       pOp = &apSub[j]->aOp[i];
   48559     }
   48560     if( p->explain==1 ){
   48561       pMem->flags = MEM_Int;
   48562       pMem->type = SQLITE_INTEGER;
   48563       pMem->u.i = i;                                /* Program counter */
   48564       pMem++;
   48565 
   48566       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
   48567       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
   48568       assert( pMem->z!=0 );
   48569       pMem->n = sqlite3Strlen30(pMem->z);
   48570       pMem->type = SQLITE_TEXT;
   48571       pMem->enc = SQLITE_UTF8;
   48572       pMem++;
   48573 
   48574       /* When an OP_Program opcode is encounter (the only opcode that has
   48575       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
   48576       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
   48577       ** has not already been seen.
   48578       */
   48579       if( pOp->p4type==P4_SUBPROGRAM ){
   48580         int nByte = (nSub+1)*sizeof(SubProgram*);
   48581         int j;
   48582         for(j=0; j<nSub; j++){
   48583           if( apSub[j]==pOp->p4.pProgram ) break;
   48584         }
   48585         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
   48586           apSub = (SubProgram **)pSub->z;
   48587           apSub[nSub++] = pOp->p4.pProgram;
   48588           pSub->flags |= MEM_Blob;
   48589           pSub->n = nSub*sizeof(SubProgram*);
   48590         }
   48591       }
   48592     }
   48593 
   48594     pMem->flags = MEM_Int;
   48595     pMem->u.i = pOp->p1;                          /* P1 */
   48596     pMem->type = SQLITE_INTEGER;
   48597     pMem++;
   48598 
   48599     pMem->flags = MEM_Int;
   48600     pMem->u.i = pOp->p2;                          /* P2 */
   48601     pMem->type = SQLITE_INTEGER;
   48602     pMem++;
   48603 
   48604     if( p->explain==1 ){
   48605       pMem->flags = MEM_Int;
   48606       pMem->u.i = pOp->p3;                          /* P3 */
   48607       pMem->type = SQLITE_INTEGER;
   48608       pMem++;
   48609     }
   48610 
   48611     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
   48612       assert( p->db->mallocFailed );
   48613       return SQLITE_ERROR;
   48614     }
   48615     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
   48616     z = displayP4(pOp, pMem->z, 32);
   48617     if( z!=pMem->z ){
   48618       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
   48619     }else{
   48620       assert( pMem->z!=0 );
   48621       pMem->n = sqlite3Strlen30(pMem->z);
   48622       pMem->enc = SQLITE_UTF8;
   48623     }
   48624     pMem->type = SQLITE_TEXT;
   48625     pMem++;
   48626 
   48627     if( p->explain==1 ){
   48628       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
   48629         assert( p->db->mallocFailed );
   48630         return SQLITE_ERROR;
   48631       }
   48632       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
   48633       pMem->n = 2;
   48634       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
   48635       pMem->type = SQLITE_TEXT;
   48636       pMem->enc = SQLITE_UTF8;
   48637       pMem++;
   48638 
   48639 #ifdef SQLITE_DEBUG
   48640       if( pOp->zComment ){
   48641         pMem->flags = MEM_Str|MEM_Term;
   48642         pMem->z = pOp->zComment;
   48643         pMem->n = sqlite3Strlen30(pMem->z);
   48644         pMem->enc = SQLITE_UTF8;
   48645         pMem->type = SQLITE_TEXT;
   48646       }else
   48647 #endif
   48648       {
   48649         pMem->flags = MEM_Null;                       /* Comment */
   48650         pMem->type = SQLITE_NULL;
   48651       }
   48652     }
   48653 
   48654     p->nResColumn = 8 - 5*(p->explain-1);
   48655     p->rc = SQLITE_OK;
   48656     rc = SQLITE_ROW;
   48657   }
   48658   return rc;
   48659 }
   48660 #endif /* SQLITE_OMIT_EXPLAIN */
   48661 
   48662 #ifdef SQLITE_DEBUG
   48663 /*
   48664 ** Print the SQL that was used to generate a VDBE program.
   48665 */
   48666 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
   48667   int nOp = p->nOp;
   48668   VdbeOp *pOp;
   48669   if( nOp<1 ) return;
   48670   pOp = &p->aOp[0];
   48671   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
   48672     const char *z = pOp->p4.z;
   48673     while( sqlite3Isspace(*z) ) z++;
   48674     printf("SQL: [%s]\n", z);
   48675   }
   48676 }
   48677 #endif
   48678 
   48679 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
   48680 /*
   48681 ** Print an IOTRACE message showing SQL content.
   48682 */
   48683 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
   48684   int nOp = p->nOp;
   48685   VdbeOp *pOp;
   48686   if( sqlite3IoTrace==0 ) return;
   48687   if( nOp<1 ) return;
   48688   pOp = &p->aOp[0];
   48689   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
   48690     int i, j;
   48691     char z[1000];
   48692     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
   48693     for(i=0; sqlite3Isspace(z[i]); i++){}
   48694     for(j=0; z[i]; i++){
   48695       if( sqlite3Isspace(z[i]) ){
   48696         if( z[i-1]!=' ' ){
   48697           z[j++] = ' ';
   48698         }
   48699       }else{
   48700         z[j++] = z[i];
   48701       }
   48702     }
   48703     z[j] = 0;
   48704     sqlite3IoTrace("SQL %s\n", z);
   48705   }
   48706 }
   48707 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
   48708 
   48709 /*
   48710 ** Allocate space from a fixed size buffer and return a pointer to
   48711 ** that space.  If insufficient space is available, return NULL.
   48712 **
   48713 ** The pBuf parameter is the initial value of a pointer which will
   48714 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
   48715 ** NULL, it means that memory space has already been allocated and that
   48716 ** this routine should not allocate any new memory.  When pBuf is not
   48717 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
   48718 ** is NULL.
   48719 **
   48720 ** nByte is the number of bytes of space needed.
   48721 **
   48722 ** *ppFrom points to available space and pEnd points to the end of the
   48723 ** available space.  When space is allocated, *ppFrom is advanced past
   48724 ** the end of the allocated space.
   48725 **
   48726 ** *pnByte is a counter of the number of bytes of space that have failed
   48727 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
   48728 ** request, then increment *pnByte by the amount of the request.
   48729 */
   48730 static void *allocSpace(
   48731   void *pBuf,          /* Where return pointer will be stored */
   48732   int nByte,           /* Number of bytes to allocate */
   48733   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
   48734   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
   48735   int *pnByte          /* If allocation cannot be made, increment *pnByte */
   48736 ){
   48737   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
   48738   if( pBuf ) return pBuf;
   48739   nByte = ROUND8(nByte);
   48740   if( &(*ppFrom)[nByte] <= pEnd ){
   48741     pBuf = (void*)*ppFrom;
   48742     *ppFrom += nByte;
   48743   }else{
   48744     *pnByte += nByte;
   48745   }
   48746   return pBuf;
   48747 }
   48748 
   48749 /*
   48750 ** Prepare a virtual machine for execution.  This involves things such
   48751 ** as allocating stack space and initializing the program counter.
   48752 ** After the VDBE has be prepped, it can be executed by one or more
   48753 ** calls to sqlite3VdbeExec().
   48754 **
   48755 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
   48756 ** VDBE_MAGIC_RUN.
   48757 **
   48758 ** This function may be called more than once on a single virtual machine.
   48759 ** The first call is made while compiling the SQL statement. Subsequent
   48760 ** calls are made as part of the process of resetting a statement to be
   48761 ** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor
   48762 ** and isExplain parameters are only passed correct values the first time
   48763 ** the function is called. On subsequent calls, from sqlite3_reset(), nVar
   48764 ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
   48765 */
   48766 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
   48767   Vdbe *p,                       /* The VDBE */
   48768   int nVar,                      /* Number of '?' see in the SQL statement */
   48769   int nMem,                      /* Number of memory cells to allocate */
   48770   int nCursor,                   /* Number of cursors to allocate */
   48771   int nArg,                      /* Maximum number of args in SubPrograms */
   48772   int isExplain,                 /* True if the EXPLAIN keywords is present */
   48773   int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
   48774 ){
   48775   int n;
   48776   sqlite3 *db = p->db;
   48777 
   48778   assert( p!=0 );
   48779   assert( p->magic==VDBE_MAGIC_INIT );
   48780 
   48781   /* There should be at least one opcode.
   48782   */
   48783   assert( p->nOp>0 );
   48784 
   48785   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
   48786   p->magic = VDBE_MAGIC_RUN;
   48787 
   48788   /* For each cursor required, also allocate a memory cell. Memory
   48789   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
   48790   ** the vdbe program. Instead they are used to allocate space for
   48791   ** VdbeCursor/BtCursor structures. The blob of memory associated with
   48792   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
   48793   ** stores the blob of memory associated with cursor 1, etc.
   48794   **
   48795   ** See also: allocateCursor().
   48796   */
   48797   nMem += nCursor;
   48798 
   48799   /* Allocate space for memory registers, SQL variables, VDBE cursors and
   48800   ** an array to marshal SQL function arguments in. This is only done the
   48801   ** first time this function is called for a given VDBE, not when it is
   48802   ** being called from sqlite3_reset() to reset the virtual machine.
   48803   */
   48804   if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
   48805     u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
   48806     u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
   48807     int nByte;                              /* How much extra memory needed */
   48808 
   48809     resolveP2Values(p, &nArg);
   48810     p->usesStmtJournal = (u8)usesStmtJournal;
   48811     if( isExplain && nMem<10 ){
   48812       nMem = 10;
   48813     }
   48814     memset(zCsr, 0, zEnd-zCsr);
   48815     zCsr += (zCsr - (u8*)0)&7;
   48816     assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
   48817 
   48818     /* Memory for registers, parameters, cursor, etc, is allocated in two
   48819     ** passes.  On the first pass, we try to reuse unused space at the
   48820     ** end of the opcode array.  If we are unable to satisfy all memory
   48821     ** requirements by reusing the opcode array tail, then the second
   48822     ** pass will fill in the rest using a fresh allocation.
   48823     **
   48824     ** This two-pass approach that reuses as much memory as possible from
   48825     ** the leftover space at the end of the opcode array can significantly
   48826     ** reduce the amount of memory held by a prepared statement.
   48827     */
   48828     do {
   48829       nByte = 0;
   48830       p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
   48831       p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
   48832       p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
   48833       p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
   48834       p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
   48835                             &zCsr, zEnd, &nByte);
   48836       if( nByte ){
   48837         p->pFree = sqlite3DbMallocZero(db, nByte);
   48838       }
   48839       zCsr = p->pFree;
   48840       zEnd = &zCsr[nByte];
   48841     }while( nByte && !db->mallocFailed );
   48842 
   48843     p->nCursor = (u16)nCursor;
   48844     if( p->aVar ){
   48845       p->nVar = (ynVar)nVar;
   48846       for(n=0; n<nVar; n++){
   48847         p->aVar[n].flags = MEM_Null;
   48848         p->aVar[n].db = db;
   48849       }
   48850     }
   48851     if( p->aMem ){
   48852       p->aMem--;                      /* aMem[] goes from 1..nMem */
   48853       p->nMem = nMem;                 /*       not from 0..nMem-1 */
   48854       for(n=1; n<=nMem; n++){
   48855         p->aMem[n].flags = MEM_Null;
   48856         p->aMem[n].db = db;
   48857       }
   48858     }
   48859   }
   48860 #ifdef SQLITE_DEBUG
   48861   for(n=1; n<p->nMem; n++){
   48862     assert( p->aMem[n].db==db );
   48863   }
   48864 #endif
   48865 
   48866   p->pc = -1;
   48867   p->rc = SQLITE_OK;
   48868   p->errorAction = OE_Abort;
   48869   p->explain |= isExplain;
   48870   p->magic = VDBE_MAGIC_RUN;
   48871   p->nChange = 0;
   48872   p->cacheCtr = 1;
   48873   p->minWriteFileFormat = 255;
   48874   p->iStatement = 0;
   48875 #ifdef VDBE_PROFILE
   48876   {
   48877     int i;
   48878     for(i=0; i<p->nOp; i++){
   48879       p->aOp[i].cnt = 0;
   48880       p->aOp[i].cycles = 0;
   48881     }
   48882   }
   48883 #endif
   48884 }
   48885 
   48886 /*
   48887 ** Close a VDBE cursor and release all the resources that cursor
   48888 ** happens to hold.
   48889 */
   48890 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
   48891   if( pCx==0 ){
   48892     return;
   48893   }
   48894   if( pCx->pBt ){
   48895     sqlite3BtreeClose(pCx->pBt);
   48896     /* The pCx->pCursor will be close automatically, if it exists, by
   48897     ** the call above. */
   48898   }else if( pCx->pCursor ){
   48899     sqlite3BtreeCloseCursor(pCx->pCursor);
   48900   }
   48901 #ifndef SQLITE_OMIT_VIRTUALTABLE
   48902   if( pCx->pVtabCursor ){
   48903     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
   48904     const sqlite3_module *pModule = pCx->pModule;
   48905     p->inVtabMethod = 1;
   48906     pModule->xClose(pVtabCursor);
   48907     p->inVtabMethod = 0;
   48908   }
   48909 #endif
   48910 }
   48911 
   48912 /*
   48913 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
   48914 ** is used, for example, when a trigger sub-program is halted to restore
   48915 ** control to the main program.
   48916 */
   48917 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
   48918   Vdbe *v = pFrame->v;
   48919   v->aOp = pFrame->aOp;
   48920   v->nOp = pFrame->nOp;
   48921   v->aMem = pFrame->aMem;
   48922   v->nMem = pFrame->nMem;
   48923   v->apCsr = pFrame->apCsr;
   48924   v->nCursor = pFrame->nCursor;
   48925   v->db->lastRowid = pFrame->lastRowid;
   48926   v->nChange = pFrame->nChange;
   48927   return pFrame->pc;
   48928 }
   48929 
   48930 /*
   48931 ** Close all cursors.
   48932 **
   48933 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
   48934 ** cell array. This is necessary as the memory cell array may contain
   48935 ** pointers to VdbeFrame objects, which may in turn contain pointers to
   48936 ** open cursors.
   48937 */
   48938 static void closeAllCursors(Vdbe *p){
   48939   if( p->pFrame ){
   48940     VdbeFrame *pFrame = p->pFrame;
   48941     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
   48942     sqlite3VdbeFrameRestore(pFrame);
   48943   }
   48944   p->pFrame = 0;
   48945   p->nFrame = 0;
   48946 
   48947   if( p->apCsr ){
   48948     int i;
   48949     for(i=0; i<p->nCursor; i++){
   48950       VdbeCursor *pC = p->apCsr[i];
   48951       if( pC ){
   48952         sqlite3VdbeFreeCursor(p, pC);
   48953         p->apCsr[i] = 0;
   48954       }
   48955     }
   48956   }
   48957   if( p->aMem ){
   48958     releaseMemArray(&p->aMem[1], p->nMem);
   48959   }
   48960 }
   48961 
   48962 /*
   48963 ** Clean up the VM after execution.
   48964 **
   48965 ** This routine will automatically close any cursors, lists, and/or
   48966 ** sorters that were left open.  It also deletes the values of
   48967 ** variables in the aVar[] array.
   48968 */
   48969 static void Cleanup(Vdbe *p){
   48970   sqlite3 *db = p->db;
   48971 
   48972 #ifdef SQLITE_DEBUG
   48973   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
   48974   ** Vdbe.aMem[] arrays have already been cleaned up.  */
   48975   int i;
   48976   for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
   48977   for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
   48978 #endif
   48979 
   48980   sqlite3DbFree(db, p->zErrMsg);
   48981   p->zErrMsg = 0;
   48982   p->pResultSet = 0;
   48983 }
   48984 
   48985 /*
   48986 ** Set the number of result columns that will be returned by this SQL
   48987 ** statement. This is now set at compile time, rather than during
   48988 ** execution of the vdbe program so that sqlite3_column_count() can
   48989 ** be called on an SQL statement before sqlite3_step().
   48990 */
   48991 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
   48992   Mem *pColName;
   48993   int n;
   48994   sqlite3 *db = p->db;
   48995 
   48996   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
   48997   sqlite3DbFree(db, p->aColName);
   48998   n = nResColumn*COLNAME_N;
   48999   p->nResColumn = (u16)nResColumn;
   49000   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
   49001   if( p->aColName==0 ) return;
   49002   while( n-- > 0 ){
   49003     pColName->flags = MEM_Null;
   49004     pColName->db = p->db;
   49005     pColName++;
   49006   }
   49007 }
   49008 
   49009 /*
   49010 ** Set the name of the idx'th column to be returned by the SQL statement.
   49011 ** zName must be a pointer to a nul terminated string.
   49012 **
   49013 ** This call must be made after a call to sqlite3VdbeSetNumCols().
   49014 **
   49015 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
   49016 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
   49017 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
   49018 */
   49019 SQLITE_PRIVATE int sqlite3VdbeSetColName(
   49020   Vdbe *p,                         /* Vdbe being configured */
   49021   int idx,                         /* Index of column zName applies to */
   49022   int var,                         /* One of the COLNAME_* constants */
   49023   const char *zName,               /* Pointer to buffer containing name */
   49024   void (*xDel)(void*)              /* Memory management strategy for zName */
   49025 ){
   49026   int rc;
   49027   Mem *pColName;
   49028   assert( idx<p->nResColumn );
   49029   assert( var<COLNAME_N );
   49030   if( p->db->mallocFailed ){
   49031     assert( !zName || xDel!=SQLITE_DYNAMIC );
   49032     return SQLITE_NOMEM;
   49033   }
   49034   assert( p->aColName!=0 );
   49035   pColName = &(p->aColName[idx+var*p->nResColumn]);
   49036   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
   49037   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
   49038   return rc;
   49039 }
   49040 
   49041 /*
   49042 ** A read or write transaction may or may not be active on database handle
   49043 ** db. If a transaction is active, commit it. If there is a
   49044 ** write-transaction spanning more than one database file, this routine
   49045 ** takes care of the master journal trickery.
   49046 */
   49047 static int vdbeCommit(sqlite3 *db, Vdbe *p){
   49048   int i;
   49049   int nTrans = 0;  /* Number of databases with an active write-transaction */
   49050   int rc = SQLITE_OK;
   49051   int needXcommit = 0;
   49052 
   49053 #ifdef SQLITE_OMIT_VIRTUALTABLE
   49054   /* With this option, sqlite3VtabSync() is defined to be simply
   49055   ** SQLITE_OK so p is not used.
   49056   */
   49057   UNUSED_PARAMETER(p);
   49058 #endif
   49059 
   49060   /* Before doing anything else, call the xSync() callback for any
   49061   ** virtual module tables written in this transaction. This has to
   49062   ** be done before determining whether a master journal file is
   49063   ** required, as an xSync() callback may add an attached database
   49064   ** to the transaction.
   49065   */
   49066   rc = sqlite3VtabSync(db, &p->zErrMsg);
   49067   if( rc!=SQLITE_OK ){
   49068     return rc;
   49069   }
   49070 
   49071   /* This loop determines (a) if the commit hook should be invoked and
   49072   ** (b) how many database files have open write transactions, not
   49073   ** including the temp database. (b) is important because if more than
   49074   ** one database file has an open write transaction, a master journal
   49075   ** file is required for an atomic commit.
   49076   */
   49077   for(i=0; i<db->nDb; i++){
   49078     Btree *pBt = db->aDb[i].pBt;
   49079     if( sqlite3BtreeIsInTrans(pBt) ){
   49080       needXcommit = 1;
   49081       if( i!=1 ) nTrans++;
   49082     }
   49083   }
   49084 
   49085   /* If there are any write-transactions at all, invoke the commit hook */
   49086   if( needXcommit && db->xCommitCallback ){
   49087     rc = db->xCommitCallback(db->pCommitArg);
   49088     if( rc ){
   49089       return SQLITE_CONSTRAINT;
   49090     }
   49091   }
   49092 
   49093   /* The simple case - no more than one database file (not counting the
   49094   ** TEMP database) has a transaction active.   There is no need for the
   49095   ** master-journal.
   49096   **
   49097   ** If the return value of sqlite3BtreeGetFilename() is a zero length
   49098   ** string, it means the main database is :memory: or a temp file.  In
   49099   ** that case we do not support atomic multi-file commits, so use the
   49100   ** simple case then too.
   49101   */
   49102   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
   49103    || nTrans<=1
   49104   ){
   49105     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   49106       Btree *pBt = db->aDb[i].pBt;
   49107       if( pBt ){
   49108         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
   49109       }
   49110     }
   49111 
   49112     /* Do the commit only if all databases successfully complete phase 1.
   49113     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
   49114     ** IO error while deleting or truncating a journal file. It is unlikely,
   49115     ** but could happen. In this case abandon processing and return the error.
   49116     */
   49117     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   49118       Btree *pBt = db->aDb[i].pBt;
   49119       if( pBt ){
   49120         rc = sqlite3BtreeCommitPhaseTwo(pBt);
   49121       }
   49122     }
   49123     if( rc==SQLITE_OK ){
   49124       sqlite3VtabCommit(db);
   49125     }
   49126   }
   49127 
   49128   /* The complex case - There is a multi-file write-transaction active.
   49129   ** This requires a master journal file to ensure the transaction is
   49130   ** committed atomicly.
   49131   */
   49132 #ifndef SQLITE_OMIT_DISKIO
   49133   else{
   49134     sqlite3_vfs *pVfs = db->pVfs;
   49135     int needSync = 0;
   49136     char *zMaster = 0;   /* File-name for the master journal */
   49137     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
   49138     sqlite3_file *pMaster = 0;
   49139     i64 offset = 0;
   49140     int res;
   49141 
   49142     /* Select a master journal file name */
   49143     do {
   49144       u32 iRandom;
   49145       sqlite3DbFree(db, zMaster);
   49146       sqlite3_randomness(sizeof(iRandom), &iRandom);
   49147       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
   49148       if( !zMaster ){
   49149         return SQLITE_NOMEM;
   49150       }
   49151       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
   49152     }while( rc==SQLITE_OK && res );
   49153     if( rc==SQLITE_OK ){
   49154       /* Open the master journal. */
   49155       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
   49156           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
   49157           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
   49158       );
   49159     }
   49160     if( rc!=SQLITE_OK ){
   49161       sqlite3DbFree(db, zMaster);
   49162       return rc;
   49163     }
   49164 
   49165     /* Write the name of each database file in the transaction into the new
   49166     ** master journal file. If an error occurs at this point close
   49167     ** and delete the master journal file. All the individual journal files
   49168     ** still have 'null' as the master journal pointer, so they will roll
   49169     ** back independently if a failure occurs.
   49170     */
   49171     for(i=0; i<db->nDb; i++){
   49172       Btree *pBt = db->aDb[i].pBt;
   49173       if( sqlite3BtreeIsInTrans(pBt) ){
   49174         char const *zFile = sqlite3BtreeGetJournalname(pBt);
   49175         if( zFile==0 || zFile[0]==0 ){
   49176           continue;  /* Ignore TEMP and :memory: databases */
   49177         }
   49178         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
   49179           needSync = 1;
   49180         }
   49181         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
   49182         offset += sqlite3Strlen30(zFile)+1;
   49183         if( rc!=SQLITE_OK ){
   49184           sqlite3OsCloseFree(pMaster);
   49185           sqlite3OsDelete(pVfs, zMaster, 0);
   49186           sqlite3DbFree(db, zMaster);
   49187           return rc;
   49188         }
   49189       }
   49190     }
   49191 
   49192     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
   49193     ** flag is set this is not required.
   49194     */
   49195     if( needSync
   49196      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
   49197      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
   49198     ){
   49199       sqlite3OsCloseFree(pMaster);
   49200       sqlite3OsDelete(pVfs, zMaster, 0);
   49201       sqlite3DbFree(db, zMaster);
   49202       return rc;
   49203     }
   49204 
   49205     /* Sync all the db files involved in the transaction. The same call
   49206     ** sets the master journal pointer in each individual journal. If
   49207     ** an error occurs here, do not delete the master journal file.
   49208     **
   49209     ** If the error occurs during the first call to
   49210     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
   49211     ** master journal file will be orphaned. But we cannot delete it,
   49212     ** in case the master journal file name was written into the journal
   49213     ** file before the failure occurred.
   49214     */
   49215     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   49216       Btree *pBt = db->aDb[i].pBt;
   49217       if( pBt ){
   49218         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
   49219       }
   49220     }
   49221     sqlite3OsCloseFree(pMaster);
   49222     if( rc!=SQLITE_OK ){
   49223       sqlite3DbFree(db, zMaster);
   49224       return rc;
   49225     }
   49226 
   49227     /* Delete the master journal file. This commits the transaction. After
   49228     ** doing this the directory is synced again before any individual
   49229     ** transaction files are deleted.
   49230     */
   49231     rc = sqlite3OsDelete(pVfs, zMaster, 1);
   49232     sqlite3DbFree(db, zMaster);
   49233     zMaster = 0;
   49234     if( rc ){
   49235       return rc;
   49236     }
   49237 
   49238     /* All files and directories have already been synced, so the following
   49239     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
   49240     ** deleting or truncating journals. If something goes wrong while
   49241     ** this is happening we don't really care. The integrity of the
   49242     ** transaction is already guaranteed, but some stray 'cold' journals
   49243     ** may be lying around. Returning an error code won't help matters.
   49244     */
   49245     disable_simulated_io_errors();
   49246     sqlite3BeginBenignMalloc();
   49247     for(i=0; i<db->nDb; i++){
   49248       Btree *pBt = db->aDb[i].pBt;
   49249       if( pBt ){
   49250         sqlite3BtreeCommitPhaseTwo(pBt);
   49251       }
   49252     }
   49253     sqlite3EndBenignMalloc();
   49254     enable_simulated_io_errors();
   49255 
   49256     sqlite3VtabCommit(db);
   49257   }
   49258 #endif
   49259 
   49260   return rc;
   49261 }
   49262 
   49263 /*
   49264 ** This routine checks that the sqlite3.activeVdbeCnt count variable
   49265 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
   49266 ** currently active. An assertion fails if the two counts do not match.
   49267 ** This is an internal self-check only - it is not an essential processing
   49268 ** step.
   49269 **
   49270 ** This is a no-op if NDEBUG is defined.
   49271 */
   49272 #ifndef NDEBUG
   49273 static void checkActiveVdbeCnt(sqlite3 *db){
   49274   Vdbe *p;
   49275   int cnt = 0;
   49276   int nWrite = 0;
   49277   p = db->pVdbe;
   49278   while( p ){
   49279     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
   49280       cnt++;
   49281       if( p->readOnly==0 ) nWrite++;
   49282     }
   49283     p = p->pNext;
   49284   }
   49285   assert( cnt==db->activeVdbeCnt );
   49286   assert( nWrite==db->writeVdbeCnt );
   49287 }
   49288 #else
   49289 #define checkActiveVdbeCnt(x)
   49290 #endif
   49291 
   49292 /*
   49293 ** For every Btree that in database connection db which
   49294 ** has been modified, "trip" or invalidate each cursor in
   49295 ** that Btree might have been modified so that the cursor
   49296 ** can never be used again.  This happens when a rollback
   49297 *** occurs.  We have to trip all the other cursors, even
   49298 ** cursor from other VMs in different database connections,
   49299 ** so that none of them try to use the data at which they
   49300 ** were pointing and which now may have been changed due
   49301 ** to the rollback.
   49302 **
   49303 ** Remember that a rollback can delete tables complete and
   49304 ** reorder rootpages.  So it is not sufficient just to save
   49305 ** the state of the cursor.  We have to invalidate the cursor
   49306 ** so that it is never used again.
   49307 */
   49308 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
   49309   int i;
   49310   for(i=0; i<db->nDb; i++){
   49311     Btree *p = db->aDb[i].pBt;
   49312     if( p && sqlite3BtreeIsInTrans(p) ){
   49313       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
   49314     }
   49315   }
   49316 }
   49317 
   49318 /*
   49319 ** If the Vdbe passed as the first argument opened a statement-transaction,
   49320 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
   49321 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
   49322 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
   49323 ** statement transaction is commtted.
   49324 **
   49325 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
   49326 ** Otherwise SQLITE_OK.
   49327 */
   49328 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
   49329   sqlite3 *const db = p->db;
   49330   int rc = SQLITE_OK;
   49331 
   49332   /* If p->iStatement is greater than zero, then this Vdbe opened a
   49333   ** statement transaction that should be closed here. The only exception
   49334   ** is that an IO error may have occured, causing an emergency rollback.
   49335   ** In this case (db->nStatement==0), and there is nothing to do.
   49336   */
   49337   if( db->nStatement && p->iStatement ){
   49338     int i;
   49339     const int iSavepoint = p->iStatement-1;
   49340 
   49341     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
   49342     assert( db->nStatement>0 );
   49343     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
   49344 
   49345     for(i=0; i<db->nDb; i++){
   49346       int rc2 = SQLITE_OK;
   49347       Btree *pBt = db->aDb[i].pBt;
   49348       if( pBt ){
   49349         if( eOp==SAVEPOINT_ROLLBACK ){
   49350           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
   49351         }
   49352         if( rc2==SQLITE_OK ){
   49353           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
   49354         }
   49355         if( rc==SQLITE_OK ){
   49356           rc = rc2;
   49357         }
   49358       }
   49359     }
   49360     db->nStatement--;
   49361     p->iStatement = 0;
   49362 
   49363     /* If the statement transaction is being rolled back, also restore the
   49364     ** database handles deferred constraint counter to the value it had when
   49365     ** the statement transaction was opened.  */
   49366     if( eOp==SAVEPOINT_ROLLBACK ){
   49367       db->nDeferredCons = p->nStmtDefCons;
   49368     }
   49369   }
   49370   return rc;
   49371 }
   49372 
   49373 /*
   49374 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
   49375 ** this routine obtains the mutex associated with each BtShared structure
   49376 ** that may be accessed by the VM passed as an argument. In doing so it
   49377 ** sets the BtShared.db member of each of the BtShared structures, ensuring
   49378 ** that the correct busy-handler callback is invoked if required.
   49379 **
   49380 ** If SQLite is not threadsafe but does support shared-cache mode, then
   49381 ** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
   49382 ** of all of BtShared structures accessible via the database handle
   49383 ** associated with the VM. Of course only a subset of these structures
   49384 ** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
   49385 ** that subset out, but there is no advantage to doing so.
   49386 **
   49387 ** If SQLite is not threadsafe and does not support shared-cache mode, this
   49388 ** function is a no-op.
   49389 */
   49390 #ifndef SQLITE_OMIT_SHARED_CACHE
   49391 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p){
   49392 #if SQLITE_THREADSAFE
   49393   sqlite3BtreeMutexArrayEnter(&p->aMutex);
   49394 #else
   49395   sqlite3BtreeEnterAll(p->db);
   49396 #endif
   49397 }
   49398 #endif
   49399 
   49400 /*
   49401 ** This function is called when a transaction opened by the database
   49402 ** handle associated with the VM passed as an argument is about to be
   49403 ** committed. If there are outstanding deferred foreign key constraint
   49404 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
   49405 **
   49406 ** If there are outstanding FK violations and this function returns
   49407 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
   49408 ** an error message to it. Then return SQLITE_ERROR.
   49409 */
   49410 #ifndef SQLITE_OMIT_FOREIGN_KEY
   49411 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
   49412   sqlite3 *db = p->db;
   49413   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
   49414     p->rc = SQLITE_CONSTRAINT;
   49415     p->errorAction = OE_Abort;
   49416     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
   49417     return SQLITE_ERROR;
   49418   }
   49419   return SQLITE_OK;
   49420 }
   49421 #endif
   49422 
   49423 /*
   49424 ** This routine is called the when a VDBE tries to halt.  If the VDBE
   49425 ** has made changes and is in autocommit mode, then commit those
   49426 ** changes.  If a rollback is needed, then do the rollback.
   49427 **
   49428 ** This routine is the only way to move the state of a VM from
   49429 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
   49430 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
   49431 **
   49432 ** Return an error code.  If the commit could not complete because of
   49433 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
   49434 ** means the close did not happen and needs to be repeated.
   49435 */
   49436 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
   49437   int rc;                         /* Used to store transient return codes */
   49438   sqlite3 *db = p->db;
   49439 
   49440   /* This function contains the logic that determines if a statement or
   49441   ** transaction will be committed or rolled back as a result of the
   49442   ** execution of this virtual machine.
   49443   **
   49444   ** If any of the following errors occur:
   49445   **
   49446   **     SQLITE_NOMEM
   49447   **     SQLITE_IOERR
   49448   **     SQLITE_FULL
   49449   **     SQLITE_INTERRUPT
   49450   **
   49451   ** Then the internal cache might have been left in an inconsistent
   49452   ** state.  We need to rollback the statement transaction, if there is
   49453   ** one, or the complete transaction if there is no statement transaction.
   49454   */
   49455 
   49456   if( p->db->mallocFailed ){
   49457     p->rc = SQLITE_NOMEM;
   49458   }
   49459   closeAllCursors(p);
   49460   if( p->magic!=VDBE_MAGIC_RUN ){
   49461     return SQLITE_OK;
   49462   }
   49463   checkActiveVdbeCnt(db);
   49464 
   49465   /* No commit or rollback needed if the program never started */
   49466   if( p->pc>=0 ){
   49467     int mrc;   /* Primary error code from p->rc */
   49468     int eStatementOp = 0;
   49469     int isSpecialError;            /* Set to true if a 'special' error */
   49470 
   49471     /* Lock all btrees used by the statement */
   49472     sqlite3VdbeMutexArrayEnter(p);
   49473 
   49474     /* Check for one of the special errors */
   49475     mrc = p->rc & 0xff;
   49476     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
   49477     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
   49478                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
   49479     if( isSpecialError ){
   49480       /* If the query was read-only, we need do no rollback at all. Otherwise,
   49481       ** proceed with the special handling.
   49482       */
   49483       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
   49484         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
   49485           eStatementOp = SAVEPOINT_ROLLBACK;
   49486         }else{
   49487           /* We are forced to roll back the active transaction. Before doing
   49488           ** so, abort any other statements this handle currently has active.
   49489           */
   49490           invalidateCursorsOnModifiedBtrees(db);
   49491           sqlite3RollbackAll(db);
   49492           sqlite3CloseSavepoints(db);
   49493           db->autoCommit = 1;
   49494         }
   49495       }
   49496     }
   49497 
   49498     /* Check for immediate foreign key violations. */
   49499     if( p->rc==SQLITE_OK ){
   49500       sqlite3VdbeCheckFk(p, 0);
   49501     }
   49502 
   49503     /* If the auto-commit flag is set and this is the only active writer
   49504     ** VM, then we do either a commit or rollback of the current transaction.
   49505     **
   49506     ** Note: This block also runs if one of the special errors handled
   49507     ** above has occurred.
   49508     */
   49509     if( !sqlite3VtabInSync(db)
   49510      && db->autoCommit
   49511      && db->writeVdbeCnt==(p->readOnly==0)
   49512     ){
   49513       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
   49514         if( sqlite3VdbeCheckFk(p, 1) ){
   49515           sqlite3BtreeMutexArrayLeave(&p->aMutex);
   49516           return SQLITE_ERROR;
   49517         }
   49518         /* The auto-commit flag is true, the vdbe program was successful
   49519         ** or hit an 'OR FAIL' constraint and there are no deferred foreign
   49520         ** key constraints to hold up the transaction. This means a commit
   49521         ** is required.  */
   49522         rc = vdbeCommit(db, p);
   49523         if( rc==SQLITE_BUSY ){
   49524           sqlite3BtreeMutexArrayLeave(&p->aMutex);
   49525           return SQLITE_BUSY;
   49526         }else if( rc!=SQLITE_OK ){
   49527           p->rc = rc;
   49528           sqlite3RollbackAll(db);
   49529         }else{
   49530           db->nDeferredCons = 0;
   49531           sqlite3CommitInternalChanges(db);
   49532         }
   49533       }else{
   49534         sqlite3RollbackAll(db);
   49535       }
   49536       db->nStatement = 0;
   49537     }else if( eStatementOp==0 ){
   49538       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
   49539         eStatementOp = SAVEPOINT_RELEASE;
   49540       }else if( p->errorAction==OE_Abort ){
   49541         eStatementOp = SAVEPOINT_ROLLBACK;
   49542       }else{
   49543         invalidateCursorsOnModifiedBtrees(db);
   49544         sqlite3RollbackAll(db);
   49545         sqlite3CloseSavepoints(db);
   49546         db->autoCommit = 1;
   49547       }
   49548     }
   49549 
   49550     /* If eStatementOp is non-zero, then a statement transaction needs to
   49551     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
   49552     ** do so. If this operation returns an error, and the current statement
   49553     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then set the error
   49554     ** code to the new value.
   49555     */
   49556     if( eStatementOp ){
   49557       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
   49558       if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
   49559         p->rc = rc;
   49560         sqlite3DbFree(db, p->zErrMsg);
   49561         p->zErrMsg = 0;
   49562       }
   49563     }
   49564 
   49565     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
   49566     ** has been rolled back, update the database connection change-counter.
   49567     */
   49568     if( p->changeCntOn ){
   49569       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
   49570         sqlite3VdbeSetChanges(db, p->nChange);
   49571       }else{
   49572         sqlite3VdbeSetChanges(db, 0);
   49573       }
   49574       p->nChange = 0;
   49575     }
   49576 
   49577     /* Rollback or commit any schema changes that occurred. */
   49578     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
   49579       sqlite3ResetInternalSchema(db, 0);
   49580       db->flags = (db->flags | SQLITE_InternChanges);
   49581     }
   49582 
   49583     /* Release the locks */
   49584     sqlite3BtreeMutexArrayLeave(&p->aMutex);
   49585   }
   49586 
   49587   /* We have successfully halted and closed the VM.  Record this fact. */
   49588   if( p->pc>=0 ){
   49589     db->activeVdbeCnt--;
   49590     if( !p->readOnly ){
   49591       db->writeVdbeCnt--;
   49592     }
   49593     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
   49594   }
   49595   p->magic = VDBE_MAGIC_HALT;
   49596   checkActiveVdbeCnt(db);
   49597   if( p->db->mallocFailed ){
   49598     p->rc = SQLITE_NOMEM;
   49599   }
   49600 
   49601   /* If the auto-commit flag is set to true, then any locks that were held
   49602   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
   49603   ** to invoke any required unlock-notify callbacks.
   49604   */
   49605   if( db->autoCommit ){
   49606     sqlite3ConnectionUnlocked(db);
   49607   }
   49608 
   49609   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
   49610   return SQLITE_OK;
   49611 }
   49612 
   49613 
   49614 /*
   49615 ** Each VDBE holds the result of the most recent sqlite3_step() call
   49616 ** in p->rc.  This routine sets that result back to SQLITE_OK.
   49617 */
   49618 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
   49619   p->rc = SQLITE_OK;
   49620 }
   49621 
   49622 /*
   49623 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
   49624 ** Write any error messages into *pzErrMsg.  Return the result code.
   49625 **
   49626 ** After this routine is run, the VDBE should be ready to be executed
   49627 ** again.
   49628 **
   49629 ** To look at it another way, this routine resets the state of the
   49630 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
   49631 ** VDBE_MAGIC_INIT.
   49632 */
   49633 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
   49634   sqlite3 *db;
   49635   db = p->db;
   49636 
   49637   /* If the VM did not run to completion or if it encountered an
   49638   ** error, then it might not have been halted properly.  So halt
   49639   ** it now.
   49640   */
   49641   sqlite3VdbeHalt(p);
   49642 
   49643   /* If the VDBE has be run even partially, then transfer the error code
   49644   ** and error message from the VDBE into the main database structure.  But
   49645   ** if the VDBE has just been set to run but has not actually executed any
   49646   ** instructions yet, leave the main database error information unchanged.
   49647   */
   49648   if( p->pc>=0 ){
   49649     if( p->zErrMsg ){
   49650       sqlite3BeginBenignMalloc();
   49651       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
   49652       sqlite3EndBenignMalloc();
   49653       db->errCode = p->rc;
   49654       sqlite3DbFree(db, p->zErrMsg);
   49655       p->zErrMsg = 0;
   49656     }else if( p->rc ){
   49657       sqlite3Error(db, p->rc, 0);
   49658     }else{
   49659       sqlite3Error(db, SQLITE_OK, 0);
   49660     }
   49661     if( p->runOnlyOnce ) p->expired = 1;
   49662   }else if( p->rc && p->expired ){
   49663     /* The expired flag was set on the VDBE before the first call
   49664     ** to sqlite3_step(). For consistency (since sqlite3_step() was
   49665     ** called), set the database error in this case as well.
   49666     */
   49667     sqlite3Error(db, p->rc, 0);
   49668     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
   49669     sqlite3DbFree(db, p->zErrMsg);
   49670     p->zErrMsg = 0;
   49671   }
   49672 
   49673   /* Reclaim all memory used by the VDBE
   49674   */
   49675   Cleanup(p);
   49676 
   49677   /* Save profiling information from this VDBE run.
   49678   */
   49679 #ifdef VDBE_PROFILE
   49680   {
   49681     FILE *out = fopen("vdbe_profile.out", "a");
   49682     if( out ){
   49683       int i;
   49684       fprintf(out, "---- ");
   49685       for(i=0; i<p->nOp; i++){
   49686         fprintf(out, "%02x", p->aOp[i].opcode);
   49687       }
   49688       fprintf(out, "\n");
   49689       for(i=0; i<p->nOp; i++){
   49690         fprintf(out, "%6d %10lld %8lld ",
   49691            p->aOp[i].cnt,
   49692            p->aOp[i].cycles,
   49693            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
   49694         );
   49695         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
   49696       }
   49697       fclose(out);
   49698     }
   49699   }
   49700 #endif
   49701   p->magic = VDBE_MAGIC_INIT;
   49702   return p->rc & db->errMask;
   49703 }
   49704 
   49705 /*
   49706 ** Clean up and delete a VDBE after execution.  Return an integer which is
   49707 ** the result code.  Write any error message text into *pzErrMsg.
   49708 */
   49709 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
   49710   int rc = SQLITE_OK;
   49711   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
   49712     rc = sqlite3VdbeReset(p);
   49713     assert( (rc & p->db->errMask)==rc );
   49714   }
   49715   sqlite3VdbeDelete(p);
   49716   return rc;
   49717 }
   49718 
   49719 /*
   49720 ** Call the destructor for each auxdata entry in pVdbeFunc for which
   49721 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
   49722 ** are always destroyed.  To destroy all auxdata entries, call this
   49723 ** routine with mask==0.
   49724 */
   49725 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
   49726   int i;
   49727   for(i=0; i<pVdbeFunc->nAux; i++){
   49728     struct AuxData *pAux = &pVdbeFunc->apAux[i];
   49729     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
   49730       if( pAux->xDelete ){
   49731         pAux->xDelete(pAux->pAux);
   49732       }
   49733       pAux->pAux = 0;
   49734     }
   49735   }
   49736 }
   49737 
   49738 /*
   49739 ** Delete an entire VDBE.
   49740 */
   49741 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
   49742   sqlite3 *db;
   49743 
   49744   if( NEVER(p==0) ) return;
   49745   db = p->db;
   49746   if( p->pPrev ){
   49747     p->pPrev->pNext = p->pNext;
   49748   }else{
   49749     assert( db->pVdbe==p );
   49750     db->pVdbe = p->pNext;
   49751   }
   49752   if( p->pNext ){
   49753     p->pNext->pPrev = p->pPrev;
   49754   }
   49755   releaseMemArray(p->aVar, p->nVar);
   49756   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
   49757   vdbeFreeOpArray(db, p->aOp, p->nOp);
   49758   sqlite3DbFree(db, p->aLabel);
   49759   sqlite3DbFree(db, p->aColName);
   49760   sqlite3DbFree(db, p->zSql);
   49761   p->magic = VDBE_MAGIC_DEAD;
   49762   sqlite3DbFree(db, p->pFree);
   49763   sqlite3DbFree(db, p);
   49764 }
   49765 
   49766 /*
   49767 ** Make sure the cursor p is ready to read or write the row to which it
   49768 ** was last positioned.  Return an error code if an OOM fault or I/O error
   49769 ** prevents us from positioning the cursor to its correct position.
   49770 **
   49771 ** If a MoveTo operation is pending on the given cursor, then do that
   49772 ** MoveTo now.  If no move is pending, check to see if the row has been
   49773 ** deleted out from under the cursor and if it has, mark the row as
   49774 ** a NULL row.
   49775 **
   49776 ** If the cursor is already pointing to the correct row and that row has
   49777 ** not been deleted out from under the cursor, then this routine is a no-op.
   49778 */
   49779 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
   49780   if( p->deferredMoveto ){
   49781     int res, rc;
   49782 #ifdef SQLITE_TEST
   49783     extern int sqlite3_search_count;
   49784 #endif
   49785     assert( p->isTable );
   49786     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
   49787     if( rc ) return rc;
   49788     p->lastRowid = p->movetoTarget;
   49789     p->rowidIsValid = ALWAYS(res==0) ?1:0;
   49790     if( NEVER(res<0) ){
   49791       rc = sqlite3BtreeNext(p->pCursor, &res);
   49792       if( rc ) return rc;
   49793     }
   49794 #ifdef SQLITE_TEST
   49795     sqlite3_search_count++;
   49796 #endif
   49797     p->deferredMoveto = 0;
   49798     p->cacheStatus = CACHE_STALE;
   49799   }else if( ALWAYS(p->pCursor) ){
   49800     int hasMoved;
   49801     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
   49802     if( rc ) return rc;
   49803     if( hasMoved ){
   49804       p->cacheStatus = CACHE_STALE;
   49805       p->nullRow = 1;
   49806     }
   49807   }
   49808   return SQLITE_OK;
   49809 }
   49810 
   49811 /*
   49812 ** The following functions:
   49813 **
   49814 ** sqlite3VdbeSerialType()
   49815 ** sqlite3VdbeSerialTypeLen()
   49816 ** sqlite3VdbeSerialLen()
   49817 ** sqlite3VdbeSerialPut()
   49818 ** sqlite3VdbeSerialGet()
   49819 **
   49820 ** encapsulate the code that serializes values for storage in SQLite
   49821 ** data and index records. Each serialized value consists of a
   49822 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
   49823 ** integer, stored as a varint.
   49824 **
   49825 ** In an SQLite index record, the serial type is stored directly before
   49826 ** the blob of data that it corresponds to. In a table record, all serial
   49827 ** types are stored at the start of the record, and the blobs of data at
   49828 ** the end. Hence these functions allow the caller to handle the
   49829 ** serial-type and data blob seperately.
   49830 **
   49831 ** The following table describes the various storage classes for data:
   49832 **
   49833 **   serial type        bytes of data      type
   49834 **   --------------     ---------------    ---------------
   49835 **      0                     0            NULL
   49836 **      1                     1            signed integer
   49837 **      2                     2            signed integer
   49838 **      3                     3            signed integer
   49839 **      4                     4            signed integer
   49840 **      5                     6            signed integer
   49841 **      6                     8            signed integer
   49842 **      7                     8            IEEE float
   49843 **      8                     0            Integer constant 0
   49844 **      9                     0            Integer constant 1
   49845 **     10,11                               reserved for expansion
   49846 **    N>=12 and even       (N-12)/2        BLOB
   49847 **    N>=13 and odd        (N-13)/2        text
   49848 **
   49849 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
   49850 ** of SQLite will not understand those serial types.
   49851 */
   49852 
   49853 /*
   49854 ** Return the serial-type for the value stored in pMem.
   49855 */
   49856 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
   49857   int flags = pMem->flags;
   49858   int n;
   49859 
   49860   if( flags&MEM_Null ){
   49861     return 0;
   49862   }
   49863   if( flags&MEM_Int ){
   49864     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
   49865 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
   49866     i64 i = pMem->u.i;
   49867     u64 u;
   49868     if( file_format>=4 && (i&1)==i ){
   49869       return 8+(u32)i;
   49870     }
   49871     u = i<0 ? -i : i;
   49872     if( u<=127 ) return 1;
   49873     if( u<=32767 ) return 2;
   49874     if( u<=8388607 ) return 3;
   49875     if( u<=2147483647 ) return 4;
   49876     if( u<=MAX_6BYTE ) return 5;
   49877     return 6;
   49878   }
   49879   if( flags&MEM_Real ){
   49880     return 7;
   49881   }
   49882   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
   49883   n = pMem->n;
   49884   if( flags & MEM_Zero ){
   49885     n += pMem->u.nZero;
   49886   }
   49887   assert( n>=0 );
   49888   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
   49889 }
   49890 
   49891 /*
   49892 ** Return the length of the data corresponding to the supplied serial-type.
   49893 */
   49894 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
   49895   if( serial_type>=12 ){
   49896     return (serial_type-12)/2;
   49897   }else{
   49898     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
   49899     return aSize[serial_type];
   49900   }
   49901 }
   49902 
   49903 /*
   49904 ** If we are on an architecture with mixed-endian floating
   49905 ** points (ex: ARM7) then swap the lower 4 bytes with the
   49906 ** upper 4 bytes.  Return the result.
   49907 **
   49908 ** For most architectures, this is a no-op.
   49909 **
   49910 ** (later):  It is reported to me that the mixed-endian problem
   49911 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
   49912 ** that early versions of GCC stored the two words of a 64-bit
   49913 ** float in the wrong order.  And that error has been propagated
   49914 ** ever since.  The blame is not necessarily with GCC, though.
   49915 ** GCC might have just copying the problem from a prior compiler.
   49916 ** I am also told that newer versions of GCC that follow a different
   49917 ** ABI get the byte order right.
   49918 **
   49919 ** Developers using SQLite on an ARM7 should compile and run their
   49920 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
   49921 ** enabled, some asserts below will ensure that the byte order of
   49922 ** floating point values is correct.
   49923 **
   49924 ** (2007-08-30)  Frank van Vugt has studied this problem closely
   49925 ** and has send his findings to the SQLite developers.  Frank
   49926 ** writes that some Linux kernels offer floating point hardware
   49927 ** emulation that uses only 32-bit mantissas instead of a full
   49928 ** 48-bits as required by the IEEE standard.  (This is the
   49929 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
   49930 ** byte swapping becomes very complicated.  To avoid problems,
   49931 ** the necessary byte swapping is carried out using a 64-bit integer
   49932 ** rather than a 64-bit float.  Frank assures us that the code here
   49933 ** works for him.  We, the developers, have no way to independently
   49934 ** verify this, but Frank seems to know what he is talking about
   49935 ** so we trust him.
   49936 */
   49937 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   49938 static u64 floatSwap(u64 in){
   49939   union {
   49940     u64 r;
   49941     u32 i[2];
   49942   } u;
   49943   u32 t;
   49944 
   49945   u.r = in;
   49946   t = u.i[0];
   49947   u.i[0] = u.i[1];
   49948   u.i[1] = t;
   49949   return u.r;
   49950 }
   49951 # define swapMixedEndianFloat(X)  X = floatSwap(X)
   49952 #else
   49953 # define swapMixedEndianFloat(X)
   49954 #endif
   49955 
   49956 /*
   49957 ** Write the serialized data blob for the value stored in pMem into
   49958 ** buf. It is assumed that the caller has allocated sufficient space.
   49959 ** Return the number of bytes written.
   49960 **
   49961 ** nBuf is the amount of space left in buf[].  nBuf must always be
   49962 ** large enough to hold the entire field.  Except, if the field is
   49963 ** a blob with a zero-filled tail, then buf[] might be just the right
   49964 ** size to hold everything except for the zero-filled tail.  If buf[]
   49965 ** is only big enough to hold the non-zero prefix, then only write that
   49966 ** prefix into buf[].  But if buf[] is large enough to hold both the
   49967 ** prefix and the tail then write the prefix and set the tail to all
   49968 ** zeros.
   49969 **
   49970 ** Return the number of bytes actually written into buf[].  The number
   49971 ** of bytes in the zero-filled tail is included in the return value only
   49972 ** if those bytes were zeroed in buf[].
   49973 */
   49974 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
   49975   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
   49976   u32 len;
   49977 
   49978   /* Integer and Real */
   49979   if( serial_type<=7 && serial_type>0 ){
   49980     u64 v;
   49981     u32 i;
   49982     if( serial_type==7 ){
   49983       assert( sizeof(v)==sizeof(pMem->r) );
   49984       memcpy(&v, &pMem->r, sizeof(v));
   49985       swapMixedEndianFloat(v);
   49986     }else{
   49987       v = pMem->u.i;
   49988     }
   49989     len = i = sqlite3VdbeSerialTypeLen(serial_type);
   49990     assert( len<=(u32)nBuf );
   49991     while( i-- ){
   49992       buf[i] = (u8)(v&0xFF);
   49993       v >>= 8;
   49994     }
   49995     return len;
   49996   }
   49997 
   49998   /* String or blob */
   49999   if( serial_type>=12 ){
   50000     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
   50001              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
   50002     assert( pMem->n<=nBuf );
   50003     len = pMem->n;
   50004     memcpy(buf, pMem->z, len);
   50005     if( pMem->flags & MEM_Zero ){
   50006       len += pMem->u.nZero;
   50007       assert( nBuf>=0 );
   50008       if( len > (u32)nBuf ){
   50009         len = (u32)nBuf;
   50010       }
   50011       memset(&buf[pMem->n], 0, len-pMem->n);
   50012     }
   50013     return len;
   50014   }
   50015 
   50016   /* NULL or constants 0 or 1 */
   50017   return 0;
   50018 }
   50019 
   50020 /*
   50021 ** Deserialize the data blob pointed to by buf as serial type serial_type
   50022 ** and store the result in pMem.  Return the number of bytes read.
   50023 */
   50024 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
   50025   const unsigned char *buf,     /* Buffer to deserialize from */
   50026   u32 serial_type,              /* Serial type to deserialize */
   50027   Mem *pMem                     /* Memory cell to write value into */
   50028 ){
   50029   switch( serial_type ){
   50030     case 10:   /* Reserved for future use */
   50031     case 11:   /* Reserved for future use */
   50032     case 0: {  /* NULL */
   50033       pMem->flags = MEM_Null;
   50034       break;
   50035     }
   50036     case 1: { /* 1-byte signed integer */
   50037       pMem->u.i = (signed char)buf[0];
   50038       pMem->flags = MEM_Int;
   50039       return 1;
   50040     }
   50041     case 2: { /* 2-byte signed integer */
   50042       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
   50043       pMem->flags = MEM_Int;
   50044       return 2;
   50045     }
   50046     case 3: { /* 3-byte signed integer */
   50047       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
   50048       pMem->flags = MEM_Int;
   50049       return 3;
   50050     }
   50051     case 4: { /* 4-byte signed integer */
   50052       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
   50053       pMem->flags = MEM_Int;
   50054       return 4;
   50055     }
   50056     case 5: { /* 6-byte signed integer */
   50057       u64 x = (((signed char)buf[0])<<8) | buf[1];
   50058       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
   50059       x = (x<<32) | y;
   50060       pMem->u.i = *(i64*)&x;
   50061       pMem->flags = MEM_Int;
   50062       return 6;
   50063     }
   50064     case 6:   /* 8-byte signed integer */
   50065     case 7: { /* IEEE floating point */
   50066       u64 x;
   50067       u32 y;
   50068 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
   50069       /* Verify that integers and floating point values use the same
   50070       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
   50071       ** defined that 64-bit floating point values really are mixed
   50072       ** endian.
   50073       */
   50074       static const u64 t1 = ((u64)0x3ff00000)<<32;
   50075       static const double r1 = 1.0;
   50076       u64 t2 = t1;
   50077       swapMixedEndianFloat(t2);
   50078       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
   50079 #endif
   50080 
   50081       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
   50082       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
   50083       x = (x<<32) | y;
   50084       if( serial_type==6 ){
   50085         pMem->u.i = *(i64*)&x;
   50086         pMem->flags = MEM_Int;
   50087       }else{
   50088         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
   50089         swapMixedEndianFloat(x);
   50090         memcpy(&pMem->r, &x, sizeof(x));
   50091         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
   50092       }
   50093       return 8;
   50094     }
   50095     case 8:    /* Integer 0 */
   50096     case 9: {  /* Integer 1 */
   50097       pMem->u.i = serial_type-8;
   50098       pMem->flags = MEM_Int;
   50099       return 0;
   50100     }
   50101     default: {
   50102       u32 len = (serial_type-12)/2;
   50103       pMem->z = (char *)buf;
   50104       pMem->n = len;
   50105       pMem->xDel = 0;
   50106       if( serial_type&0x01 ){
   50107         pMem->flags = MEM_Str | MEM_Ephem;
   50108       }else{
   50109         pMem->flags = MEM_Blob | MEM_Ephem;
   50110       }
   50111       return len;
   50112     }
   50113   }
   50114   return 0;
   50115 }
   50116 
   50117 
   50118 /*
   50119 ** Given the nKey-byte encoding of a record in pKey[], parse the
   50120 ** record into a UnpackedRecord structure.  Return a pointer to
   50121 ** that structure.
   50122 **
   50123 ** The calling function might provide szSpace bytes of memory
   50124 ** space at pSpace.  This space can be used to hold the returned
   50125 ** VDbeParsedRecord structure if it is large enough.  If it is
   50126 ** not big enough, space is obtained from sqlite3_malloc().
   50127 **
   50128 ** The returned structure should be closed by a call to
   50129 ** sqlite3VdbeDeleteUnpackedRecord().
   50130 */
   50131 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
   50132   KeyInfo *pKeyInfo,     /* Information about the record format */
   50133   int nKey,              /* Size of the binary record */
   50134   const void *pKey,      /* The binary record */
   50135   char *pSpace,          /* Unaligned space available to hold the object */
   50136   int szSpace            /* Size of pSpace[] in bytes */
   50137 ){
   50138   const unsigned char *aKey = (const unsigned char *)pKey;
   50139   UnpackedRecord *p;  /* The unpacked record that we will return */
   50140   int nByte;          /* Memory space needed to hold p, in bytes */
   50141   int d;
   50142   u32 idx;
   50143   u16 u;              /* Unsigned loop counter */
   50144   u32 szHdr;
   50145   Mem *pMem;
   50146   int nOff;           /* Increase pSpace by this much to 8-byte align it */
   50147 
   50148   /*
   50149   ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
   50150   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
   50151   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
   50152   */
   50153   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
   50154   pSpace += nOff;
   50155   szSpace -= nOff;
   50156   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
   50157   if( nByte>szSpace ){
   50158     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
   50159     if( p==0 ) return 0;
   50160     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
   50161   }else{
   50162     p = (UnpackedRecord*)pSpace;
   50163     p->flags = UNPACKED_NEED_DESTROY;
   50164   }
   50165   p->pKeyInfo = pKeyInfo;
   50166   p->nField = pKeyInfo->nField + 1;
   50167   p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
   50168   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   50169   idx = getVarint32(aKey, szHdr);
   50170   d = szHdr;
   50171   u = 0;
   50172   while( idx<szHdr && u<p->nField && d<=nKey ){
   50173     u32 serial_type;
   50174 
   50175     idx += getVarint32(&aKey[idx], serial_type);
   50176     pMem->enc = pKeyInfo->enc;
   50177     pMem->db = pKeyInfo->db;
   50178     pMem->flags = 0;
   50179     pMem->zMalloc = 0;
   50180     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
   50181     pMem++;
   50182     u++;
   50183   }
   50184   assert( u<=pKeyInfo->nField + 1 );
   50185   p->nField = u;
   50186   return (void*)p;
   50187 }
   50188 
   50189 /*
   50190 ** This routine destroys a UnpackedRecord object.
   50191 */
   50192 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
   50193   int i;
   50194   Mem *pMem;
   50195 
   50196   assert( p!=0 );
   50197   assert( p->flags & UNPACKED_NEED_DESTROY );
   50198   for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
   50199     /* The unpacked record is always constructed by the
   50200     ** sqlite3VdbeUnpackRecord() function above, which makes all
   50201     ** strings and blobs static.  And none of the elements are
   50202     ** ever transformed, so there is never anything to delete.
   50203     */
   50204     if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
   50205   }
   50206   if( p->flags & UNPACKED_NEED_FREE ){
   50207     sqlite3DbFree(p->pKeyInfo->db, p);
   50208   }
   50209 }
   50210 
   50211 /*
   50212 ** This function compares the two table rows or index records
   50213 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
   50214 ** or positive integer if key1 is less than, equal to or
   50215 ** greater than key2.  The {nKey1, pKey1} key must be a blob
   50216 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
   50217 ** key must be a parsed key such as obtained from
   50218 ** sqlite3VdbeParseRecord.
   50219 **
   50220 ** Key1 and Key2 do not have to contain the same number of fields.
   50221 ** The key with fewer fields is usually compares less than the
   50222 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
   50223 ** and the common prefixes are equal, then key1 is less than key2.
   50224 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
   50225 ** equal, then the keys are considered to be equal and
   50226 ** the parts beyond the common prefix are ignored.
   50227 **
   50228 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
   50229 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
   50230 ** an index key, and thus ends with a rowid value.  The last byte
   50231 ** of the header will therefore be the serial type of the rowid:
   50232 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
   50233 ** The serial type of the final rowid will always be a single byte.
   50234 ** By ignoring this last byte of the header, we force the comparison
   50235 ** to ignore the rowid at the end of key1.
   50236 */
   50237 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
   50238   int nKey1, const void *pKey1, /* Left key */
   50239   UnpackedRecord *pPKey2        /* Right key */
   50240 ){
   50241   int d1;            /* Offset into aKey[] of next data element */
   50242   u32 idx1;          /* Offset into aKey[] of next header element */
   50243   u32 szHdr1;        /* Number of bytes in header */
   50244   int i = 0;
   50245   int nField;
   50246   int rc = 0;
   50247   const unsigned char *aKey1 = (const unsigned char *)pKey1;
   50248   KeyInfo *pKeyInfo;
   50249   Mem mem1;
   50250 
   50251   pKeyInfo = pPKey2->pKeyInfo;
   50252   mem1.enc = pKeyInfo->enc;
   50253   mem1.db = pKeyInfo->db;
   50254   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
   50255   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
   50256 
   50257   /* Compilers may complain that mem1.u.i is potentially uninitialized.
   50258   ** We could initialize it, as shown here, to silence those complaints.
   50259   ** But in fact, mem1.u.i will never actually be used initialized, and doing
   50260   ** the unnecessary initialization has a measurable negative performance
   50261   ** impact, since this routine is a very high runner.  And so, we choose
   50262   ** to ignore the compiler warnings and leave this variable uninitialized.
   50263   */
   50264   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
   50265 
   50266   idx1 = getVarint32(aKey1, szHdr1);
   50267   d1 = szHdr1;
   50268   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
   50269     szHdr1--;
   50270   }
   50271   nField = pKeyInfo->nField;
   50272   while( idx1<szHdr1 && i<pPKey2->nField ){
   50273     u32 serial_type1;
   50274 
   50275     /* Read the serial types for the next element in each key. */
   50276     idx1 += getVarint32( aKey1+idx1, serial_type1 );
   50277     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
   50278 
   50279     /* Extract the values to be compared.
   50280     */
   50281     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
   50282 
   50283     /* Do the comparison
   50284     */
   50285     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
   50286                            i<nField ? pKeyInfo->aColl[i] : 0);
   50287     if( rc!=0 ){
   50288       assert( mem1.zMalloc==0 );  /* See comment below */
   50289 
   50290       /* Invert the result if we are using DESC sort order. */
   50291       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
   50292         rc = -rc;
   50293       }
   50294 
   50295       /* If the PREFIX_SEARCH flag is set and all fields except the final
   50296       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
   50297       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
   50298       ** This is used by the OP_IsUnique opcode.
   50299       */
   50300       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
   50301         assert( idx1==szHdr1 && rc );
   50302         assert( mem1.flags & MEM_Int );
   50303         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
   50304         pPKey2->rowid = mem1.u.i;
   50305       }
   50306 
   50307       return rc;
   50308     }
   50309     i++;
   50310   }
   50311 
   50312   /* No memory allocation is ever used on mem1.  Prove this using
   50313   ** the following assert().  If the assert() fails, it indicates a
   50314   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
   50315   */
   50316   assert( mem1.zMalloc==0 );
   50317 
   50318   /* rc==0 here means that one of the keys ran out of fields and
   50319   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
   50320   ** flag is set, then break the tie by treating key2 as larger.
   50321   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
   50322   ** are considered to be equal.  Otherwise, the longer key is the
   50323   ** larger.  As it happens, the pPKey2 will always be the longer
   50324   ** if there is a difference.
   50325   */
   50326   assert( rc==0 );
   50327   if( pPKey2->flags & UNPACKED_INCRKEY ){
   50328     rc = -1;
   50329   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
   50330     /* Leave rc==0 */
   50331   }else if( idx1<szHdr1 ){
   50332     rc = 1;
   50333   }
   50334   return rc;
   50335 }
   50336 
   50337 
   50338 /*
   50339 ** pCur points at an index entry created using the OP_MakeRecord opcode.
   50340 ** Read the rowid (the last field in the record) and store it in *rowid.
   50341 ** Return SQLITE_OK if everything works, or an error code otherwise.
   50342 **
   50343 ** pCur might be pointing to text obtained from a corrupt database file.
   50344 ** So the content cannot be trusted.  Do appropriate checks on the content.
   50345 */
   50346 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
   50347   i64 nCellKey = 0;
   50348   int rc;
   50349   u32 szHdr;        /* Size of the header */
   50350   u32 typeRowid;    /* Serial type of the rowid */
   50351   u32 lenRowid;     /* Size of the rowid */
   50352   Mem m, v;
   50353 
   50354   UNUSED_PARAMETER(db);
   50355 
   50356   /* Get the size of the index entry.  Only indices entries of less
   50357   ** than 2GiB are support - anything large must be database corruption.
   50358   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
   50359   ** this code can safely assume that nCellKey is 32-bits
   50360   */
   50361   assert( sqlite3BtreeCursorIsValid(pCur) );
   50362   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
   50363   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
   50364   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
   50365 
   50366   /* Read in the complete content of the index entry */
   50367   memset(&m, 0, sizeof(m));
   50368   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
   50369   if( rc ){
   50370     return rc;
   50371   }
   50372 
   50373   /* The index entry must begin with a header size */
   50374   (void)getVarint32((u8*)m.z, szHdr);
   50375   testcase( szHdr==3 );
   50376   testcase( szHdr==m.n );
   50377   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
   50378     goto idx_rowid_corruption;
   50379   }
   50380 
   50381   /* The last field of the index should be an integer - the ROWID.
   50382   ** Verify that the last entry really is an integer. */
   50383   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
   50384   testcase( typeRowid==1 );
   50385   testcase( typeRowid==2 );
   50386   testcase( typeRowid==3 );
   50387   testcase( typeRowid==4 );
   50388   testcase( typeRowid==5 );
   50389   testcase( typeRowid==6 );
   50390   testcase( typeRowid==8 );
   50391   testcase( typeRowid==9 );
   50392   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
   50393     goto idx_rowid_corruption;
   50394   }
   50395   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
   50396   testcase( (u32)m.n==szHdr+lenRowid );
   50397   if( unlikely((u32)m.n<szHdr+lenRowid) ){
   50398     goto idx_rowid_corruption;
   50399   }
   50400 
   50401   /* Fetch the integer off the end of the index record */
   50402   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
   50403   *rowid = v.u.i;
   50404   sqlite3VdbeMemRelease(&m);
   50405   return SQLITE_OK;
   50406 
   50407   /* Jump here if database corruption is detected after m has been
   50408   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
   50409 idx_rowid_corruption:
   50410   testcase( m.zMalloc!=0 );
   50411   sqlite3VdbeMemRelease(&m);
   50412   return SQLITE_CORRUPT_BKPT;
   50413 }
   50414 
   50415 /*
   50416 ** Compare the key of the index entry that cursor pC is pointing to against
   50417 ** the key string in pUnpacked.  Write into *pRes a number
   50418 ** that is negative, zero, or positive if pC is less than, equal to,
   50419 ** or greater than pUnpacked.  Return SQLITE_OK on success.
   50420 **
   50421 ** pUnpacked is either created without a rowid or is truncated so that it
   50422 ** omits the rowid at the end.  The rowid at the end of the index entry
   50423 ** is ignored as well.  Hence, this routine only compares the prefixes
   50424 ** of the keys prior to the final rowid, not the entire key.
   50425 */
   50426 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
   50427   VdbeCursor *pC,             /* The cursor to compare against */
   50428   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
   50429   int *res                    /* Write the comparison result here */
   50430 ){
   50431   i64 nCellKey = 0;
   50432   int rc;
   50433   BtCursor *pCur = pC->pCursor;
   50434   Mem m;
   50435 
   50436   assert( sqlite3BtreeCursorIsValid(pCur) );
   50437   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
   50438   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
   50439   /* nCellKey will always be between 0 and 0xffffffff because of the say
   50440   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
   50441   if( nCellKey<=0 || nCellKey>0x7fffffff ){
   50442     *res = 0;
   50443     return SQLITE_CORRUPT_BKPT;
   50444   }
   50445   memset(&m, 0, sizeof(m));
   50446   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
   50447   if( rc ){
   50448     return rc;
   50449   }
   50450   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
   50451   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
   50452   sqlite3VdbeMemRelease(&m);
   50453   return SQLITE_OK;
   50454 }
   50455 
   50456 /*
   50457 ** This routine sets the value to be returned by subsequent calls to
   50458 ** sqlite3_changes() on the database handle 'db'.
   50459 */
   50460 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
   50461   assert( sqlite3_mutex_held(db->mutex) );
   50462   db->nChange = nChange;
   50463   db->nTotalChange += nChange;
   50464 }
   50465 
   50466 /*
   50467 ** Set a flag in the vdbe to update the change counter when it is finalised
   50468 ** or reset.
   50469 */
   50470 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
   50471   v->changeCntOn = 1;
   50472 }
   50473 
   50474 /*
   50475 ** Mark every prepared statement associated with a database connection
   50476 ** as expired.
   50477 **
   50478 ** An expired statement means that recompilation of the statement is
   50479 ** recommend.  Statements expire when things happen that make their
   50480 ** programs obsolete.  Removing user-defined functions or collating
   50481 ** sequences, or changing an authorization function are the types of
   50482 ** things that make prepared statements obsolete.
   50483 */
   50484 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
   50485   Vdbe *p;
   50486   for(p = db->pVdbe; p; p=p->pNext){
   50487     p->expired = 1;
   50488   }
   50489 }
   50490 
   50491 /*
   50492 ** Return the database associated with the Vdbe.
   50493 */
   50494 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
   50495   return v->db;
   50496 }
   50497 
   50498 /*
   50499 ** Return a pointer to an sqlite3_value structure containing the value bound
   50500 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
   50501 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
   50502 ** constants) to the value before returning it.
   50503 **
   50504 ** The returned value must be freed by the caller using sqlite3ValueFree().
   50505 */
   50506 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
   50507   assert( iVar>0 );
   50508   if( v ){
   50509     Mem *pMem = &v->aVar[iVar-1];
   50510     if( 0==(pMem->flags & MEM_Null) ){
   50511       sqlite3_value *pRet = sqlite3ValueNew(v->db);
   50512       if( pRet ){
   50513         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
   50514         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
   50515         sqlite3VdbeMemStoreType((Mem *)pRet);
   50516       }
   50517       return pRet;
   50518     }
   50519   }
   50520   return 0;
   50521 }
   50522 
   50523 /*
   50524 ** Configure SQL variable iVar so that binding a new value to it signals
   50525 ** to sqlite3_reoptimize() that re-preparing the statement may result
   50526 ** in a better query plan.
   50527 */
   50528 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
   50529   assert( iVar>0 );
   50530   if( iVar>32 ){
   50531     v->expmask = 0xffffffff;
   50532   }else{
   50533     v->expmask |= ((u32)1 << (iVar-1));
   50534   }
   50535 }
   50536 
   50537 /************** End of vdbeaux.c *********************************************/
   50538 /************** Begin file vdbeapi.c *****************************************/
   50539 /*
   50540 ** 2004 May 26
   50541 **
   50542 ** The author disclaims copyright to this source code.  In place of
   50543 ** a legal notice, here is a blessing:
   50544 **
   50545 **    May you do good and not evil.
   50546 **    May you find forgiveness for yourself and forgive others.
   50547 **    May you share freely, never taking more than you give.
   50548 **
   50549 *************************************************************************
   50550 **
   50551 ** This file contains code use to implement APIs that are part of the
   50552 ** VDBE.
   50553 */
   50554 
   50555 #ifndef SQLITE_OMIT_DEPRECATED
   50556 /*
   50557 ** Return TRUE (non-zero) of the statement supplied as an argument needs
   50558 ** to be recompiled.  A statement needs to be recompiled whenever the
   50559 ** execution environment changes in a way that would alter the program
   50560 ** that sqlite3_prepare() generates.  For example, if new functions or
   50561 ** collating sequences are registered or if an authorizer function is
   50562 ** added or changed.
   50563 */
   50564 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
   50565   Vdbe *p = (Vdbe*)pStmt;
   50566   return p==0 || p->expired;
   50567 }
   50568 #endif
   50569 
   50570 /*
   50571 ** Check on a Vdbe to make sure it has not been finalized.  Log
   50572 ** an error and return true if it has been finalized (or is otherwise
   50573 ** invalid).  Return false if it is ok.
   50574 */
   50575 static int vdbeSafety(Vdbe *p){
   50576   if( p->db==0 ){
   50577     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
   50578     return 1;
   50579   }else{
   50580     return 0;
   50581   }
   50582 }
   50583 static int vdbeSafetyNotNull(Vdbe *p){
   50584   if( p==0 ){
   50585     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
   50586     return 1;
   50587   }else{
   50588     return vdbeSafety(p);
   50589   }
   50590 }
   50591 
   50592 /*
   50593 ** The following routine destroys a virtual machine that is created by
   50594 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
   50595 ** success/failure code that describes the result of executing the virtual
   50596 ** machine.
   50597 **
   50598 ** This routine sets the error code and string returned by
   50599 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
   50600 */
   50601 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
   50602   int rc;
   50603   if( pStmt==0 ){
   50604     rc = SQLITE_OK;
   50605   }else{
   50606     Vdbe *v = (Vdbe*)pStmt;
   50607     sqlite3 *db = v->db;
   50608 #if SQLITE_THREADSAFE
   50609     sqlite3_mutex *mutex;
   50610 #endif
   50611     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
   50612 #if SQLITE_THREADSAFE
   50613     mutex = v->db->mutex;
   50614 #endif
   50615     sqlite3_mutex_enter(mutex);
   50616     rc = sqlite3VdbeFinalize(v);
   50617     rc = sqlite3ApiExit(db, rc);
   50618     sqlite3_mutex_leave(mutex);
   50619   }
   50620   return rc;
   50621 }
   50622 
   50623 /*
   50624 ** Terminate the current execution of an SQL statement and reset it
   50625 ** back to its starting state so that it can be reused. A success code from
   50626 ** the prior execution is returned.
   50627 **
   50628 ** This routine sets the error code and string returned by
   50629 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
   50630 */
   50631 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
   50632   int rc;
   50633   if( pStmt==0 ){
   50634     rc = SQLITE_OK;
   50635   }else{
   50636     Vdbe *v = (Vdbe*)pStmt;
   50637     sqlite3_mutex_enter(v->db->mutex);
   50638     rc = sqlite3VdbeReset(v);
   50639     sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
   50640     assert( (rc & (v->db->errMask))==rc );
   50641     rc = sqlite3ApiExit(v->db, rc);
   50642     sqlite3_mutex_leave(v->db->mutex);
   50643   }
   50644   return rc;
   50645 }
   50646 
   50647 /*
   50648 ** Set all the parameters in the compiled SQL statement to NULL.
   50649 */
   50650 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
   50651   int i;
   50652   int rc = SQLITE_OK;
   50653   Vdbe *p = (Vdbe*)pStmt;
   50654 #if SQLITE_THREADSAFE
   50655   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
   50656 #endif
   50657   sqlite3_mutex_enter(mutex);
   50658   for(i=0; i<p->nVar; i++){
   50659     sqlite3VdbeMemRelease(&p->aVar[i]);
   50660     p->aVar[i].flags = MEM_Null;
   50661   }
   50662   if( p->isPrepareV2 && p->expmask ){
   50663     p->expired = 1;
   50664   }
   50665   sqlite3_mutex_leave(mutex);
   50666   return rc;
   50667 }
   50668 
   50669 
   50670 /**************************** sqlite3_value_  *******************************
   50671 ** The following routines extract information from a Mem or sqlite3_value
   50672 ** structure.
   50673 */
   50674 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
   50675   Mem *p = (Mem*)pVal;
   50676   if( p->flags & (MEM_Blob|MEM_Str) ){
   50677     sqlite3VdbeMemExpandBlob(p);
   50678     p->flags &= ~MEM_Str;
   50679     p->flags |= MEM_Blob;
   50680     return p->z;
   50681   }else{
   50682     return sqlite3_value_text(pVal);
   50683   }
   50684 }
   50685 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
   50686   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
   50687 }
   50688 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
   50689   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
   50690 }
   50691 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
   50692   return sqlite3VdbeRealValue((Mem*)pVal);
   50693 }
   50694 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
   50695   return (int)sqlite3VdbeIntValue((Mem*)pVal);
   50696 }
   50697 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
   50698   return sqlite3VdbeIntValue((Mem*)pVal);
   50699 }
   50700 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
   50701   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
   50702 }
   50703 #ifndef SQLITE_OMIT_UTF16
   50704 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
   50705   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
   50706 }
   50707 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
   50708   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
   50709 }
   50710 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
   50711   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
   50712 }
   50713 #endif /* SQLITE_OMIT_UTF16 */
   50714 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
   50715   return pVal->type;
   50716 }
   50717 
   50718 /**************************** sqlite3_result_  *******************************
   50719 ** The following routines are used by user-defined functions to specify
   50720 ** the function result.
   50721 **
   50722 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
   50723 ** result as a string or blob but if the string or blob is too large, it
   50724 ** then sets the error code to SQLITE_TOOBIG
   50725 */
   50726 static void setResultStrOrError(
   50727   sqlite3_context *pCtx,  /* Function context */
   50728   const char *z,          /* String pointer */
   50729   int n,                  /* Bytes in string, or negative */
   50730   u8 enc,                 /* Encoding of z.  0 for BLOBs */
   50731   void (*xDel)(void*)     /* Destructor function */
   50732 ){
   50733   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
   50734     sqlite3_result_error_toobig(pCtx);
   50735   }
   50736 }
   50737 SQLITE_API void sqlite3_result_blob(
   50738   sqlite3_context *pCtx,
   50739   const void *z,
   50740   int n,
   50741   void (*xDel)(void *)
   50742 ){
   50743   assert( n>=0 );
   50744   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   50745   setResultStrOrError(pCtx, z, n, 0, xDel);
   50746 }
   50747 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
   50748   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   50749   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
   50750 }
   50751 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
   50752   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   50753   pCtx->isError = SQLITE_ERROR;
   50754   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
   50755 }
   50756 #ifndef SQLITE_OMIT_UTF16
   50757 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
   50758   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   50759   pCtx->isError = SQLITE_ERROR;
   50760   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
   50761 }
   50762 #endif
   50763 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
   50764   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   50765   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
   50766 }
   50767 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
   50768   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   50769   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
   50770 }
   50771 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
   50772   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   50773   sqlite3VdbeMemSetNull(&pCtx->s);
   50774 }
   50775 SQLITE_API void sqlite3_result_text(
   50776   sqlite3_context *pCtx,
   50777   const char *z,
   50778   int n,
   50779   void (*xDel)(void *)
   50780 ){
   50781   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   50782   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
   50783 }
   50784 #ifndef SQLITE_OMIT_UTF16
   50785 SQLITE_API void sqlite3_result_text16(
   50786   sqlite3_context *pCtx,
   50787   const void *z,
   50788   int n,
   50789   void (*xDel)(void *)
   50790 ){
   50791   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   50792   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
   50793 }
   50794 SQLITE_API void sqlite3_result_text16be(
   50795   sqlite3_context *pCtx,
   50796   const void *z,
   50797   int n,
   50798   void (*xDel)(void *)
   50799 ){
   50800   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   50801   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
   50802 }
   50803 SQLITE_API void sqlite3_result_text16le(
   50804   sqlite3_context *pCtx,
   50805   const void *z,
   50806   int n,
   50807   void (*xDel)(void *)
   50808 ){
   50809   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   50810   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
   50811 }
   50812 #endif /* SQLITE_OMIT_UTF16 */
   50813 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
   50814   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   50815   sqlite3VdbeMemCopy(&pCtx->s, pValue);
   50816 }
   50817 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
   50818   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   50819   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
   50820 }
   50821 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
   50822   pCtx->isError = errCode;
   50823   if( pCtx->s.flags & MEM_Null ){
   50824     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
   50825                          SQLITE_UTF8, SQLITE_STATIC);
   50826   }
   50827 }
   50828 
   50829 /* Force an SQLITE_TOOBIG error. */
   50830 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
   50831   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   50832   pCtx->isError = SQLITE_TOOBIG;
   50833   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
   50834                        SQLITE_UTF8, SQLITE_STATIC);
   50835 }
   50836 
   50837 /* An SQLITE_NOMEM error. */
   50838 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
   50839   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   50840   sqlite3VdbeMemSetNull(&pCtx->s);
   50841   pCtx->isError = SQLITE_NOMEM;
   50842   pCtx->s.db->mallocFailed = 1;
   50843 }
   50844 
   50845 /*
   50846 ** Execute the statement pStmt, either until a row of data is ready, the
   50847 ** statement is completely executed or an error occurs.
   50848 **
   50849 ** This routine implements the bulk of the logic behind the sqlite_step()
   50850 ** API.  The only thing omitted is the automatic recompile if a
   50851 ** schema change has occurred.  That detail is handled by the
   50852 ** outer sqlite3_step() wrapper procedure.
   50853 */
   50854 static int sqlite3Step(Vdbe *p){
   50855   sqlite3 *db;
   50856   int rc;
   50857 
   50858   assert(p);
   50859   if( p->magic!=VDBE_MAGIC_RUN ){
   50860     sqlite3_log(SQLITE_MISUSE,
   50861           "attempt to step a halted statement: [%s]", p->zSql);
   50862     return SQLITE_MISUSE_BKPT;
   50863   }
   50864 
   50865   /* Assert that malloc() has not failed */
   50866   db = p->db;
   50867   if( db->mallocFailed ){
   50868     return SQLITE_NOMEM;
   50869   }
   50870 
   50871   if( p->pc<=0 && p->expired ){
   50872     if( p->rc==SQLITE_OK ){
   50873       p->rc = SQLITE_SCHEMA;
   50874     }
   50875     rc = SQLITE_ERROR;
   50876     goto end_of_step;
   50877   }
   50878   if( p->pc<0 ){
   50879     /* If there are no other statements currently running, then
   50880     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
   50881     ** from interrupting a statement that has not yet started.
   50882     */
   50883     if( db->activeVdbeCnt==0 ){
   50884       db->u1.isInterrupted = 0;
   50885     }
   50886 
   50887     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
   50888 
   50889 #ifndef SQLITE_OMIT_TRACE
   50890     if( db->xProfile && !db->init.busy ){
   50891       double rNow;
   50892       sqlite3OsCurrentTime(db->pVfs, &rNow);
   50893       p->startTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
   50894     }
   50895 #endif
   50896 
   50897     db->activeVdbeCnt++;
   50898     if( p->readOnly==0 ) db->writeVdbeCnt++;
   50899     p->pc = 0;
   50900   }
   50901 #ifndef SQLITE_OMIT_EXPLAIN
   50902   if( p->explain ){
   50903     rc = sqlite3VdbeList(p);
   50904   }else
   50905 #endif /* SQLITE_OMIT_EXPLAIN */
   50906   {
   50907     rc = sqlite3VdbeExec(p);
   50908   }
   50909 
   50910 #ifndef SQLITE_OMIT_TRACE
   50911   /* Invoke the profile callback if there is one
   50912   */
   50913   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
   50914     double rNow;
   50915     u64 elapseTime;
   50916 
   50917     sqlite3OsCurrentTime(db->pVfs, &rNow);
   50918     elapseTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
   50919     elapseTime -= p->startTime;
   50920     db->xProfile(db->pProfileArg, p->zSql, elapseTime);
   50921   }
   50922 #endif
   50923 
   50924   db->errCode = rc;
   50925   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
   50926     p->rc = SQLITE_NOMEM;
   50927   }
   50928 end_of_step:
   50929   /* At this point local variable rc holds the value that should be
   50930   ** returned if this statement was compiled using the legacy
   50931   ** sqlite3_prepare() interface. According to the docs, this can only
   50932   ** be one of the values in the first assert() below. Variable p->rc
   50933   ** contains the value that would be returned if sqlite3_finalize()
   50934   ** were called on statement p.
   50935   */
   50936   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
   50937        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
   50938   );
   50939   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
   50940   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
   50941     /* If this statement was prepared using sqlite3_prepare_v2(), and an
   50942     ** error has occured, then return the error code in p->rc to the
   50943     ** caller. Set the error code in the database handle to the same value.
   50944     */
   50945     rc = db->errCode = p->rc;
   50946   }
   50947   return (rc&db->errMask);
   50948 }
   50949 
   50950 /*
   50951 ** This is the top-level implementation of sqlite3_step().  Call
   50952 ** sqlite3Step() to do most of the work.  If a schema error occurs,
   50953 ** call sqlite3Reprepare() and try again.
   50954 */
   50955 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
   50956   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
   50957   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
   50958   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
   50959   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
   50960   sqlite3 *db;             /* The database connection */
   50961 
   50962   if( vdbeSafetyNotNull(v) ){
   50963     return SQLITE_MISUSE_BKPT;
   50964   }
   50965   db = v->db;
   50966   sqlite3_mutex_enter(db->mutex);
   50967   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
   50968          && cnt++ < 5
   50969          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
   50970     sqlite3_reset(pStmt);
   50971     v->expired = 0;
   50972   }
   50973   if( rc2!=SQLITE_OK && v->isPrepareV2 && db->pErr ){
   50974     /* This case occurs after failing to recompile an sql statement.
   50975     ** The error message from the SQL compiler has already been loaded
   50976     ** into the database handle. This block copies the error message
   50977     ** from the database handle into the statement and sets the statement
   50978     ** program counter to 0 to ensure that when the statement is
   50979     ** finalized or reset the parser error message is available via
   50980     ** sqlite3_errmsg() and sqlite3_errcode().
   50981     */
   50982     const char *zErr = (const char *)sqlite3_value_text(db->pErr);
   50983     sqlite3DbFree(db, v->zErrMsg);
   50984     if( !db->mallocFailed ){
   50985       v->zErrMsg = sqlite3DbStrDup(db, zErr);
   50986       v->rc = rc2;
   50987     } else {
   50988       v->zErrMsg = 0;
   50989       v->rc = rc = SQLITE_NOMEM;
   50990     }
   50991   }
   50992   rc = sqlite3ApiExit(db, rc);
   50993   sqlite3_mutex_leave(db->mutex);
   50994   return rc;
   50995 }
   50996 
   50997 /*
   50998 ** Extract the user data from a sqlite3_context structure and return a
   50999 ** pointer to it.
   51000 */
   51001 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
   51002   assert( p && p->pFunc );
   51003   return p->pFunc->pUserData;
   51004 }
   51005 
   51006 /*
   51007 ** Extract the user data from a sqlite3_context structure and return a
   51008 ** pointer to it.
   51009 */
   51010 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
   51011   assert( p && p->pFunc );
   51012   return p->s.db;
   51013 }
   51014 
   51015 /*
   51016 ** The following is the implementation of an SQL function that always
   51017 ** fails with an error message stating that the function is used in the
   51018 ** wrong context.  The sqlite3_overload_function() API might construct
   51019 ** SQL function that use this routine so that the functions will exist
   51020 ** for name resolution but are actually overloaded by the xFindFunction
   51021 ** method of virtual tables.
   51022 */
   51023 SQLITE_PRIVATE void sqlite3InvalidFunction(
   51024   sqlite3_context *context,  /* The function calling context */
   51025   int NotUsed,               /* Number of arguments to the function */
   51026   sqlite3_value **NotUsed2   /* Value of each argument */
   51027 ){
   51028   const char *zName = context->pFunc->zName;
   51029   char *zErr;
   51030   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   51031   zErr = sqlite3_mprintf(
   51032       "unable to use function %s in the requested context", zName);
   51033   sqlite3_result_error(context, zErr, -1);
   51034   sqlite3_free(zErr);
   51035 }
   51036 
   51037 /*
   51038 ** Allocate or return the aggregate context for a user function.  A new
   51039 ** context is allocated on the first call.  Subsequent calls return the
   51040 ** same context that was returned on prior calls.
   51041 */
   51042 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
   51043   Mem *pMem;
   51044   assert( p && p->pFunc && p->pFunc->xStep );
   51045   assert( sqlite3_mutex_held(p->s.db->mutex) );
   51046   pMem = p->pMem;
   51047   testcase( nByte<0 );
   51048   if( (pMem->flags & MEM_Agg)==0 ){
   51049     if( nByte<=0 ){
   51050       sqlite3VdbeMemReleaseExternal(pMem);
   51051       pMem->flags = MEM_Null;
   51052       pMem->z = 0;
   51053     }else{
   51054       sqlite3VdbeMemGrow(pMem, nByte, 0);
   51055       pMem->flags = MEM_Agg;
   51056       pMem->u.pDef = p->pFunc;
   51057       if( pMem->z ){
   51058         memset(pMem->z, 0, nByte);
   51059       }
   51060     }
   51061   }
   51062   return (void*)pMem->z;
   51063 }
   51064 
   51065 /*
   51066 ** Return the auxilary data pointer, if any, for the iArg'th argument to
   51067 ** the user-function defined by pCtx.
   51068 */
   51069 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
   51070   VdbeFunc *pVdbeFunc;
   51071 
   51072   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   51073   pVdbeFunc = pCtx->pVdbeFunc;
   51074   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
   51075     return 0;
   51076   }
   51077   return pVdbeFunc->apAux[iArg].pAux;
   51078 }
   51079 
   51080 /*
   51081 ** Set the auxilary data pointer and delete function, for the iArg'th
   51082 ** argument to the user-function defined by pCtx. Any previous value is
   51083 ** deleted by calling the delete function specified when it was set.
   51084 */
   51085 SQLITE_API void sqlite3_set_auxdata(
   51086   sqlite3_context *pCtx,
   51087   int iArg,
   51088   void *pAux,
   51089   void (*xDelete)(void*)
   51090 ){
   51091   struct AuxData *pAuxData;
   51092   VdbeFunc *pVdbeFunc;
   51093   if( iArg<0 ) goto failed;
   51094 
   51095   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   51096   pVdbeFunc = pCtx->pVdbeFunc;
   51097   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
   51098     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
   51099     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
   51100     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
   51101     if( !pVdbeFunc ){
   51102       goto failed;
   51103     }
   51104     pCtx->pVdbeFunc = pVdbeFunc;
   51105     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
   51106     pVdbeFunc->nAux = iArg+1;
   51107     pVdbeFunc->pFunc = pCtx->pFunc;
   51108   }
   51109 
   51110   pAuxData = &pVdbeFunc->apAux[iArg];
   51111   if( pAuxData->pAux && pAuxData->xDelete ){
   51112     pAuxData->xDelete(pAuxData->pAux);
   51113   }
   51114   pAuxData->pAux = pAux;
   51115   pAuxData->xDelete = xDelete;
   51116   return;
   51117 
   51118 failed:
   51119   if( xDelete ){
   51120     xDelete(pAux);
   51121   }
   51122 }
   51123 
   51124 #ifndef SQLITE_OMIT_DEPRECATED
   51125 /*
   51126 ** Return the number of times the Step function of a aggregate has been
   51127 ** called.
   51128 **
   51129 ** This function is deprecated.  Do not use it for new code.  It is
   51130 ** provide only to avoid breaking legacy code.  New aggregate function
   51131 ** implementations should keep their own counts within their aggregate
   51132 ** context.
   51133 */
   51134 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
   51135   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
   51136   return p->pMem->n;
   51137 }
   51138 #endif
   51139 
   51140 /*
   51141 ** Return the number of columns in the result set for the statement pStmt.
   51142 */
   51143 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
   51144   Vdbe *pVm = (Vdbe *)pStmt;
   51145   return pVm ? pVm->nResColumn : 0;
   51146 }
   51147 
   51148 /*
   51149 ** Return the number of values available from the current row of the
   51150 ** currently executing statement pStmt.
   51151 */
   51152 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
   51153   Vdbe *pVm = (Vdbe *)pStmt;
   51154   if( pVm==0 || pVm->pResultSet==0 ) return 0;
   51155   return pVm->nResColumn;
   51156 }
   51157 
   51158 
   51159 /*
   51160 ** Check to see if column iCol of the given statement is valid.  If
   51161 ** it is, return a pointer to the Mem for the value of that column.
   51162 ** If iCol is not valid, return a pointer to a Mem which has a value
   51163 ** of NULL.
   51164 */
   51165 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
   51166   Vdbe *pVm;
   51167   int vals;
   51168   Mem *pOut;
   51169 
   51170   pVm = (Vdbe *)pStmt;
   51171   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
   51172     sqlite3_mutex_enter(pVm->db->mutex);
   51173     vals = sqlite3_data_count(pStmt);
   51174     pOut = &pVm->pResultSet[i];
   51175   }else{
   51176     /* If the value passed as the second argument is out of range, return
   51177     ** a pointer to the following static Mem object which contains the
   51178     ** value SQL NULL. Even though the Mem structure contains an element
   51179     ** of type i64, on certain architecture (x86) with certain compiler
   51180     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
   51181     ** instead of an 8-byte one. This all works fine, except that when
   51182     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
   51183     ** that a Mem structure is located on an 8-byte boundary. To prevent
   51184     ** this assert() from failing, when building with SQLITE_DEBUG defined
   51185     ** using gcc, force nullMem to be 8-byte aligned using the magical
   51186     ** __attribute__((aligned(8))) macro.  */
   51187     static const Mem nullMem
   51188 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
   51189       __attribute__((aligned(8)))
   51190 #endif
   51191       = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
   51192 
   51193     if( pVm && ALWAYS(pVm->db) ){
   51194       sqlite3_mutex_enter(pVm->db->mutex);
   51195       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
   51196     }
   51197     pOut = (Mem*)&nullMem;
   51198   }
   51199   return pOut;
   51200 }
   51201 
   51202 /*
   51203 ** This function is called after invoking an sqlite3_value_XXX function on a
   51204 ** column value (i.e. a value returned by evaluating an SQL expression in the
   51205 ** select list of a SELECT statement) that may cause a malloc() failure. If
   51206 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
   51207 ** code of statement pStmt set to SQLITE_NOMEM.
   51208 **
   51209 ** Specifically, this is called from within:
   51210 **
   51211 **     sqlite3_column_int()
   51212 **     sqlite3_column_int64()
   51213 **     sqlite3_column_text()
   51214 **     sqlite3_column_text16()
   51215 **     sqlite3_column_real()
   51216 **     sqlite3_column_bytes()
   51217 **     sqlite3_column_bytes16()
   51218 **
   51219 ** But not for sqlite3_column_blob(), which never calls malloc().
   51220 */
   51221 static void columnMallocFailure(sqlite3_stmt *pStmt)
   51222 {
   51223   /* If malloc() failed during an encoding conversion within an
   51224   ** sqlite3_column_XXX API, then set the return code of the statement to
   51225   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
   51226   ** and _finalize() will return NOMEM.
   51227   */
   51228   Vdbe *p = (Vdbe *)pStmt;
   51229   if( p ){
   51230     p->rc = sqlite3ApiExit(p->db, p->rc);
   51231     sqlite3_mutex_leave(p->db->mutex);
   51232   }
   51233 }
   51234 
   51235 /**************************** sqlite3_column_  *******************************
   51236 ** The following routines are used to access elements of the current row
   51237 ** in the result set.
   51238 */
   51239 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
   51240   const void *val;
   51241   val = sqlite3_value_blob( columnMem(pStmt,i) );
   51242   /* Even though there is no encoding conversion, value_blob() might
   51243   ** need to call malloc() to expand the result of a zeroblob()
   51244   ** expression.
   51245   */
   51246   columnMallocFailure(pStmt);
   51247   return val;
   51248 }
   51249 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
   51250   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
   51251   columnMallocFailure(pStmt);
   51252   return val;
   51253 }
   51254 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
   51255   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
   51256   columnMallocFailure(pStmt);
   51257   return val;
   51258 }
   51259 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
   51260   double val = sqlite3_value_double( columnMem(pStmt,i) );
   51261   columnMallocFailure(pStmt);
   51262   return val;
   51263 }
   51264 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
   51265   int val = sqlite3_value_int( columnMem(pStmt,i) );
   51266   columnMallocFailure(pStmt);
   51267   return val;
   51268 }
   51269 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
   51270   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
   51271   columnMallocFailure(pStmt);
   51272   return val;
   51273 }
   51274 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
   51275   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
   51276   columnMallocFailure(pStmt);
   51277   return val;
   51278 }
   51279 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
   51280   Mem *pOut = columnMem(pStmt, i);
   51281   if( pOut->flags&MEM_Static ){
   51282     pOut->flags &= ~MEM_Static;
   51283     pOut->flags |= MEM_Ephem;
   51284   }
   51285   columnMallocFailure(pStmt);
   51286   return (sqlite3_value *)pOut;
   51287 }
   51288 #ifndef SQLITE_OMIT_UTF16
   51289 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
   51290   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
   51291   columnMallocFailure(pStmt);
   51292   return val;
   51293 }
   51294 #endif /* SQLITE_OMIT_UTF16 */
   51295 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
   51296   int iType = sqlite3_value_type( columnMem(pStmt,i) );
   51297   columnMallocFailure(pStmt);
   51298   return iType;
   51299 }
   51300 
   51301 /* The following function is experimental and subject to change or
   51302 ** removal */
   51303 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
   51304 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
   51305 **}
   51306 */
   51307 
   51308 /*
   51309 ** Convert the N-th element of pStmt->pColName[] into a string using
   51310 ** xFunc() then return that string.  If N is out of range, return 0.
   51311 **
   51312 ** There are up to 5 names for each column.  useType determines which
   51313 ** name is returned.  Here are the names:
   51314 **
   51315 **    0      The column name as it should be displayed for output
   51316 **    1      The datatype name for the column
   51317 **    2      The name of the database that the column derives from
   51318 **    3      The name of the table that the column derives from
   51319 **    4      The name of the table column that the result column derives from
   51320 **
   51321 ** If the result is not a simple column reference (if it is an expression
   51322 ** or a constant) then useTypes 2, 3, and 4 return NULL.
   51323 */
   51324 static const void *columnName(
   51325   sqlite3_stmt *pStmt,
   51326   int N,
   51327   const void *(*xFunc)(Mem*),
   51328   int useType
   51329 ){
   51330   const void *ret = 0;
   51331   Vdbe *p = (Vdbe *)pStmt;
   51332   int n;
   51333   sqlite3 *db = p->db;
   51334 
   51335   assert( db!=0 );
   51336   n = sqlite3_column_count(pStmt);
   51337   if( N<n && N>=0 ){
   51338     N += useType*n;
   51339     sqlite3_mutex_enter(db->mutex);
   51340     assert( db->mallocFailed==0 );
   51341     ret = xFunc(&p->aColName[N]);
   51342      /* A malloc may have failed inside of the xFunc() call. If this
   51343     ** is the case, clear the mallocFailed flag and return NULL.
   51344     */
   51345     if( db->mallocFailed ){
   51346       db->mallocFailed = 0;
   51347       ret = 0;
   51348     }
   51349     sqlite3_mutex_leave(db->mutex);
   51350   }
   51351   return ret;
   51352 }
   51353 
   51354 /*
   51355 ** Return the name of the Nth column of the result set returned by SQL
   51356 ** statement pStmt.
   51357 */
   51358 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
   51359   return columnName(
   51360       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
   51361 }
   51362 #ifndef SQLITE_OMIT_UTF16
   51363 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
   51364   return columnName(
   51365       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
   51366 }
   51367 #endif
   51368 
   51369 /*
   51370 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
   51371 ** not define OMIT_DECLTYPE.
   51372 */
   51373 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
   51374 # error "Must not define both SQLITE_OMIT_DECLTYPE \
   51375          and SQLITE_ENABLE_COLUMN_METADATA"
   51376 #endif
   51377 
   51378 #ifndef SQLITE_OMIT_DECLTYPE
   51379 /*
   51380 ** Return the column declaration type (if applicable) of the 'i'th column
   51381 ** of the result set of SQL statement pStmt.
   51382 */
   51383 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
   51384   return columnName(
   51385       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
   51386 }
   51387 #ifndef SQLITE_OMIT_UTF16
   51388 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
   51389   return columnName(
   51390       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
   51391 }
   51392 #endif /* SQLITE_OMIT_UTF16 */
   51393 #endif /* SQLITE_OMIT_DECLTYPE */
   51394 
   51395 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   51396 /*
   51397 ** Return the name of the database from which a result column derives.
   51398 ** NULL is returned if the result column is an expression or constant or
   51399 ** anything else which is not an unabiguous reference to a database column.
   51400 */
   51401 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
   51402   return columnName(
   51403       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
   51404 }
   51405 #ifndef SQLITE_OMIT_UTF16
   51406 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
   51407   return columnName(
   51408       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
   51409 }
   51410 #endif /* SQLITE_OMIT_UTF16 */
   51411 
   51412 /*
   51413 ** Return the name of the table from which a result column derives.
   51414 ** NULL is returned if the result column is an expression or constant or
   51415 ** anything else which is not an unabiguous reference to a database column.
   51416 */
   51417 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
   51418   return columnName(
   51419       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
   51420 }
   51421 #ifndef SQLITE_OMIT_UTF16
   51422 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
   51423   return columnName(
   51424       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
   51425 }
   51426 #endif /* SQLITE_OMIT_UTF16 */
   51427 
   51428 /*
   51429 ** Return the name of the table column from which a result column derives.
   51430 ** NULL is returned if the result column is an expression or constant or
   51431 ** anything else which is not an unabiguous reference to a database column.
   51432 */
   51433 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
   51434   return columnName(
   51435       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
   51436 }
   51437 #ifndef SQLITE_OMIT_UTF16
   51438 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
   51439   return columnName(
   51440       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
   51441 }
   51442 #endif /* SQLITE_OMIT_UTF16 */
   51443 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
   51444 
   51445 
   51446 /******************************* sqlite3_bind_  ***************************
   51447 **
   51448 ** Routines used to attach values to wildcards in a compiled SQL statement.
   51449 */
   51450 /*
   51451 ** Unbind the value bound to variable i in virtual machine p. This is the
   51452 ** the same as binding a NULL value to the column. If the "i" parameter is
   51453 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
   51454 **
   51455 ** A successful evaluation of this routine acquires the mutex on p.
   51456 ** the mutex is released if any kind of error occurs.
   51457 **
   51458 ** The error code stored in database p->db is overwritten with the return
   51459 ** value in any case.
   51460 */
   51461 static int vdbeUnbind(Vdbe *p, int i){
   51462   Mem *pVar;
   51463   if( vdbeSafetyNotNull(p) ){
   51464     return SQLITE_MISUSE_BKPT;
   51465   }
   51466   sqlite3_mutex_enter(p->db->mutex);
   51467   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
   51468     sqlite3Error(p->db, SQLITE_MISUSE, 0);
   51469     sqlite3_mutex_leave(p->db->mutex);
   51470     sqlite3_log(SQLITE_MISUSE,
   51471         "bind on a busy prepared statement: [%s]", p->zSql);
   51472     return SQLITE_MISUSE_BKPT;
   51473   }
   51474   if( i<1 || i>p->nVar ){
   51475     sqlite3Error(p->db, SQLITE_RANGE, 0);
   51476     sqlite3_mutex_leave(p->db->mutex);
   51477     return SQLITE_RANGE;
   51478   }
   51479   i--;
   51480   pVar = &p->aVar[i];
   51481   sqlite3VdbeMemRelease(pVar);
   51482   pVar->flags = MEM_Null;
   51483   sqlite3Error(p->db, SQLITE_OK, 0);
   51484 
   51485   /* If the bit corresponding to this variable in Vdbe.expmask is set, then
   51486   ** binding a new value to this variable invalidates the current query plan.
   51487   */
   51488   if( p->isPrepareV2 &&
   51489      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
   51490   ){
   51491     p->expired = 1;
   51492   }
   51493   return SQLITE_OK;
   51494 }
   51495 
   51496 /*
   51497 ** Bind a text or BLOB value.
   51498 */
   51499 static int bindText(
   51500   sqlite3_stmt *pStmt,   /* The statement to bind against */
   51501   int i,                 /* Index of the parameter to bind */
   51502   const void *zData,     /* Pointer to the data to be bound */
   51503   int nData,             /* Number of bytes of data to be bound */
   51504   void (*xDel)(void*),   /* Destructor for the data */
   51505   u8 encoding            /* Encoding for the data */
   51506 ){
   51507   Vdbe *p = (Vdbe *)pStmt;
   51508   Mem *pVar;
   51509   int rc;
   51510 
   51511   rc = vdbeUnbind(p, i);
   51512   if( rc==SQLITE_OK ){
   51513     if( zData!=0 ){
   51514       pVar = &p->aVar[i-1];
   51515       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
   51516       if( rc==SQLITE_OK && encoding!=0 ){
   51517         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
   51518       }
   51519       sqlite3Error(p->db, rc, 0);
   51520       rc = sqlite3ApiExit(p->db, rc);
   51521     }
   51522     sqlite3_mutex_leave(p->db->mutex);
   51523   }
   51524   return rc;
   51525 }
   51526 
   51527 
   51528 /*
   51529 ** Bind a blob value to an SQL statement variable.
   51530 */
   51531 SQLITE_API int sqlite3_bind_blob(
   51532   sqlite3_stmt *pStmt,
   51533   int i,
   51534   const void *zData,
   51535   int nData,
   51536   void (*xDel)(void*)
   51537 ){
   51538   return bindText(pStmt, i, zData, nData, xDel, 0);
   51539 }
   51540 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
   51541   int rc;
   51542   Vdbe *p = (Vdbe *)pStmt;
   51543   rc = vdbeUnbind(p, i);
   51544   if( rc==SQLITE_OK ){
   51545     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
   51546     sqlite3_mutex_leave(p->db->mutex);
   51547   }
   51548   return rc;
   51549 }
   51550 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
   51551   return sqlite3_bind_int64(p, i, (i64)iValue);
   51552 }
   51553 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
   51554   int rc;
   51555   Vdbe *p = (Vdbe *)pStmt;
   51556   rc = vdbeUnbind(p, i);
   51557   if( rc==SQLITE_OK ){
   51558     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
   51559     sqlite3_mutex_leave(p->db->mutex);
   51560   }
   51561   return rc;
   51562 }
   51563 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
   51564   int rc;
   51565   Vdbe *p = (Vdbe*)pStmt;
   51566   rc = vdbeUnbind(p, i);
   51567   if( rc==SQLITE_OK ){
   51568     sqlite3_mutex_leave(p->db->mutex);
   51569   }
   51570   return rc;
   51571 }
   51572 SQLITE_API int sqlite3_bind_text(
   51573   sqlite3_stmt *pStmt,
   51574   int i,
   51575   const char *zData,
   51576   int nData,
   51577   void (*xDel)(void*)
   51578 ){
   51579   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
   51580 }
   51581 #ifndef SQLITE_OMIT_UTF16
   51582 SQLITE_API int sqlite3_bind_text16(
   51583   sqlite3_stmt *pStmt,
   51584   int i,
   51585   const void *zData,
   51586   int nData,
   51587   void (*xDel)(void*)
   51588 ){
   51589   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
   51590 }
   51591 #endif /* SQLITE_OMIT_UTF16 */
   51592 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
   51593   int rc;
   51594   switch( pValue->type ){
   51595     case SQLITE_INTEGER: {
   51596       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
   51597       break;
   51598     }
   51599     case SQLITE_FLOAT: {
   51600       rc = sqlite3_bind_double(pStmt, i, pValue->r);
   51601       break;
   51602     }
   51603     case SQLITE_BLOB: {
   51604       if( pValue->flags & MEM_Zero ){
   51605         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
   51606       }else{
   51607         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
   51608       }
   51609       break;
   51610     }
   51611     case SQLITE_TEXT: {
   51612       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
   51613                               pValue->enc);
   51614       break;
   51615     }
   51616     default: {
   51617       rc = sqlite3_bind_null(pStmt, i);
   51618       break;
   51619     }
   51620   }
   51621   return rc;
   51622 }
   51623 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
   51624   int rc;
   51625   Vdbe *p = (Vdbe *)pStmt;
   51626   rc = vdbeUnbind(p, i);
   51627   if( rc==SQLITE_OK ){
   51628     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
   51629     sqlite3_mutex_leave(p->db->mutex);
   51630   }
   51631   return rc;
   51632 }
   51633 
   51634 /*
   51635 ** Return the number of wildcards that can be potentially bound to.
   51636 ** This routine is added to support DBD::SQLite.
   51637 */
   51638 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
   51639   Vdbe *p = (Vdbe*)pStmt;
   51640   return p ? p->nVar : 0;
   51641 }
   51642 
   51643 /*
   51644 ** Create a mapping from variable numbers to variable names
   51645 ** in the Vdbe.azVar[] array, if such a mapping does not already
   51646 ** exist.
   51647 */
   51648 static void createVarMap(Vdbe *p){
   51649   if( !p->okVar ){
   51650     int j;
   51651     Op *pOp;
   51652     sqlite3_mutex_enter(p->db->mutex);
   51653     /* The race condition here is harmless.  If two threads call this
   51654     ** routine on the same Vdbe at the same time, they both might end
   51655     ** up initializing the Vdbe.azVar[] array.  That is a little extra
   51656     ** work but it results in the same answer.
   51657     */
   51658     for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
   51659       if( pOp->opcode==OP_Variable ){
   51660         assert( pOp->p1>0 && pOp->p1<=p->nVar );
   51661         p->azVar[pOp->p1-1] = pOp->p4.z;
   51662       }
   51663     }
   51664     p->okVar = 1;
   51665     sqlite3_mutex_leave(p->db->mutex);
   51666   }
   51667 }
   51668 
   51669 /*
   51670 ** Return the name of a wildcard parameter.  Return NULL if the index
   51671 ** is out of range or if the wildcard is unnamed.
   51672 **
   51673 ** The result is always UTF-8.
   51674 */
   51675 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
   51676   Vdbe *p = (Vdbe*)pStmt;
   51677   if( p==0 || i<1 || i>p->nVar ){
   51678     return 0;
   51679   }
   51680   createVarMap(p);
   51681   return p->azVar[i-1];
   51682 }
   51683 
   51684 /*
   51685 ** Given a wildcard parameter name, return the index of the variable
   51686 ** with that name.  If there is no variable with the given name,
   51687 ** return 0.
   51688 */
   51689 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
   51690   int i;
   51691   if( p==0 ){
   51692     return 0;
   51693   }
   51694   createVarMap(p);
   51695   if( zName ){
   51696     for(i=0; i<p->nVar; i++){
   51697       const char *z = p->azVar[i];
   51698       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
   51699         return i+1;
   51700       }
   51701     }
   51702   }
   51703   return 0;
   51704 }
   51705 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
   51706   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
   51707 }
   51708 
   51709 /*
   51710 ** Transfer all bindings from the first statement over to the second.
   51711 */
   51712 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
   51713   Vdbe *pFrom = (Vdbe*)pFromStmt;
   51714   Vdbe *pTo = (Vdbe*)pToStmt;
   51715   int i;
   51716   assert( pTo->db==pFrom->db );
   51717   assert( pTo->nVar==pFrom->nVar );
   51718   sqlite3_mutex_enter(pTo->db->mutex);
   51719   for(i=0; i<pFrom->nVar; i++){
   51720     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
   51721   }
   51722   sqlite3_mutex_leave(pTo->db->mutex);
   51723   return SQLITE_OK;
   51724 }
   51725 
   51726 #ifndef SQLITE_OMIT_DEPRECATED
   51727 /*
   51728 ** Deprecated external interface.  Internal/core SQLite code
   51729 ** should call sqlite3TransferBindings.
   51730 **
   51731 ** Is is misuse to call this routine with statements from different
   51732 ** database connections.  But as this is a deprecated interface, we
   51733 ** will not bother to check for that condition.
   51734 **
   51735 ** If the two statements contain a different number of bindings, then
   51736 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
   51737 ** SQLITE_OK is returned.
   51738 */
   51739 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
   51740   Vdbe *pFrom = (Vdbe*)pFromStmt;
   51741   Vdbe *pTo = (Vdbe*)pToStmt;
   51742   if( pFrom->nVar!=pTo->nVar ){
   51743     return SQLITE_ERROR;
   51744   }
   51745   if( pTo->isPrepareV2 && pTo->expmask ){
   51746     pTo->expired = 1;
   51747   }
   51748   if( pFrom->isPrepareV2 && pFrom->expmask ){
   51749     pFrom->expired = 1;
   51750   }
   51751   return sqlite3TransferBindings(pFromStmt, pToStmt);
   51752 }
   51753 #endif
   51754 
   51755 /*
   51756 ** Return the sqlite3* database handle to which the prepared statement given
   51757 ** in the argument belongs.  This is the same database handle that was
   51758 ** the first argument to the sqlite3_prepare() that was used to create
   51759 ** the statement in the first place.
   51760 */
   51761 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
   51762   return pStmt ? ((Vdbe*)pStmt)->db : 0;
   51763 }
   51764 
   51765 /*
   51766 ** Return a pointer to the next prepared statement after pStmt associated
   51767 ** with database connection pDb.  If pStmt is NULL, return the first
   51768 ** prepared statement for the database connection.  Return NULL if there
   51769 ** are no more.
   51770 */
   51771 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
   51772   sqlite3_stmt *pNext;
   51773   sqlite3_mutex_enter(pDb->mutex);
   51774   if( pStmt==0 ){
   51775     pNext = (sqlite3_stmt*)pDb->pVdbe;
   51776   }else{
   51777     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
   51778   }
   51779   sqlite3_mutex_leave(pDb->mutex);
   51780   return pNext;
   51781 }
   51782 
   51783 /*
   51784 ** Return the value of a status counter for a prepared statement
   51785 */
   51786 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
   51787   Vdbe *pVdbe = (Vdbe*)pStmt;
   51788   int v = pVdbe->aCounter[op-1];
   51789   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
   51790   return v;
   51791 }
   51792 
   51793 /************** End of vdbeapi.c *********************************************/
   51794 /************** Begin file vdbetrace.c ***************************************/
   51795 /*
   51796 ** 2009 November 25
   51797 **
   51798 ** The author disclaims copyright to this source code.  In place of
   51799 ** a legal notice, here is a blessing:
   51800 **
   51801 **    May you do good and not evil.
   51802 **    May you find forgiveness for yourself and forgive others.
   51803 **    May you share freely, never taking more than you give.
   51804 **
   51805 *************************************************************************
   51806 **
   51807 ** This file contains code used to insert the values of host parameters
   51808 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
   51809 */
   51810 
   51811 #ifndef SQLITE_OMIT_TRACE
   51812 
   51813 /*
   51814 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
   51815 ** bytes in this text up to but excluding the first character in
   51816 ** a host parameter.  If the text contains no host parameters, return
   51817 ** the total number of bytes in the text.
   51818 */
   51819 static int findNextHostParameter(const char *zSql, int *pnToken){
   51820   int tokenType;
   51821   int nTotal = 0;
   51822   int n;
   51823 
   51824   *pnToken = 0;
   51825   while( zSql[0] ){
   51826     n = sqlite3GetToken((u8*)zSql, &tokenType);
   51827     assert( n>0 && tokenType!=TK_ILLEGAL );
   51828     if( tokenType==TK_VARIABLE ){
   51829       *pnToken = n;
   51830       break;
   51831     }
   51832     nTotal += n;
   51833     zSql += n;
   51834   }
   51835   return nTotal;
   51836 }
   51837 
   51838 /*
   51839 ** Return a pointer to a string in memory obtained form sqlite3DbMalloc() which
   51840 ** holds a copy of zRawSql but with host parameters expanded to their
   51841 ** current bindings.
   51842 **
   51843 ** The calling function is responsible for making sure the memory returned
   51844 ** is eventually freed.
   51845 **
   51846 ** ALGORITHM:  Scan the input string looking for host parameters in any of
   51847 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
   51848 ** string literals, quoted identifier names, and comments.  For text forms,
   51849 ** the host parameter index is found by scanning the perpared
   51850 ** statement for the corresponding OP_Variable opcode.  Once the host
   51851 ** parameter index is known, locate the value in p->aVar[].  Then render
   51852 ** the value as a literal in place of the host parameter name.
   51853 */
   51854 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
   51855   Vdbe *p,                 /* The prepared statement being evaluated */
   51856   const char *zRawSql      /* Raw text of the SQL statement */
   51857 ){
   51858   sqlite3 *db;             /* The database connection */
   51859   int idx = 0;             /* Index of a host parameter */
   51860   int nextIndex = 1;       /* Index of next ? host parameter */
   51861   int n;                   /* Length of a token prefix */
   51862   int nToken;              /* Length of the parameter token */
   51863   int i;                   /* Loop counter */
   51864   Mem *pVar;               /* Value of a host parameter */
   51865   StrAccum out;            /* Accumulate the output here */
   51866   char zBase[100];         /* Initial working space */
   51867 
   51868   db = p->db;
   51869   sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
   51870                       db->aLimit[SQLITE_LIMIT_LENGTH]);
   51871   out.db = db;
   51872   while( zRawSql[0] ){
   51873     n = findNextHostParameter(zRawSql, &nToken);
   51874     assert( n>0 );
   51875     sqlite3StrAccumAppend(&out, zRawSql, n);
   51876     zRawSql += n;
   51877     assert( zRawSql[0] || nToken==0 );
   51878     if( nToken==0 ) break;
   51879     if( zRawSql[0]=='?' ){
   51880       if( nToken>1 ){
   51881         assert( sqlite3Isdigit(zRawSql[1]) );
   51882         sqlite3GetInt32(&zRawSql[1], &idx);
   51883       }else{
   51884         idx = nextIndex;
   51885       }
   51886     }else{
   51887       assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
   51888       testcase( zRawSql[0]==':' );
   51889       testcase( zRawSql[0]=='$' );
   51890       testcase( zRawSql[0]=='@' );
   51891       idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
   51892       assert( idx>0 );
   51893     }
   51894     zRawSql += nToken;
   51895     nextIndex = idx + 1;
   51896     assert( idx>0 && idx<=p->nVar );
   51897     pVar = &p->aVar[idx-1];
   51898     if( pVar->flags & MEM_Null ){
   51899       sqlite3StrAccumAppend(&out, "NULL", 4);
   51900     }else if( pVar->flags & MEM_Int ){
   51901       sqlite3XPrintf(&out, "%lld", pVar->u.i);
   51902     }else if( pVar->flags & MEM_Real ){
   51903       sqlite3XPrintf(&out, "%!.15g", pVar->r);
   51904     }else if( pVar->flags & MEM_Str ){
   51905 #ifndef SQLITE_OMIT_UTF16
   51906       u8 enc = ENC(db);
   51907       if( enc!=SQLITE_UTF8 ){
   51908         Mem utf8;
   51909         memset(&utf8, 0, sizeof(utf8));
   51910         utf8.db = db;
   51911         sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
   51912         sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
   51913         sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
   51914         sqlite3VdbeMemRelease(&utf8);
   51915       }else
   51916 #endif
   51917       {
   51918         sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
   51919       }
   51920     }else if( pVar->flags & MEM_Zero ){
   51921       sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
   51922     }else{
   51923       assert( pVar->flags & MEM_Blob );
   51924       sqlite3StrAccumAppend(&out, "x'", 2);
   51925       for(i=0; i<pVar->n; i++){
   51926         sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
   51927       }
   51928       sqlite3StrAccumAppend(&out, "'", 1);
   51929     }
   51930   }
   51931   return sqlite3StrAccumFinish(&out);
   51932 }
   51933 
   51934 #endif /* #ifndef SQLITE_OMIT_TRACE */
   51935 
   51936 /************** End of vdbetrace.c *******************************************/
   51937 /************** Begin file vdbe.c ********************************************/
   51938 /*
   51939 ** 2001 September 15
   51940 **
   51941 ** The author disclaims copyright to this source code.  In place of
   51942 ** a legal notice, here is a blessing:
   51943 **
   51944 **    May you do good and not evil.
   51945 **    May you find forgiveness for yourself and forgive others.
   51946 **    May you share freely, never taking more than you give.
   51947 **
   51948 *************************************************************************
   51949 ** The code in this file implements execution method of the
   51950 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
   51951 ** handles housekeeping details such as creating and deleting
   51952 ** VDBE instances.  This file is solely interested in executing
   51953 ** the VDBE program.
   51954 **
   51955 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
   51956 ** to a VDBE.
   51957 **
   51958 ** The SQL parser generates a program which is then executed by
   51959 ** the VDBE to do the work of the SQL statement.  VDBE programs are
   51960 ** similar in form to assembly language.  The program consists of
   51961 ** a linear sequence of operations.  Each operation has an opcode
   51962 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
   51963 ** is a null-terminated string.  Operand P5 is an unsigned character.
   51964 ** Few opcodes use all 5 operands.
   51965 **
   51966 ** Computation results are stored on a set of registers numbered beginning
   51967 ** with 1 and going up to Vdbe.nMem.  Each register can store
   51968 ** either an integer, a null-terminated string, a floating point
   51969 ** number, or the SQL "NULL" value.  An implicit conversion from one
   51970 ** type to the other occurs as necessary.
   51971 **
   51972 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
   51973 ** function which does the work of interpreting a VDBE program.
   51974 ** But other routines are also provided to help in building up
   51975 ** a program instruction by instruction.
   51976 **
   51977 ** Various scripts scan this source file in order to generate HTML
   51978 ** documentation, headers files, or other derived files.  The formatting
   51979 ** of the code in this file is, therefore, important.  See other comments
   51980 ** in this file for details.  If in doubt, do not deviate from existing
   51981 ** commenting and indentation practices when changing or adding code.
   51982 */
   51983 
   51984 /*
   51985 ** The following global variable is incremented every time a cursor
   51986 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
   51987 ** procedures use this information to make sure that indices are
   51988 ** working correctly.  This variable has no function other than to
   51989 ** help verify the correct operation of the library.
   51990 */
   51991 #ifdef SQLITE_TEST
   51992 SQLITE_API int sqlite3_search_count = 0;
   51993 #endif
   51994 
   51995 /*
   51996 ** When this global variable is positive, it gets decremented once before
   51997 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
   51998 ** field of the sqlite3 structure is set in order to simulate and interrupt.
   51999 **
   52000 ** This facility is used for testing purposes only.  It does not function
   52001 ** in an ordinary build.
   52002 */
   52003 #ifdef SQLITE_TEST
   52004 SQLITE_API int sqlite3_interrupt_count = 0;
   52005 #endif
   52006 
   52007 /*
   52008 ** The next global variable is incremented each type the OP_Sort opcode
   52009 ** is executed.  The test procedures use this information to make sure that
   52010 ** sorting is occurring or not occurring at appropriate times.   This variable
   52011 ** has no function other than to help verify the correct operation of the
   52012 ** library.
   52013 */
   52014 #ifdef SQLITE_TEST
   52015 SQLITE_API int sqlite3_sort_count = 0;
   52016 #endif
   52017 
   52018 /*
   52019 ** The next global variable records the size of the largest MEM_Blob
   52020 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
   52021 ** use this information to make sure that the zero-blob functionality
   52022 ** is working correctly.   This variable has no function other than to
   52023 ** help verify the correct operation of the library.
   52024 */
   52025 #ifdef SQLITE_TEST
   52026 SQLITE_API int sqlite3_max_blobsize = 0;
   52027 static void updateMaxBlobsize(Mem *p){
   52028   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
   52029     sqlite3_max_blobsize = p->n;
   52030   }
   52031 }
   52032 #endif
   52033 
   52034 /*
   52035 ** The next global variable is incremented each type the OP_Found opcode
   52036 ** is executed. This is used to test whether or not the foreign key
   52037 ** operation implemented using OP_FkIsZero is working. This variable
   52038 ** has no function other than to help verify the correct operation of the
   52039 ** library.
   52040 */
   52041 #ifdef SQLITE_TEST
   52042 SQLITE_API int sqlite3_found_count = 0;
   52043 #endif
   52044 
   52045 /*
   52046 ** Test a register to see if it exceeds the current maximum blob size.
   52047 ** If it does, record the new maximum blob size.
   52048 */
   52049 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
   52050 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
   52051 #else
   52052 # define UPDATE_MAX_BLOBSIZE(P)
   52053 #endif
   52054 
   52055 /*
   52056 ** Convert the given register into a string if it isn't one
   52057 ** already. Return non-zero if a malloc() fails.
   52058 */
   52059 #define Stringify(P, enc) \
   52060    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
   52061      { goto no_mem; }
   52062 
   52063 /*
   52064 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
   52065 ** a pointer to a dynamically allocated string where some other entity
   52066 ** is responsible for deallocating that string.  Because the register
   52067 ** does not control the string, it might be deleted without the register
   52068 ** knowing it.
   52069 **
   52070 ** This routine converts an ephemeral string into a dynamically allocated
   52071 ** string that the register itself controls.  In other words, it
   52072 ** converts an MEM_Ephem string into an MEM_Dyn string.
   52073 */
   52074 #define Deephemeralize(P) \
   52075    if( ((P)->flags&MEM_Ephem)!=0 \
   52076        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
   52077 
   52078 /*
   52079 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
   52080 ** P if required.
   52081 */
   52082 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
   52083 
   52084 /*
   52085 ** Argument pMem points at a register that will be passed to a
   52086 ** user-defined function or returned to the user as the result of a query.
   52087 ** This routine sets the pMem->type variable used by the sqlite3_value_*()
   52088 ** routines.
   52089 */
   52090 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
   52091   int flags = pMem->flags;
   52092   if( flags & MEM_Null ){
   52093     pMem->type = SQLITE_NULL;
   52094   }
   52095   else if( flags & MEM_Int ){
   52096     pMem->type = SQLITE_INTEGER;
   52097   }
   52098   else if( flags & MEM_Real ){
   52099     pMem->type = SQLITE_FLOAT;
   52100   }
   52101   else if( flags & MEM_Str ){
   52102     pMem->type = SQLITE_TEXT;
   52103   }else{
   52104     pMem->type = SQLITE_BLOB;
   52105   }
   52106 }
   52107 
   52108 /*
   52109 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
   52110 ** if we run out of memory.
   52111 */
   52112 static VdbeCursor *allocateCursor(
   52113   Vdbe *p,              /* The virtual machine */
   52114   int iCur,             /* Index of the new VdbeCursor */
   52115   int nField,           /* Number of fields in the table or index */
   52116   int iDb,              /* When database the cursor belongs to, or -1 */
   52117   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
   52118 ){
   52119   /* Find the memory cell that will be used to store the blob of memory
   52120   ** required for this VdbeCursor structure. It is convenient to use a
   52121   ** vdbe memory cell to manage the memory allocation required for a
   52122   ** VdbeCursor structure for the following reasons:
   52123   **
   52124   **   * Sometimes cursor numbers are used for a couple of different
   52125   **     purposes in a vdbe program. The different uses might require
   52126   **     different sized allocations. Memory cells provide growable
   52127   **     allocations.
   52128   **
   52129   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
   52130   **     be freed lazily via the sqlite3_release_memory() API. This
   52131   **     minimizes the number of malloc calls made by the system.
   52132   **
   52133   ** Memory cells for cursors are allocated at the top of the address
   52134   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
   52135   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
   52136   */
   52137   Mem *pMem = &p->aMem[p->nMem-iCur];
   52138 
   52139   int nByte;
   52140   VdbeCursor *pCx = 0;
   52141   nByte =
   52142       ROUND8(sizeof(VdbeCursor)) +
   52143       (isBtreeCursor?sqlite3BtreeCursorSize():0) +
   52144       2*nField*sizeof(u32);
   52145 
   52146   assert( iCur<p->nCursor );
   52147   if( p->apCsr[iCur] ){
   52148     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
   52149     p->apCsr[iCur] = 0;
   52150   }
   52151   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
   52152     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
   52153     memset(pCx, 0, sizeof(VdbeCursor));
   52154     pCx->iDb = iDb;
   52155     pCx->nField = nField;
   52156     if( nField ){
   52157       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
   52158     }
   52159     if( isBtreeCursor ){
   52160       pCx->pCursor = (BtCursor*)
   52161           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
   52162       sqlite3BtreeCursorZero(pCx->pCursor);
   52163     }
   52164   }
   52165   return pCx;
   52166 }
   52167 
   52168 /*
   52169 ** Try to convert a value into a numeric representation if we can
   52170 ** do so without loss of information.  In other words, if the string
   52171 ** looks like a number, convert it into a number.  If it does not
   52172 ** look like a number, leave it alone.
   52173 */
   52174 static void applyNumericAffinity(Mem *pRec){
   52175   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
   52176     int realnum;
   52177     sqlite3VdbeMemNulTerminate(pRec);
   52178     if( (pRec->flags&MEM_Str)
   52179          && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
   52180       i64 value;
   52181       sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
   52182       if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
   52183         pRec->u.i = value;
   52184         MemSetTypeFlag(pRec, MEM_Int);
   52185       }else{
   52186         sqlite3VdbeMemRealify(pRec);
   52187       }
   52188     }
   52189   }
   52190 }
   52191 
   52192 /*
   52193 ** Processing is determine by the affinity parameter:
   52194 **
   52195 ** SQLITE_AFF_INTEGER:
   52196 ** SQLITE_AFF_REAL:
   52197 ** SQLITE_AFF_NUMERIC:
   52198 **    Try to convert pRec to an integer representation or a
   52199 **    floating-point representation if an integer representation
   52200 **    is not possible.  Note that the integer representation is
   52201 **    always preferred, even if the affinity is REAL, because
   52202 **    an integer representation is more space efficient on disk.
   52203 **
   52204 ** SQLITE_AFF_TEXT:
   52205 **    Convert pRec to a text representation.
   52206 **
   52207 ** SQLITE_AFF_NONE:
   52208 **    No-op.  pRec is unchanged.
   52209 */
   52210 static void applyAffinity(
   52211   Mem *pRec,          /* The value to apply affinity to */
   52212   char affinity,      /* The affinity to be applied */
   52213   u8 enc              /* Use this text encoding */
   52214 ){
   52215   if( affinity==SQLITE_AFF_TEXT ){
   52216     /* Only attempt the conversion to TEXT if there is an integer or real
   52217     ** representation (blob and NULL do not get converted) but no string
   52218     ** representation.
   52219     */
   52220     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
   52221       sqlite3VdbeMemStringify(pRec, enc);
   52222     }
   52223     pRec->flags &= ~(MEM_Real|MEM_Int);
   52224   }else if( affinity!=SQLITE_AFF_NONE ){
   52225     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
   52226              || affinity==SQLITE_AFF_NUMERIC );
   52227     applyNumericAffinity(pRec);
   52228     if( pRec->flags & MEM_Real ){
   52229       sqlite3VdbeIntegerAffinity(pRec);
   52230     }
   52231   }
   52232 }
   52233 
   52234 /*
   52235 ** Try to convert the type of a function argument or a result column
   52236 ** into a numeric representation.  Use either INTEGER or REAL whichever
   52237 ** is appropriate.  But only do the conversion if it is possible without
   52238 ** loss of information and return the revised type of the argument.
   52239 **
   52240 ** This is an EXPERIMENTAL api and is subject to change or removal.
   52241 */
   52242 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
   52243   Mem *pMem = (Mem*)pVal;
   52244   applyNumericAffinity(pMem);
   52245   sqlite3VdbeMemStoreType(pMem);
   52246   return pMem->type;
   52247 }
   52248 
   52249 /*
   52250 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
   52251 ** not the internal Mem* type.
   52252 */
   52253 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
   52254   sqlite3_value *pVal,
   52255   u8 affinity,
   52256   u8 enc
   52257 ){
   52258   applyAffinity((Mem *)pVal, affinity, enc);
   52259 }
   52260 
   52261 #ifdef SQLITE_DEBUG
   52262 /*
   52263 ** Write a nice string representation of the contents of cell pMem
   52264 ** into buffer zBuf, length nBuf.
   52265 */
   52266 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
   52267   char *zCsr = zBuf;
   52268   int f = pMem->flags;
   52269 
   52270   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
   52271 
   52272   if( f&MEM_Blob ){
   52273     int i;
   52274     char c;
   52275     if( f & MEM_Dyn ){
   52276       c = 'z';
   52277       assert( (f & (MEM_Static|MEM_Ephem))==0 );
   52278     }else if( f & MEM_Static ){
   52279       c = 't';
   52280       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
   52281     }else if( f & MEM_Ephem ){
   52282       c = 'e';
   52283       assert( (f & (MEM_Static|MEM_Dyn))==0 );
   52284     }else{
   52285       c = 's';
   52286     }
   52287 
   52288     sqlite3_snprintf(100, zCsr, "%c", c);
   52289     zCsr += sqlite3Strlen30(zCsr);
   52290     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
   52291     zCsr += sqlite3Strlen30(zCsr);
   52292     for(i=0; i<16 && i<pMem->n; i++){
   52293       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
   52294       zCsr += sqlite3Strlen30(zCsr);
   52295     }
   52296     for(i=0; i<16 && i<pMem->n; i++){
   52297       char z = pMem->z[i];
   52298       if( z<32 || z>126 ) *zCsr++ = '.';
   52299       else *zCsr++ = z;
   52300     }
   52301 
   52302     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
   52303     zCsr += sqlite3Strlen30(zCsr);
   52304     if( f & MEM_Zero ){
   52305       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
   52306       zCsr += sqlite3Strlen30(zCsr);
   52307     }
   52308     *zCsr = '\0';
   52309   }else if( f & MEM_Str ){
   52310     int j, k;
   52311     zBuf[0] = ' ';
   52312     if( f & MEM_Dyn ){
   52313       zBuf[1] = 'z';
   52314       assert( (f & (MEM_Static|MEM_Ephem))==0 );
   52315     }else if( f & MEM_Static ){
   52316       zBuf[1] = 't';
   52317       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
   52318     }else if( f & MEM_Ephem ){
   52319       zBuf[1] = 'e';
   52320       assert( (f & (MEM_Static|MEM_Dyn))==0 );
   52321     }else{
   52322       zBuf[1] = 's';
   52323     }
   52324     k = 2;
   52325     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
   52326     k += sqlite3Strlen30(&zBuf[k]);
   52327     zBuf[k++] = '[';
   52328     for(j=0; j<15 && j<pMem->n; j++){
   52329       u8 c = pMem->z[j];
   52330       if( c>=0x20 && c<0x7f ){
   52331         zBuf[k++] = c;
   52332       }else{
   52333         zBuf[k++] = '.';
   52334       }
   52335     }
   52336     zBuf[k++] = ']';
   52337     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
   52338     k += sqlite3Strlen30(&zBuf[k]);
   52339     zBuf[k++] = 0;
   52340   }
   52341 }
   52342 #endif
   52343 
   52344 #ifdef SQLITE_DEBUG
   52345 /*
   52346 ** Print the value of a register for tracing purposes:
   52347 */
   52348 static void memTracePrint(FILE *out, Mem *p){
   52349   if( p->flags & MEM_Null ){
   52350     fprintf(out, " NULL");
   52351   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
   52352     fprintf(out, " si:%lld", p->u.i);
   52353   }else if( p->flags & MEM_Int ){
   52354     fprintf(out, " i:%lld", p->u.i);
   52355 #ifndef SQLITE_OMIT_FLOATING_POINT
   52356   }else if( p->flags & MEM_Real ){
   52357     fprintf(out, " r:%g", p->r);
   52358 #endif
   52359   }else if( p->flags & MEM_RowSet ){
   52360     fprintf(out, " (rowset)");
   52361   }else{
   52362     char zBuf[200];
   52363     sqlite3VdbeMemPrettyPrint(p, zBuf);
   52364     fprintf(out, " ");
   52365     fprintf(out, "%s", zBuf);
   52366   }
   52367 }
   52368 static void registerTrace(FILE *out, int iReg, Mem *p){
   52369   fprintf(out, "REG[%d] = ", iReg);
   52370   memTracePrint(out, p);
   52371   fprintf(out, "\n");
   52372 }
   52373 #endif
   52374 
   52375 #ifdef SQLITE_DEBUG
   52376 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
   52377 #else
   52378 #  define REGISTER_TRACE(R,M)
   52379 #endif
   52380 
   52381 
   52382 #ifdef VDBE_PROFILE
   52383 
   52384 /*
   52385 ** hwtime.h contains inline assembler code for implementing
   52386 ** high-performance timing routines.
   52387 */
   52388 /************** Include hwtime.h in the middle of vdbe.c *********************/
   52389 /************** Begin file hwtime.h ******************************************/
   52390 /*
   52391 ** 2008 May 27
   52392 **
   52393 ** The author disclaims copyright to this source code.  In place of
   52394 ** a legal notice, here is a blessing:
   52395 **
   52396 **    May you do good and not evil.
   52397 **    May you find forgiveness for yourself and forgive others.
   52398 **    May you share freely, never taking more than you give.
   52399 **
   52400 ******************************************************************************
   52401 **
   52402 ** This file contains inline asm code for retrieving "high-performance"
   52403 ** counters for x86 class CPUs.
   52404 */
   52405 #ifndef _HWTIME_H_
   52406 #define _HWTIME_H_
   52407 
   52408 /*
   52409 ** The following routine only works on pentium-class (or newer) processors.
   52410 ** It uses the RDTSC opcode to read the cycle count value out of the
   52411 ** processor and returns that value.  This can be used for high-res
   52412 ** profiling.
   52413 */
   52414 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   52415       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   52416 
   52417   #if defined(__GNUC__)
   52418 
   52419   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   52420      unsigned int lo, hi;
   52421      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   52422      return (sqlite_uint64)hi << 32 | lo;
   52423   }
   52424 
   52425   #elif defined(_MSC_VER)
   52426 
   52427   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   52428      __asm {
   52429         rdtsc
   52430         ret       ; return value at EDX:EAX
   52431      }
   52432   }
   52433 
   52434   #endif
   52435 
   52436 #elif (defined(__GNUC__) && defined(__x86_64__))
   52437 
   52438   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   52439       unsigned long val;
   52440       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   52441       return val;
   52442   }
   52443 
   52444 #elif (defined(__GNUC__) && defined(__ppc__))
   52445 
   52446   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   52447       unsigned long long retval;
   52448       unsigned long junk;
   52449       __asm__ __volatile__ ("\n\
   52450           1:      mftbu   %1\n\
   52451                   mftb    %L0\n\
   52452                   mftbu   %0\n\
   52453                   cmpw    %0,%1\n\
   52454                   bne     1b"
   52455                   : "=r" (retval), "=r" (junk));
   52456       return retval;
   52457   }
   52458 
   52459 #else
   52460 
   52461   #error Need implementation of sqlite3Hwtime() for your platform.
   52462 
   52463   /*
   52464   ** To compile without implementing sqlite3Hwtime() for your platform,
   52465   ** you can remove the above #error and use the following
   52466   ** stub function.  You will lose timing support for many
   52467   ** of the debugging and testing utilities, but it should at
   52468   ** least compile and run.
   52469   */
   52470 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   52471 
   52472 #endif
   52473 
   52474 #endif /* !defined(_HWTIME_H_) */
   52475 
   52476 /************** End of hwtime.h **********************************************/
   52477 /************** Continuing where we left off in vdbe.c ***********************/
   52478 
   52479 #endif
   52480 
   52481 /*
   52482 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
   52483 ** sqlite3_interrupt() routine has been called.  If it has been, then
   52484 ** processing of the VDBE program is interrupted.
   52485 **
   52486 ** This macro added to every instruction that does a jump in order to
   52487 ** implement a loop.  This test used to be on every single instruction,
   52488 ** but that meant we more testing that we needed.  By only testing the
   52489 ** flag on jump instructions, we get a (small) speed improvement.
   52490 */
   52491 #define CHECK_FOR_INTERRUPT \
   52492    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
   52493 
   52494 #ifdef SQLITE_DEBUG
   52495 static int fileExists(sqlite3 *db, const char *zFile){
   52496   int res = 0;
   52497   int rc = SQLITE_OK;
   52498 #ifdef SQLITE_TEST
   52499   /* If we are currently testing IO errors, then do not call OsAccess() to
   52500   ** test for the presence of zFile. This is because any IO error that
   52501   ** occurs here will not be reported, causing the test to fail.
   52502   */
   52503   extern int sqlite3_io_error_pending;
   52504   if( sqlite3_io_error_pending<=0 )
   52505 #endif
   52506     rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
   52507   return (res && rc==SQLITE_OK);
   52508 }
   52509 #endif
   52510 
   52511 #ifndef NDEBUG
   52512 /*
   52513 ** This function is only called from within an assert() expression. It
   52514 ** checks that the sqlite3.nTransaction variable is correctly set to
   52515 ** the number of non-transaction savepoints currently in the
   52516 ** linked list starting at sqlite3.pSavepoint.
   52517 **
   52518 ** Usage:
   52519 **
   52520 **     assert( checkSavepointCount(db) );
   52521 */
   52522 static int checkSavepointCount(sqlite3 *db){
   52523   int n = 0;
   52524   Savepoint *p;
   52525   for(p=db->pSavepoint; p; p=p->pNext) n++;
   52526   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
   52527   return 1;
   52528 }
   52529 #endif
   52530 
   52531 /*
   52532 ** Execute as much of a VDBE program as we can then return.
   52533 **
   52534 ** sqlite3VdbeMakeReady() must be called before this routine in order to
   52535 ** close the program with a final OP_Halt and to set up the callbacks
   52536 ** and the error message pointer.
   52537 **
   52538 ** Whenever a row or result data is available, this routine will either
   52539 ** invoke the result callback (if there is one) or return with
   52540 ** SQLITE_ROW.
   52541 **
   52542 ** If an attempt is made to open a locked database, then this routine
   52543 ** will either invoke the busy callback (if there is one) or it will
   52544 ** return SQLITE_BUSY.
   52545 **
   52546 ** If an error occurs, an error message is written to memory obtained
   52547 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
   52548 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
   52549 **
   52550 ** If the callback ever returns non-zero, then the program exits
   52551 ** immediately.  There will be no error message but the p->rc field is
   52552 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
   52553 **
   52554 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
   52555 ** routine to return SQLITE_ERROR.
   52556 **
   52557 ** Other fatal errors return SQLITE_ERROR.
   52558 **
   52559 ** After this routine has finished, sqlite3VdbeFinalize() should be
   52560 ** used to clean up the mess that was left behind.
   52561 */
   52562 SQLITE_PRIVATE int sqlite3VdbeExec(
   52563   Vdbe *p                    /* The VDBE */
   52564 ){
   52565   int pc;                    /* The program counter */
   52566   Op *aOp = p->aOp;          /* Copy of p->aOp */
   52567   Op *pOp;                   /* Current operation */
   52568   int rc = SQLITE_OK;        /* Value to return */
   52569   sqlite3 *db = p->db;       /* The database */
   52570   u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */
   52571   u8 encoding = ENC(db);     /* The database encoding */
   52572 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   52573   int checkProgress;         /* True if progress callbacks are enabled */
   52574   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
   52575 #endif
   52576   Mem *aMem = p->aMem;       /* Copy of p->aMem */
   52577   Mem *pIn1 = 0;             /* 1st input operand */
   52578   Mem *pIn2 = 0;             /* 2nd input operand */
   52579   Mem *pIn3 = 0;             /* 3rd input operand */
   52580   Mem *pOut = 0;             /* Output operand */
   52581   int iCompare = 0;          /* Result of last OP_Compare operation */
   52582   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
   52583 #ifdef VDBE_PROFILE
   52584   u64 start;                 /* CPU clock count at start of opcode */
   52585   int origPc;                /* Program counter at start of opcode */
   52586 #endif
   52587   /********************************************************************
   52588   ** Automatically generated code
   52589   **
   52590   ** The following union is automatically generated by the
   52591   ** vdbe-compress.tcl script.  The purpose of this union is to
   52592   ** reduce the amount of stack space required by this function.
   52593   ** See comments in the vdbe-compress.tcl script for details.
   52594   */
   52595   union vdbeExecUnion {
   52596     struct OP_Yield_stack_vars {
   52597       int pcDest;
   52598     } aa;
   52599     struct OP_Variable_stack_vars {
   52600       int p1;          /* Variable to copy from */
   52601       int p2;          /* Register to copy to */
   52602       int n;           /* Number of values left to copy */
   52603       Mem *pVar;       /* Value being transferred */
   52604     } ab;
   52605     struct OP_Move_stack_vars {
   52606       char *zMalloc;   /* Holding variable for allocated memory */
   52607       int n;           /* Number of registers left to copy */
   52608       int p1;          /* Register to copy from */
   52609       int p2;          /* Register to copy to */
   52610     } ac;
   52611     struct OP_ResultRow_stack_vars {
   52612       Mem *pMem;
   52613       int i;
   52614     } ad;
   52615     struct OP_Concat_stack_vars {
   52616       i64 nByte;
   52617     } ae;
   52618     struct OP_Remainder_stack_vars {
   52619       int flags;      /* Combined MEM_* flags from both inputs */
   52620       i64 iA;         /* Integer value of left operand */
   52621       i64 iB;         /* Integer value of right operand */
   52622       double rA;      /* Real value of left operand */
   52623       double rB;      /* Real value of right operand */
   52624     } af;
   52625     struct OP_Function_stack_vars {
   52626       int i;
   52627       Mem *pArg;
   52628       sqlite3_context ctx;
   52629       sqlite3_value **apVal;
   52630       int n;
   52631     } ag;
   52632     struct OP_ShiftRight_stack_vars {
   52633       i64 a;
   52634       i64 b;
   52635     } ah;
   52636     struct OP_Ge_stack_vars {
   52637       int res;            /* Result of the comparison of pIn1 against pIn3 */
   52638       char affinity;      /* Affinity to use for comparison */
   52639     } ai;
   52640     struct OP_Compare_stack_vars {
   52641       int n;
   52642       int i;
   52643       int p1;
   52644       int p2;
   52645       const KeyInfo *pKeyInfo;
   52646       int idx;
   52647       CollSeq *pColl;    /* Collating sequence to use on this term */
   52648       int bRev;          /* True for DESCENDING sort order */
   52649     } aj;
   52650     struct OP_Or_stack_vars {
   52651       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   52652       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   52653     } ak;
   52654     struct OP_IfNot_stack_vars {
   52655       int c;
   52656     } al;
   52657     struct OP_Column_stack_vars {
   52658       u32 payloadSize;   /* Number of bytes in the record */
   52659       i64 payloadSize64; /* Number of bytes in the record */
   52660       int p1;            /* P1 value of the opcode */
   52661       int p2;            /* column number to retrieve */
   52662       VdbeCursor *pC;    /* The VDBE cursor */
   52663       char *zRec;        /* Pointer to complete record-data */
   52664       BtCursor *pCrsr;   /* The BTree cursor */
   52665       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
   52666       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
   52667       int nField;        /* number of fields in the record */
   52668       int len;           /* The length of the serialized data for the column */
   52669       int i;             /* Loop counter */
   52670       char *zData;       /* Part of the record being decoded */
   52671       Mem *pDest;        /* Where to write the extracted value */
   52672       Mem sMem;          /* For storing the record being decoded */
   52673       u8 *zIdx;          /* Index into header */
   52674       u8 *zEndHdr;       /* Pointer to first byte after the header */
   52675       u32 offset;        /* Offset into the data */
   52676       u32 szField;       /* Number of bytes in the content of a field */
   52677       int szHdr;         /* Size of the header size field at start of record */
   52678       int avail;         /* Number of bytes of available data */
   52679       Mem *pReg;         /* PseudoTable input register */
   52680     } am;
   52681     struct OP_Affinity_stack_vars {
   52682       const char *zAffinity;   /* The affinity to be applied */
   52683       char cAff;               /* A single character of affinity */
   52684     } an;
   52685     struct OP_MakeRecord_stack_vars {
   52686       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
   52687       Mem *pRec;             /* The new record */
   52688       u64 nData;             /* Number of bytes of data space */
   52689       int nHdr;              /* Number of bytes of header space */
   52690       i64 nByte;             /* Data space required for this record */
   52691       int nZero;             /* Number of zero bytes at the end of the record */
   52692       int nVarint;           /* Number of bytes in a varint */
   52693       u32 serial_type;       /* Type field */
   52694       Mem *pData0;           /* First field to be combined into the record */
   52695       Mem *pLast;            /* Last field of the record */
   52696       int nField;            /* Number of fields in the record */
   52697       char *zAffinity;       /* The affinity string for the record */
   52698       int file_format;       /* File format to use for encoding */
   52699       int i;                 /* Space used in zNewRecord[] */
   52700       int len;               /* Length of a field */
   52701     } ao;
   52702     struct OP_Count_stack_vars {
   52703       i64 nEntry;
   52704       BtCursor *pCrsr;
   52705     } ap;
   52706     struct OP_Savepoint_stack_vars {
   52707       int p1;                         /* Value of P1 operand */
   52708       char *zName;                    /* Name of savepoint */
   52709       int nName;
   52710       Savepoint *pNew;
   52711       Savepoint *pSavepoint;
   52712       Savepoint *pTmp;
   52713       int iSavepoint;
   52714       int ii;
   52715     } aq;
   52716     struct OP_AutoCommit_stack_vars {
   52717       int desiredAutoCommit;
   52718       int iRollback;
   52719       int turnOnAC;
   52720     } ar;
   52721     struct OP_Transaction_stack_vars {
   52722       Btree *pBt;
   52723     } as;
   52724     struct OP_ReadCookie_stack_vars {
   52725       int iMeta;
   52726       int iDb;
   52727       int iCookie;
   52728     } at;
   52729     struct OP_SetCookie_stack_vars {
   52730       Db *pDb;
   52731     } au;
   52732     struct OP_VerifyCookie_stack_vars {
   52733       int iMeta;
   52734       Btree *pBt;
   52735     } av;
   52736     struct OP_OpenWrite_stack_vars {
   52737       int nField;
   52738       KeyInfo *pKeyInfo;
   52739       int p2;
   52740       int iDb;
   52741       int wrFlag;
   52742       Btree *pX;
   52743       VdbeCursor *pCur;
   52744       Db *pDb;
   52745     } aw;
   52746     struct OP_OpenEphemeral_stack_vars {
   52747       VdbeCursor *pCx;
   52748     } ax;
   52749     struct OP_OpenPseudo_stack_vars {
   52750       VdbeCursor *pCx;
   52751     } ay;
   52752     struct OP_SeekGt_stack_vars {
   52753       int res;
   52754       int oc;
   52755       VdbeCursor *pC;
   52756       UnpackedRecord r;
   52757       int nField;
   52758       i64 iKey;      /* The rowid we are to seek to */
   52759     } az;
   52760     struct OP_Seek_stack_vars {
   52761       VdbeCursor *pC;
   52762     } ba;
   52763     struct OP_Found_stack_vars {
   52764       int alreadyExists;
   52765       VdbeCursor *pC;
   52766       int res;
   52767       UnpackedRecord *pIdxKey;
   52768       UnpackedRecord r;
   52769       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
   52770     } bb;
   52771     struct OP_IsUnique_stack_vars {
   52772       u16 ii;
   52773       VdbeCursor *pCx;
   52774       BtCursor *pCrsr;
   52775       u16 nField;
   52776       Mem *aMx;
   52777       UnpackedRecord r;                  /* B-Tree index search key */
   52778       i64 R;                             /* Rowid stored in register P3 */
   52779     } bc;
   52780     struct OP_NotExists_stack_vars {
   52781       VdbeCursor *pC;
   52782       BtCursor *pCrsr;
   52783       int res;
   52784       u64 iKey;
   52785     } bd;
   52786     struct OP_NewRowid_stack_vars {
   52787       i64 v;                 /* The new rowid */
   52788       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
   52789       int res;               /* Result of an sqlite3BtreeLast() */
   52790       int cnt;               /* Counter to limit the number of searches */
   52791       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
   52792       VdbeFrame *pFrame;     /* Root frame of VDBE */
   52793     } be;
   52794     struct OP_InsertInt_stack_vars {
   52795       Mem *pData;       /* MEM cell holding data for the record to be inserted */
   52796       Mem *pKey;        /* MEM cell holding key  for the record */
   52797       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
   52798       VdbeCursor *pC;   /* Cursor to table into which insert is written */
   52799       int nZero;        /* Number of zero-bytes to append */
   52800       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
   52801       const char *zDb;  /* database name - used by the update hook */
   52802       const char *zTbl; /* Table name - used by the opdate hook */
   52803       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
   52804     } bf;
   52805     struct OP_Delete_stack_vars {
   52806       i64 iKey;
   52807       VdbeCursor *pC;
   52808     } bg;
   52809     struct OP_RowData_stack_vars {
   52810       VdbeCursor *pC;
   52811       BtCursor *pCrsr;
   52812       u32 n;
   52813       i64 n64;
   52814     } bh;
   52815     struct OP_Rowid_stack_vars {
   52816       VdbeCursor *pC;
   52817       i64 v;
   52818       sqlite3_vtab *pVtab;
   52819       const sqlite3_module *pModule;
   52820     } bi;
   52821     struct OP_NullRow_stack_vars {
   52822       VdbeCursor *pC;
   52823     } bj;
   52824     struct OP_Last_stack_vars {
   52825       VdbeCursor *pC;
   52826       BtCursor *pCrsr;
   52827       int res;
   52828     } bk;
   52829     struct OP_Rewind_stack_vars {
   52830       VdbeCursor *pC;
   52831       BtCursor *pCrsr;
   52832       int res;
   52833     } bl;
   52834     struct OP_Next_stack_vars {
   52835       VdbeCursor *pC;
   52836       BtCursor *pCrsr;
   52837       int res;
   52838     } bm;
   52839     struct OP_IdxInsert_stack_vars {
   52840       VdbeCursor *pC;
   52841       BtCursor *pCrsr;
   52842       int nKey;
   52843       const char *zKey;
   52844     } bn;
   52845     struct OP_IdxDelete_stack_vars {
   52846       VdbeCursor *pC;
   52847       BtCursor *pCrsr;
   52848       int res;
   52849       UnpackedRecord r;
   52850     } bo;
   52851     struct OP_IdxRowid_stack_vars {
   52852       BtCursor *pCrsr;
   52853       VdbeCursor *pC;
   52854       i64 rowid;
   52855     } bp;
   52856     struct OP_IdxGE_stack_vars {
   52857       VdbeCursor *pC;
   52858       int res;
   52859       UnpackedRecord r;
   52860     } bq;
   52861     struct OP_Destroy_stack_vars {
   52862       int iMoved;
   52863       int iCnt;
   52864       Vdbe *pVdbe;
   52865       int iDb;
   52866     } br;
   52867     struct OP_Clear_stack_vars {
   52868       int nChange;
   52869     } bs;
   52870     struct OP_CreateTable_stack_vars {
   52871       int pgno;
   52872       int flags;
   52873       Db *pDb;
   52874     } bt;
   52875     struct OP_ParseSchema_stack_vars {
   52876       int iDb;
   52877       const char *zMaster;
   52878       char *zSql;
   52879       InitData initData;
   52880     } bu;
   52881     struct OP_IntegrityCk_stack_vars {
   52882       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
   52883       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
   52884       int j;          /* Loop counter */
   52885       int nErr;       /* Number of errors reported */
   52886       char *z;        /* Text of the error report */
   52887       Mem *pnErr;     /* Register keeping track of errors remaining */
   52888     } bv;
   52889     struct OP_RowSetRead_stack_vars {
   52890       i64 val;
   52891     } bw;
   52892     struct OP_RowSetTest_stack_vars {
   52893       int iSet;
   52894       int exists;
   52895     } bx;
   52896     struct OP_Program_stack_vars {
   52897       int nMem;               /* Number of memory registers for sub-program */
   52898       int nByte;              /* Bytes of runtime space required for sub-program */
   52899       Mem *pRt;               /* Register to allocate runtime space */
   52900       Mem *pMem;              /* Used to iterate through memory cells */
   52901       Mem *pEnd;              /* Last memory cell in new array */
   52902       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
   52903       SubProgram *pProgram;   /* Sub-program to execute */
   52904       void *t;                /* Token identifying trigger */
   52905     } by;
   52906     struct OP_Param_stack_vars {
   52907       VdbeFrame *pFrame;
   52908       Mem *pIn;
   52909     } bz;
   52910     struct OP_MemMax_stack_vars {
   52911       Mem *pIn1;
   52912       VdbeFrame *pFrame;
   52913     } ca;
   52914     struct OP_AggStep_stack_vars {
   52915       int n;
   52916       int i;
   52917       Mem *pMem;
   52918       Mem *pRec;
   52919       sqlite3_context ctx;
   52920       sqlite3_value **apVal;
   52921     } cb;
   52922     struct OP_AggFinal_stack_vars {
   52923       Mem *pMem;
   52924     } cc;
   52925     struct OP_IncrVacuum_stack_vars {
   52926       Btree *pBt;
   52927     } cd;
   52928     struct OP_VBegin_stack_vars {
   52929       VTable *pVTab;
   52930     } ce;
   52931     struct OP_VOpen_stack_vars {
   52932       VdbeCursor *pCur;
   52933       sqlite3_vtab_cursor *pVtabCursor;
   52934       sqlite3_vtab *pVtab;
   52935       sqlite3_module *pModule;
   52936     } cf;
   52937     struct OP_VFilter_stack_vars {
   52938       int nArg;
   52939       int iQuery;
   52940       const sqlite3_module *pModule;
   52941       Mem *pQuery;
   52942       Mem *pArgc;
   52943       sqlite3_vtab_cursor *pVtabCursor;
   52944       sqlite3_vtab *pVtab;
   52945       VdbeCursor *pCur;
   52946       int res;
   52947       int i;
   52948       Mem **apArg;
   52949     } cg;
   52950     struct OP_VColumn_stack_vars {
   52951       sqlite3_vtab *pVtab;
   52952       const sqlite3_module *pModule;
   52953       Mem *pDest;
   52954       sqlite3_context sContext;
   52955     } ch;
   52956     struct OP_VNext_stack_vars {
   52957       sqlite3_vtab *pVtab;
   52958       const sqlite3_module *pModule;
   52959       int res;
   52960       VdbeCursor *pCur;
   52961     } ci;
   52962     struct OP_VRename_stack_vars {
   52963       sqlite3_vtab *pVtab;
   52964       Mem *pName;
   52965     } cj;
   52966     struct OP_VUpdate_stack_vars {
   52967       sqlite3_vtab *pVtab;
   52968       sqlite3_module *pModule;
   52969       int nArg;
   52970       int i;
   52971       sqlite_int64 rowid;
   52972       Mem **apArg;
   52973       Mem *pX;
   52974     } ck;
   52975     struct OP_Pagecount_stack_vars {
   52976       int p1;
   52977       int nPage;
   52978       Pager *pPager;
   52979     } cl;
   52980     struct OP_Trace_stack_vars {
   52981       char *zTrace;
   52982     } cm;
   52983   } u;
   52984   /* End automatically generated code
   52985   ********************************************************************/
   52986 
   52987   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
   52988   sqlite3VdbeMutexArrayEnter(p);
   52989   if( p->rc==SQLITE_NOMEM ){
   52990     /* This happens if a malloc() inside a call to sqlite3_column_text() or
   52991     ** sqlite3_column_text16() failed.  */
   52992     goto no_mem;
   52993   }
   52994   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
   52995   p->rc = SQLITE_OK;
   52996   assert( p->explain==0 );
   52997   p->pResultSet = 0;
   52998   db->busyHandler.nBusy = 0;
   52999   CHECK_FOR_INTERRUPT;
   53000   sqlite3VdbeIOTraceSql(p);
   53001 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   53002   checkProgress = db->xProgress!=0;
   53003 #endif
   53004 #ifdef SQLITE_DEBUG
   53005   sqlite3BeginBenignMalloc();
   53006   if( p->pc==0
   53007    && ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
   53008   ){
   53009     int i;
   53010     printf("VDBE Program Listing:\n");
   53011     sqlite3VdbePrintSql(p);
   53012     for(i=0; i<p->nOp; i++){
   53013       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
   53014     }
   53015   }
   53016   if( fileExists(db, "vdbe_trace") ){
   53017     p->trace = stdout;
   53018   }
   53019   sqlite3EndBenignMalloc();
   53020 #endif
   53021   for(pc=p->pc; rc==SQLITE_OK; pc++){
   53022     assert( pc>=0 && pc<p->nOp );
   53023     if( db->mallocFailed ) goto no_mem;
   53024 #ifdef VDBE_PROFILE
   53025     origPc = pc;
   53026     start = sqlite3Hwtime();
   53027 #endif
   53028     pOp = &aOp[pc];
   53029 
   53030     /* Only allow tracing if SQLITE_DEBUG is defined.
   53031     */
   53032 #ifdef SQLITE_DEBUG
   53033     if( p->trace ){
   53034       if( pc==0 ){
   53035         printf("VDBE Execution Trace:\n");
   53036         sqlite3VdbePrintSql(p);
   53037       }
   53038       sqlite3VdbePrintOp(p->trace, pc, pOp);
   53039     }
   53040     if( p->trace==0 && pc==0 ){
   53041       sqlite3BeginBenignMalloc();
   53042       if( fileExists(db, "vdbe_sqltrace") ){
   53043         sqlite3VdbePrintSql(p);
   53044       }
   53045       sqlite3EndBenignMalloc();
   53046     }
   53047 #endif
   53048 
   53049 
   53050     /* Check to see if we need to simulate an interrupt.  This only happens
   53051     ** if we have a special test build.
   53052     */
   53053 #ifdef SQLITE_TEST
   53054     if( sqlite3_interrupt_count>0 ){
   53055       sqlite3_interrupt_count--;
   53056       if( sqlite3_interrupt_count==0 ){
   53057         sqlite3_interrupt(db);
   53058       }
   53059     }
   53060 #endif
   53061 
   53062 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   53063     /* Call the progress callback if it is configured and the required number
   53064     ** of VDBE ops have been executed (either since this invocation of
   53065     ** sqlite3VdbeExec() or since last time the progress callback was called).
   53066     ** If the progress callback returns non-zero, exit the virtual machine with
   53067     ** a return code SQLITE_ABORT.
   53068     */
   53069     if( checkProgress ){
   53070       if( db->nProgressOps==nProgressOps ){
   53071         int prc;
   53072         prc = db->xProgress(db->pProgressArg);
   53073         if( prc!=0 ){
   53074           rc = SQLITE_INTERRUPT;
   53075           goto vdbe_error_halt;
   53076         }
   53077         nProgressOps = 0;
   53078       }
   53079       nProgressOps++;
   53080     }
   53081 #endif
   53082 
   53083     /* On any opcode with the "out2-prerelase" tag, free any
   53084     ** external allocations out of mem[p2] and set mem[p2] to be
   53085     ** an undefined integer.  Opcodes will either fill in the integer
   53086     ** value or convert mem[p2] to a different type.
   53087     */
   53088     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
   53089     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
   53090       assert( pOp->p2>0 );
   53091       assert( pOp->p2<=p->nMem );
   53092       pOut = &aMem[pOp->p2];
   53093       sqlite3VdbeMemReleaseExternal(pOut);
   53094       pOut->flags = MEM_Int;
   53095     }
   53096 
   53097     /* Sanity checking on other operands */
   53098 #ifdef SQLITE_DEBUG
   53099     if( (pOp->opflags & OPFLG_IN1)!=0 ){
   53100       assert( pOp->p1>0 );
   53101       assert( pOp->p1<=p->nMem );
   53102       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
   53103     }
   53104     if( (pOp->opflags & OPFLG_IN2)!=0 ){
   53105       assert( pOp->p2>0 );
   53106       assert( pOp->p2<=p->nMem );
   53107       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
   53108     }
   53109     if( (pOp->opflags & OPFLG_IN3)!=0 ){
   53110       assert( pOp->p3>0 );
   53111       assert( pOp->p3<=p->nMem );
   53112       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
   53113     }
   53114     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
   53115       assert( pOp->p2>0 );
   53116       assert( pOp->p2<=p->nMem );
   53117     }
   53118     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
   53119       assert( pOp->p3>0 );
   53120       assert( pOp->p3<=p->nMem );
   53121     }
   53122 #endif
   53123 
   53124     switch( pOp->opcode ){
   53125 
   53126 /*****************************************************************************
   53127 ** What follows is a massive switch statement where each case implements a
   53128 ** separate instruction in the virtual machine.  If we follow the usual
   53129 ** indentation conventions, each case should be indented by 6 spaces.  But
   53130 ** that is a lot of wasted space on the left margin.  So the code within
   53131 ** the switch statement will break with convention and be flush-left. Another
   53132 ** big comment (similar to this one) will mark the point in the code where
   53133 ** we transition back to normal indentation.
   53134 **
   53135 ** The formatting of each case is important.  The makefile for SQLite
   53136 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
   53137 ** file looking for lines that begin with "case OP_".  The opcodes.h files
   53138 ** will be filled with #defines that give unique integer values to each
   53139 ** opcode and the opcodes.c file is filled with an array of strings where
   53140 ** each string is the symbolic name for the corresponding opcode.  If the
   53141 ** case statement is followed by a comment of the form "/# same as ... #/"
   53142 ** that comment is used to determine the particular value of the opcode.
   53143 **
   53144 ** Other keywords in the comment that follows each case are used to
   53145 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
   53146 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
   53147 ** the mkopcodeh.awk script for additional information.
   53148 **
   53149 ** Documentation about VDBE opcodes is generated by scanning this file
   53150 ** for lines of that contain "Opcode:".  That line and all subsequent
   53151 ** comment lines are used in the generation of the opcode.html documentation
   53152 ** file.
   53153 **
   53154 ** SUMMARY:
   53155 **
   53156 **     Formatting is important to scripts that scan this file.
   53157 **     Do not deviate from the formatting style currently in use.
   53158 **
   53159 *****************************************************************************/
   53160 
   53161 /* Opcode:  Goto * P2 * * *
   53162 **
   53163 ** An unconditional jump to address P2.
   53164 ** The next instruction executed will be
   53165 ** the one at index P2 from the beginning of
   53166 ** the program.
   53167 */
   53168 case OP_Goto: {             /* jump */
   53169   CHECK_FOR_INTERRUPT;
   53170   pc = pOp->p2 - 1;
   53171   break;
   53172 }
   53173 
   53174 /* Opcode:  Gosub P1 P2 * * *
   53175 **
   53176 ** Write the current address onto register P1
   53177 ** and then jump to address P2.
   53178 */
   53179 case OP_Gosub: {            /* jump, in1 */
   53180   pIn1 = &aMem[pOp->p1];
   53181   assert( (pIn1->flags & MEM_Dyn)==0 );
   53182   pIn1->flags = MEM_Int;
   53183   pIn1->u.i = pc;
   53184   REGISTER_TRACE(pOp->p1, pIn1);
   53185   pc = pOp->p2 - 1;
   53186   break;
   53187 }
   53188 
   53189 /* Opcode:  Return P1 * * * *
   53190 **
   53191 ** Jump to the next instruction after the address in register P1.
   53192 */
   53193 case OP_Return: {           /* in1 */
   53194   pIn1 = &aMem[pOp->p1];
   53195   assert( pIn1->flags & MEM_Int );
   53196   pc = (int)pIn1->u.i;
   53197   break;
   53198 }
   53199 
   53200 /* Opcode:  Yield P1 * * * *
   53201 **
   53202 ** Swap the program counter with the value in register P1.
   53203 */
   53204 case OP_Yield: {            /* in1 */
   53205 #if 0  /* local variables moved into u.aa */
   53206   int pcDest;
   53207 #endif /* local variables moved into u.aa */
   53208   pIn1 = &aMem[pOp->p1];
   53209   assert( (pIn1->flags & MEM_Dyn)==0 );
   53210   pIn1->flags = MEM_Int;
   53211   u.aa.pcDest = (int)pIn1->u.i;
   53212   pIn1->u.i = pc;
   53213   REGISTER_TRACE(pOp->p1, pIn1);
   53214   pc = u.aa.pcDest;
   53215   break;
   53216 }
   53217 
   53218 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
   53219 **
   53220 ** Check the value in register P3.  If is is NULL then Halt using
   53221 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
   53222 ** value in register P3 is not NULL, then this routine is a no-op.
   53223 */
   53224 case OP_HaltIfNull: {      /* in3 */
   53225   pIn3 = &aMem[pOp->p3];
   53226   if( (pIn3->flags & MEM_Null)==0 ) break;
   53227   /* Fall through into OP_Halt */
   53228 }
   53229 
   53230 /* Opcode:  Halt P1 P2 * P4 *
   53231 **
   53232 ** Exit immediately.  All open cursors, etc are closed
   53233 ** automatically.
   53234 **
   53235 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
   53236 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
   53237 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
   53238 ** whether or not to rollback the current transaction.  Do not rollback
   53239 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
   53240 ** then back out all changes that have occurred during this execution of the
   53241 ** VDBE, but do not rollback the transaction.
   53242 **
   53243 ** If P4 is not null then it is an error message string.
   53244 **
   53245 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
   53246 ** every program.  So a jump past the last instruction of the program
   53247 ** is the same as executing Halt.
   53248 */
   53249 case OP_Halt: {
   53250   if( pOp->p1==SQLITE_OK && p->pFrame ){
   53251     /* Halt the sub-program. Return control to the parent frame. */
   53252     VdbeFrame *pFrame = p->pFrame;
   53253     p->pFrame = pFrame->pParent;
   53254     p->nFrame--;
   53255     sqlite3VdbeSetChanges(db, p->nChange);
   53256     pc = sqlite3VdbeFrameRestore(pFrame);
   53257     if( pOp->p2==OE_Ignore ){
   53258       /* Instruction pc is the OP_Program that invoked the sub-program
   53259       ** currently being halted. If the p2 instruction of this OP_Halt
   53260       ** instruction is set to OE_Ignore, then the sub-program is throwing
   53261       ** an IGNORE exception. In this case jump to the address specified
   53262       ** as the p2 of the calling OP_Program.  */
   53263       pc = p->aOp[pc].p2-1;
   53264     }
   53265     aOp = p->aOp;
   53266     aMem = p->aMem;
   53267     break;
   53268   }
   53269 
   53270   p->rc = pOp->p1;
   53271   p->errorAction = (u8)pOp->p2;
   53272   p->pc = pc;
   53273   if( pOp->p4.z ){
   53274     assert( p->rc!=SQLITE_OK );
   53275     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
   53276     testcase( sqlite3GlobalConfig.xLog!=0 );
   53277     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
   53278   }else if( p->rc ){
   53279     testcase( sqlite3GlobalConfig.xLog!=0 );
   53280     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
   53281   }
   53282   rc = sqlite3VdbeHalt(p);
   53283   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
   53284   if( rc==SQLITE_BUSY ){
   53285     p->rc = rc = SQLITE_BUSY;
   53286   }else{
   53287     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
   53288     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
   53289     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
   53290   }
   53291   goto vdbe_return;
   53292 }
   53293 
   53294 /* Opcode: Integer P1 P2 * * *
   53295 **
   53296 ** The 32-bit integer value P1 is written into register P2.
   53297 */
   53298 case OP_Integer: {         /* out2-prerelease */
   53299   pOut->u.i = pOp->p1;
   53300   break;
   53301 }
   53302 
   53303 /* Opcode: Int64 * P2 * P4 *
   53304 **
   53305 ** P4 is a pointer to a 64-bit integer value.
   53306 ** Write that value into register P2.
   53307 */
   53308 case OP_Int64: {           /* out2-prerelease */
   53309   assert( pOp->p4.pI64!=0 );
   53310   pOut->u.i = *pOp->p4.pI64;
   53311   break;
   53312 }
   53313 
   53314 /* Opcode: Real * P2 * P4 *
   53315 **
   53316 ** P4 is a pointer to a 64-bit floating point value.
   53317 ** Write that value into register P2.
   53318 */
   53319 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
   53320   pOut->flags = MEM_Real;
   53321   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
   53322   pOut->r = *pOp->p4.pReal;
   53323   break;
   53324 }
   53325 
   53326 /* Opcode: String8 * P2 * P4 *
   53327 **
   53328 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
   53329 ** into an OP_String before it is executed for the first time.
   53330 */
   53331 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
   53332   assert( pOp->p4.z!=0 );
   53333   pOp->opcode = OP_String;
   53334   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
   53335 
   53336 #ifndef SQLITE_OMIT_UTF16
   53337   if( encoding!=SQLITE_UTF8 ){
   53338     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
   53339     if( rc==SQLITE_TOOBIG ) goto too_big;
   53340     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
   53341     assert( pOut->zMalloc==pOut->z );
   53342     assert( pOut->flags & MEM_Dyn );
   53343     pOut->zMalloc = 0;
   53344     pOut->flags |= MEM_Static;
   53345     pOut->flags &= ~MEM_Dyn;
   53346     if( pOp->p4type==P4_DYNAMIC ){
   53347       sqlite3DbFree(db, pOp->p4.z);
   53348     }
   53349     pOp->p4type = P4_DYNAMIC;
   53350     pOp->p4.z = pOut->z;
   53351     pOp->p1 = pOut->n;
   53352   }
   53353 #endif
   53354   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   53355     goto too_big;
   53356   }
   53357   /* Fall through to the next case, OP_String */
   53358 }
   53359 
   53360 /* Opcode: String P1 P2 * P4 *
   53361 **
   53362 ** The string value P4 of length P1 (bytes) is stored in register P2.
   53363 */
   53364 case OP_String: {          /* out2-prerelease */
   53365   assert( pOp->p4.z!=0 );
   53366   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
   53367   pOut->z = pOp->p4.z;
   53368   pOut->n = pOp->p1;
   53369   pOut->enc = encoding;
   53370   UPDATE_MAX_BLOBSIZE(pOut);
   53371   break;
   53372 }
   53373 
   53374 /* Opcode: Null * P2 * * *
   53375 **
   53376 ** Write a NULL into register P2.
   53377 */
   53378 case OP_Null: {           /* out2-prerelease */
   53379   pOut->flags = MEM_Null;
   53380   break;
   53381 }
   53382 
   53383 
   53384 /* Opcode: Blob P1 P2 * P4
   53385 **
   53386 ** P4 points to a blob of data P1 bytes long.  Store this
   53387 ** blob in register P2. This instruction is not coded directly
   53388 ** by the compiler. Instead, the compiler layer specifies
   53389 ** an OP_HexBlob opcode, with the hex string representation of
   53390 ** the blob as P4. This opcode is transformed to an OP_Blob
   53391 ** the first time it is executed.
   53392 */
   53393 case OP_Blob: {                /* out2-prerelease */
   53394   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
   53395   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
   53396   pOut->enc = encoding;
   53397   UPDATE_MAX_BLOBSIZE(pOut);
   53398   break;
   53399 }
   53400 
   53401 /* Opcode: Variable P1 P2 P3 P4 *
   53402 **
   53403 ** Transfer the values of bound parameters P1..P1+P3-1 into registers
   53404 ** P2..P2+P3-1.
   53405 **
   53406 ** If the parameter is named, then its name appears in P4 and P3==1.
   53407 ** The P4 value is used by sqlite3_bind_parameter_name().
   53408 */
   53409 case OP_Variable: {
   53410 #if 0  /* local variables moved into u.ab */
   53411   int p1;          /* Variable to copy from */
   53412   int p2;          /* Register to copy to */
   53413   int n;           /* Number of values left to copy */
   53414   Mem *pVar;       /* Value being transferred */
   53415 #endif /* local variables moved into u.ab */
   53416 
   53417   u.ab.p1 = pOp->p1 - 1;
   53418   u.ab.p2 = pOp->p2;
   53419   u.ab.n = pOp->p3;
   53420   assert( u.ab.p1>=0 && u.ab.p1+u.ab.n<=p->nVar );
   53421   assert( u.ab.p2>=1 && u.ab.p2+u.ab.n-1<=p->nMem );
   53422   assert( pOp->p4.z==0 || pOp->p3==1 || pOp->p3==0 );
   53423 
   53424   while( u.ab.n-- > 0 ){
   53425     u.ab.pVar = &p->aVar[u.ab.p1++];
   53426     if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
   53427       goto too_big;
   53428     }
   53429     pOut = &aMem[u.ab.p2++];
   53430     sqlite3VdbeMemReleaseExternal(pOut);
   53431     pOut->flags = MEM_Null;
   53432     sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
   53433     UPDATE_MAX_BLOBSIZE(pOut);
   53434   }
   53435   break;
   53436 }
   53437 
   53438 /* Opcode: Move P1 P2 P3 * *
   53439 **
   53440 ** Move the values in register P1..P1+P3-1 over into
   53441 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
   53442 ** left holding a NULL.  It is an error for register ranges
   53443 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
   53444 */
   53445 case OP_Move: {
   53446 #if 0  /* local variables moved into u.ac */
   53447   char *zMalloc;   /* Holding variable for allocated memory */
   53448   int n;           /* Number of registers left to copy */
   53449   int p1;          /* Register to copy from */
   53450   int p2;          /* Register to copy to */
   53451 #endif /* local variables moved into u.ac */
   53452 
   53453   u.ac.n = pOp->p3;
   53454   u.ac.p1 = pOp->p1;
   53455   u.ac.p2 = pOp->p2;
   53456   assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
   53457   assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
   53458 
   53459   pIn1 = &aMem[u.ac.p1];
   53460   pOut = &aMem[u.ac.p2];
   53461   while( u.ac.n-- ){
   53462     assert( pOut<=&aMem[p->nMem] );
   53463     assert( pIn1<=&aMem[p->nMem] );
   53464     u.ac.zMalloc = pOut->zMalloc;
   53465     pOut->zMalloc = 0;
   53466     sqlite3VdbeMemMove(pOut, pIn1);
   53467     pIn1->zMalloc = u.ac.zMalloc;
   53468     REGISTER_TRACE(u.ac.p2++, pOut);
   53469     pIn1++;
   53470     pOut++;
   53471   }
   53472   break;
   53473 }
   53474 
   53475 /* Opcode: Copy P1 P2 * * *
   53476 **
   53477 ** Make a copy of register P1 into register P2.
   53478 **
   53479 ** This instruction makes a deep copy of the value.  A duplicate
   53480 ** is made of any string or blob constant.  See also OP_SCopy.
   53481 */
   53482 case OP_Copy: {             /* in1, out2 */
   53483   pIn1 = &aMem[pOp->p1];
   53484   pOut = &aMem[pOp->p2];
   53485   assert( pOut!=pIn1 );
   53486   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
   53487   Deephemeralize(pOut);
   53488   REGISTER_TRACE(pOp->p2, pOut);
   53489   break;
   53490 }
   53491 
   53492 /* Opcode: SCopy P1 P2 * * *
   53493 **
   53494 ** Make a shallow copy of register P1 into register P2.
   53495 **
   53496 ** This instruction makes a shallow copy of the value.  If the value
   53497 ** is a string or blob, then the copy is only a pointer to the
   53498 ** original and hence if the original changes so will the copy.
   53499 ** Worse, if the original is deallocated, the copy becomes invalid.
   53500 ** Thus the program must guarantee that the original will not change
   53501 ** during the lifetime of the copy.  Use OP_Copy to make a complete
   53502 ** copy.
   53503 */
   53504 case OP_SCopy: {            /* in1, out2 */
   53505   pIn1 = &aMem[pOp->p1];
   53506   pOut = &aMem[pOp->p2];
   53507   assert( pOut!=pIn1 );
   53508   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
   53509   REGISTER_TRACE(pOp->p2, pOut);
   53510   break;
   53511 }
   53512 
   53513 /* Opcode: ResultRow P1 P2 * * *
   53514 **
   53515 ** The registers P1 through P1+P2-1 contain a single row of
   53516 ** results. This opcode causes the sqlite3_step() call to terminate
   53517 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
   53518 ** structure to provide access to the top P1 values as the result
   53519 ** row.
   53520 */
   53521 case OP_ResultRow: {
   53522 #if 0  /* local variables moved into u.ad */
   53523   Mem *pMem;
   53524   int i;
   53525 #endif /* local variables moved into u.ad */
   53526   assert( p->nResColumn==pOp->p2 );
   53527   assert( pOp->p1>0 );
   53528   assert( pOp->p1+pOp->p2<=p->nMem+1 );
   53529 
   53530   /* If this statement has violated immediate foreign key constraints, do
   53531   ** not return the number of rows modified. And do not RELEASE the statement
   53532   ** transaction. It needs to be rolled back.  */
   53533   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
   53534     assert( db->flags&SQLITE_CountRows );
   53535     assert( p->usesStmtJournal );
   53536     break;
   53537   }
   53538 
   53539   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
   53540   ** DML statements invoke this opcode to return the number of rows
   53541   ** modified to the user. This is the only way that a VM that
   53542   ** opens a statement transaction may invoke this opcode.
   53543   **
   53544   ** In case this is such a statement, close any statement transaction
   53545   ** opened by this VM before returning control to the user. This is to
   53546   ** ensure that statement-transactions are always nested, not overlapping.
   53547   ** If the open statement-transaction is not closed here, then the user
   53548   ** may step another VM that opens its own statement transaction. This
   53549   ** may lead to overlapping statement transactions.
   53550   **
   53551   ** The statement transaction is never a top-level transaction.  Hence
   53552   ** the RELEASE call below can never fail.
   53553   */
   53554   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
   53555   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
   53556   if( NEVER(rc!=SQLITE_OK) ){
   53557     break;
   53558   }
   53559 
   53560   /* Invalidate all ephemeral cursor row caches */
   53561   p->cacheCtr = (p->cacheCtr + 2)|1;
   53562 
   53563   /* Make sure the results of the current row are \000 terminated
   53564   ** and have an assigned type.  The results are de-ephemeralized as
   53565   ** as side effect.
   53566   */
   53567   u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
   53568   for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
   53569     sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
   53570     sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
   53571     REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
   53572   }
   53573   if( db->mallocFailed ) goto no_mem;
   53574 
   53575   /* Return SQLITE_ROW
   53576   */
   53577   p->pc = pc + 1;
   53578   rc = SQLITE_ROW;
   53579   goto vdbe_return;
   53580 }
   53581 
   53582 /* Opcode: Concat P1 P2 P3 * *
   53583 **
   53584 ** Add the text in register P1 onto the end of the text in
   53585 ** register P2 and store the result in register P3.
   53586 ** If either the P1 or P2 text are NULL then store NULL in P3.
   53587 **
   53588 **   P3 = P2 || P1
   53589 **
   53590 ** It is illegal for P1 and P3 to be the same register. Sometimes,
   53591 ** if P3 is the same register as P2, the implementation is able
   53592 ** to avoid a memcpy().
   53593 */
   53594 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
   53595 #if 0  /* local variables moved into u.ae */
   53596   i64 nByte;
   53597 #endif /* local variables moved into u.ae */
   53598 
   53599   pIn1 = &aMem[pOp->p1];
   53600   pIn2 = &aMem[pOp->p2];
   53601   pOut = &aMem[pOp->p3];
   53602   assert( pIn1!=pOut );
   53603   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
   53604     sqlite3VdbeMemSetNull(pOut);
   53605     break;
   53606   }
   53607   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
   53608   Stringify(pIn1, encoding);
   53609   Stringify(pIn2, encoding);
   53610   u.ae.nByte = pIn1->n + pIn2->n;
   53611   if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   53612     goto too_big;
   53613   }
   53614   MemSetTypeFlag(pOut, MEM_Str);
   53615   if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
   53616     goto no_mem;
   53617   }
   53618   if( pOut!=pIn2 ){
   53619     memcpy(pOut->z, pIn2->z, pIn2->n);
   53620   }
   53621   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
   53622   pOut->z[u.ae.nByte] = 0;
   53623   pOut->z[u.ae.nByte+1] = 0;
   53624   pOut->flags |= MEM_Term;
   53625   pOut->n = (int)u.ae.nByte;
   53626   pOut->enc = encoding;
   53627   UPDATE_MAX_BLOBSIZE(pOut);
   53628   break;
   53629 }
   53630 
   53631 /* Opcode: Add P1 P2 P3 * *
   53632 **
   53633 ** Add the value in register P1 to the value in register P2
   53634 ** and store the result in register P3.
   53635 ** If either input is NULL, the result is NULL.
   53636 */
   53637 /* Opcode: Multiply P1 P2 P3 * *
   53638 **
   53639 **
   53640 ** Multiply the value in register P1 by the value in register P2
   53641 ** and store the result in register P3.
   53642 ** If either input is NULL, the result is NULL.
   53643 */
   53644 /* Opcode: Subtract P1 P2 P3 * *
   53645 **
   53646 ** Subtract the value in register P1 from the value in register P2
   53647 ** and store the result in register P3.
   53648 ** If either input is NULL, the result is NULL.
   53649 */
   53650 /* Opcode: Divide P1 P2 P3 * *
   53651 **
   53652 ** Divide the value in register P1 by the value in register P2
   53653 ** and store the result in register P3 (P3=P2/P1). If the value in
   53654 ** register P1 is zero, then the result is NULL. If either input is
   53655 ** NULL, the result is NULL.
   53656 */
   53657 /* Opcode: Remainder P1 P2 P3 * *
   53658 **
   53659 ** Compute the remainder after integer division of the value in
   53660 ** register P1 by the value in register P2 and store the result in P3.
   53661 ** If the value in register P2 is zero the result is NULL.
   53662 ** If either operand is NULL, the result is NULL.
   53663 */
   53664 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
   53665 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
   53666 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
   53667 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
   53668 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
   53669 #if 0  /* local variables moved into u.af */
   53670   int flags;      /* Combined MEM_* flags from both inputs */
   53671   i64 iA;         /* Integer value of left operand */
   53672   i64 iB;         /* Integer value of right operand */
   53673   double rA;      /* Real value of left operand */
   53674   double rB;      /* Real value of right operand */
   53675 #endif /* local variables moved into u.af */
   53676 
   53677   pIn1 = &aMem[pOp->p1];
   53678   applyNumericAffinity(pIn1);
   53679   pIn2 = &aMem[pOp->p2];
   53680   applyNumericAffinity(pIn2);
   53681   pOut = &aMem[pOp->p3];
   53682   u.af.flags = pIn1->flags | pIn2->flags;
   53683   if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
   53684   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
   53685     u.af.iA = pIn1->u.i;
   53686     u.af.iB = pIn2->u.i;
   53687     switch( pOp->opcode ){
   53688       case OP_Add:         u.af.iB += u.af.iA;       break;
   53689       case OP_Subtract:    u.af.iB -= u.af.iA;       break;
   53690       case OP_Multiply:    u.af.iB *= u.af.iA;       break;
   53691       case OP_Divide: {
   53692         if( u.af.iA==0 ) goto arithmetic_result_is_null;
   53693         /* Dividing the largest possible negative 64-bit integer (1<<63) by
   53694         ** -1 returns an integer too large to store in a 64-bit data-type. On
   53695         ** some architectures, the value overflows to (1<<63). On others,
   53696         ** a SIGFPE is issued. The following statement normalizes this
   53697         ** behavior so that all architectures behave as if integer
   53698         ** overflow occurred.
   53699         */
   53700         if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) u.af.iA = 1;
   53701         u.af.iB /= u.af.iA;
   53702         break;
   53703       }
   53704       default: {
   53705         if( u.af.iA==0 ) goto arithmetic_result_is_null;
   53706         if( u.af.iA==-1 ) u.af.iA = 1;
   53707         u.af.iB %= u.af.iA;
   53708         break;
   53709       }
   53710     }
   53711     pOut->u.i = u.af.iB;
   53712     MemSetTypeFlag(pOut, MEM_Int);
   53713   }else{
   53714     u.af.rA = sqlite3VdbeRealValue(pIn1);
   53715     u.af.rB = sqlite3VdbeRealValue(pIn2);
   53716     switch( pOp->opcode ){
   53717       case OP_Add:         u.af.rB += u.af.rA;       break;
   53718       case OP_Subtract:    u.af.rB -= u.af.rA;       break;
   53719       case OP_Multiply:    u.af.rB *= u.af.rA;       break;
   53720       case OP_Divide: {
   53721         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   53722         if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
   53723         u.af.rB /= u.af.rA;
   53724         break;
   53725       }
   53726       default: {
   53727         u.af.iA = (i64)u.af.rA;
   53728         u.af.iB = (i64)u.af.rB;
   53729         if( u.af.iA==0 ) goto arithmetic_result_is_null;
   53730         if( u.af.iA==-1 ) u.af.iA = 1;
   53731         u.af.rB = (double)(u.af.iB % u.af.iA);
   53732         break;
   53733       }
   53734     }
   53735     if( sqlite3IsNaN(u.af.rB) ){
   53736       goto arithmetic_result_is_null;
   53737     }
   53738     pOut->r = u.af.rB;
   53739     MemSetTypeFlag(pOut, MEM_Real);
   53740     if( (u.af.flags & MEM_Real)==0 ){
   53741       sqlite3VdbeIntegerAffinity(pOut);
   53742     }
   53743   }
   53744   break;
   53745 
   53746 arithmetic_result_is_null:
   53747   sqlite3VdbeMemSetNull(pOut);
   53748   break;
   53749 }
   53750 
   53751 /* Opcode: CollSeq * * P4
   53752 **
   53753 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
   53754 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
   53755 ** be returned. This is used by the built-in min(), max() and nullif()
   53756 ** functions.
   53757 **
   53758 ** The interface used by the implementation of the aforementioned functions
   53759 ** to retrieve the collation sequence set by this opcode is not available
   53760 ** publicly, only to user functions defined in func.c.
   53761 */
   53762 case OP_CollSeq: {
   53763   assert( pOp->p4type==P4_COLLSEQ );
   53764   break;
   53765 }
   53766 
   53767 /* Opcode: Function P1 P2 P3 P4 P5
   53768 **
   53769 ** Invoke a user function (P4 is a pointer to a Function structure that
   53770 ** defines the function) with P5 arguments taken from register P2 and
   53771 ** successors.  The result of the function is stored in register P3.
   53772 ** Register P3 must not be one of the function inputs.
   53773 **
   53774 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
   53775 ** function was determined to be constant at compile time. If the first
   53776 ** argument was constant then bit 0 of P1 is set. This is used to determine
   53777 ** whether meta data associated with a user function argument using the
   53778 ** sqlite3_set_auxdata() API may be safely retained until the next
   53779 ** invocation of this opcode.
   53780 **
   53781 ** See also: AggStep and AggFinal
   53782 */
   53783 case OP_Function: {
   53784 #if 0  /* local variables moved into u.ag */
   53785   int i;
   53786   Mem *pArg;
   53787   sqlite3_context ctx;
   53788   sqlite3_value **apVal;
   53789   int n;
   53790 #endif /* local variables moved into u.ag */
   53791 
   53792   u.ag.n = pOp->p5;
   53793   u.ag.apVal = p->apArg;
   53794   assert( u.ag.apVal || u.ag.n==0 );
   53795 
   53796   assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
   53797   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
   53798   u.ag.pArg = &aMem[pOp->p2];
   53799   for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
   53800     u.ag.apVal[u.ag.i] = u.ag.pArg;
   53801     sqlite3VdbeMemStoreType(u.ag.pArg);
   53802     REGISTER_TRACE(pOp->p2, u.ag.pArg);
   53803   }
   53804 
   53805   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
   53806   if( pOp->p4type==P4_FUNCDEF ){
   53807     u.ag.ctx.pFunc = pOp->p4.pFunc;
   53808     u.ag.ctx.pVdbeFunc = 0;
   53809   }else{
   53810     u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
   53811     u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
   53812   }
   53813 
   53814   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   53815   pOut = &aMem[pOp->p3];
   53816   u.ag.ctx.s.flags = MEM_Null;
   53817   u.ag.ctx.s.db = db;
   53818   u.ag.ctx.s.xDel = 0;
   53819   u.ag.ctx.s.zMalloc = 0;
   53820 
   53821   /* The output cell may already have a buffer allocated. Move
   53822   ** the pointer to u.ag.ctx.s so in case the user-function can use
   53823   ** the already allocated buffer instead of allocating a new one.
   53824   */
   53825   sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
   53826   MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
   53827 
   53828   u.ag.ctx.isError = 0;
   53829   if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
   53830     assert( pOp>aOp );
   53831     assert( pOp[-1].p4type==P4_COLLSEQ );
   53832     assert( pOp[-1].opcode==OP_CollSeq );
   53833     u.ag.ctx.pColl = pOp[-1].p4.pColl;
   53834   }
   53835   (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal);
   53836   if( db->mallocFailed ){
   53837     /* Even though a malloc() has failed, the implementation of the
   53838     ** user function may have called an sqlite3_result_XXX() function
   53839     ** to return a value. The following call releases any resources
   53840     ** associated with such a value.
   53841     */
   53842     sqlite3VdbeMemRelease(&u.ag.ctx.s);
   53843     goto no_mem;
   53844   }
   53845 
   53846   /* If any auxiliary data functions have been called by this user function,
   53847   ** immediately call the destructor for any non-static values.
   53848   */
   53849   if( u.ag.ctx.pVdbeFunc ){
   53850     sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
   53851     pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
   53852     pOp->p4type = P4_VDBEFUNC;
   53853   }
   53854 
   53855   /* If the function returned an error, throw an exception */
   53856   if( u.ag.ctx.isError ){
   53857     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
   53858     rc = u.ag.ctx.isError;
   53859   }
   53860 
   53861   /* Copy the result of the function into register P3 */
   53862   sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
   53863   sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
   53864   if( sqlite3VdbeMemTooBig(pOut) ){
   53865     goto too_big;
   53866   }
   53867   REGISTER_TRACE(pOp->p3, pOut);
   53868   UPDATE_MAX_BLOBSIZE(pOut);
   53869   break;
   53870 }
   53871 
   53872 /* Opcode: BitAnd P1 P2 P3 * *
   53873 **
   53874 ** Take the bit-wise AND of the values in register P1 and P2 and
   53875 ** store the result in register P3.
   53876 ** If either input is NULL, the result is NULL.
   53877 */
   53878 /* Opcode: BitOr P1 P2 P3 * *
   53879 **
   53880 ** Take the bit-wise OR of the values in register P1 and P2 and
   53881 ** store the result in register P3.
   53882 ** If either input is NULL, the result is NULL.
   53883 */
   53884 /* Opcode: ShiftLeft P1 P2 P3 * *
   53885 **
   53886 ** Shift the integer value in register P2 to the left by the
   53887 ** number of bits specified by the integer in regiser P1.
   53888 ** Store the result in register P3.
   53889 ** If either input is NULL, the result is NULL.
   53890 */
   53891 /* Opcode: ShiftRight P1 P2 P3 * *
   53892 **
   53893 ** Shift the integer value in register P2 to the right by the
   53894 ** number of bits specified by the integer in register P1.
   53895 ** Store the result in register P3.
   53896 ** If either input is NULL, the result is NULL.
   53897 */
   53898 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
   53899 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
   53900 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
   53901 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
   53902 #if 0  /* local variables moved into u.ah */
   53903   i64 a;
   53904   i64 b;
   53905 #endif /* local variables moved into u.ah */
   53906 
   53907   pIn1 = &aMem[pOp->p1];
   53908   pIn2 = &aMem[pOp->p2];
   53909   pOut = &aMem[pOp->p3];
   53910   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
   53911     sqlite3VdbeMemSetNull(pOut);
   53912     break;
   53913   }
   53914   u.ah.a = sqlite3VdbeIntValue(pIn2);
   53915   u.ah.b = sqlite3VdbeIntValue(pIn1);
   53916   switch( pOp->opcode ){
   53917     case OP_BitAnd:      u.ah.a &= u.ah.b;     break;
   53918     case OP_BitOr:       u.ah.a |= u.ah.b;     break;
   53919     case OP_ShiftLeft:   u.ah.a <<= u.ah.b;    break;
   53920     default:  assert( pOp->opcode==OP_ShiftRight );
   53921                          u.ah.a >>= u.ah.b;    break;
   53922   }
   53923   pOut->u.i = u.ah.a;
   53924   MemSetTypeFlag(pOut, MEM_Int);
   53925   break;
   53926 }
   53927 
   53928 /* Opcode: AddImm  P1 P2 * * *
   53929 **
   53930 ** Add the constant P2 to the value in register P1.
   53931 ** The result is always an integer.
   53932 **
   53933 ** To force any register to be an integer, just add 0.
   53934 */
   53935 case OP_AddImm: {            /* in1 */
   53936   pIn1 = &aMem[pOp->p1];
   53937   sqlite3VdbeMemIntegerify(pIn1);
   53938   pIn1->u.i += pOp->p2;
   53939   break;
   53940 }
   53941 
   53942 /* Opcode: MustBeInt P1 P2 * * *
   53943 **
   53944 ** Force the value in register P1 to be an integer.  If the value
   53945 ** in P1 is not an integer and cannot be converted into an integer
   53946 ** without data loss, then jump immediately to P2, or if P2==0
   53947 ** raise an SQLITE_MISMATCH exception.
   53948 */
   53949 case OP_MustBeInt: {            /* jump, in1 */
   53950   pIn1 = &aMem[pOp->p1];
   53951   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
   53952   if( (pIn1->flags & MEM_Int)==0 ){
   53953     if( pOp->p2==0 ){
   53954       rc = SQLITE_MISMATCH;
   53955       goto abort_due_to_error;
   53956     }else{
   53957       pc = pOp->p2 - 1;
   53958     }
   53959   }else{
   53960     MemSetTypeFlag(pIn1, MEM_Int);
   53961   }
   53962   break;
   53963 }
   53964 
   53965 /* Opcode: RealAffinity P1 * * * *
   53966 **
   53967 ** If register P1 holds an integer convert it to a real value.
   53968 **
   53969 ** This opcode is used when extracting information from a column that
   53970 ** has REAL affinity.  Such column values may still be stored as
   53971 ** integers, for space efficiency, but after extraction we want them
   53972 ** to have only a real value.
   53973 */
   53974 case OP_RealAffinity: {                  /* in1 */
   53975   pIn1 = &aMem[pOp->p1];
   53976   if( pIn1->flags & MEM_Int ){
   53977     sqlite3VdbeMemRealify(pIn1);
   53978   }
   53979   break;
   53980 }
   53981 
   53982 #ifndef SQLITE_OMIT_CAST
   53983 /* Opcode: ToText P1 * * * *
   53984 **
   53985 ** Force the value in register P1 to be text.
   53986 ** If the value is numeric, convert it to a string using the
   53987 ** equivalent of printf().  Blob values are unchanged and
   53988 ** are afterwards simply interpreted as text.
   53989 **
   53990 ** A NULL value is not changed by this routine.  It remains NULL.
   53991 */
   53992 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
   53993   pIn1 = &aMem[pOp->p1];
   53994   if( pIn1->flags & MEM_Null ) break;
   53995   assert( MEM_Str==(MEM_Blob>>3) );
   53996   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
   53997   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
   53998   rc = ExpandBlob(pIn1);
   53999   assert( pIn1->flags & MEM_Str || db->mallocFailed );
   54000   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
   54001   UPDATE_MAX_BLOBSIZE(pIn1);
   54002   break;
   54003 }
   54004 
   54005 /* Opcode: ToBlob P1 * * * *
   54006 **
   54007 ** Force the value in register P1 to be a BLOB.
   54008 ** If the value is numeric, convert it to a string first.
   54009 ** Strings are simply reinterpreted as blobs with no change
   54010 ** to the underlying data.
   54011 **
   54012 ** A NULL value is not changed by this routine.  It remains NULL.
   54013 */
   54014 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
   54015   pIn1 = &aMem[pOp->p1];
   54016   if( pIn1->flags & MEM_Null ) break;
   54017   if( (pIn1->flags & MEM_Blob)==0 ){
   54018     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
   54019     assert( pIn1->flags & MEM_Str || db->mallocFailed );
   54020     MemSetTypeFlag(pIn1, MEM_Blob);
   54021   }else{
   54022     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
   54023   }
   54024   UPDATE_MAX_BLOBSIZE(pIn1);
   54025   break;
   54026 }
   54027 
   54028 /* Opcode: ToNumeric P1 * * * *
   54029 **
   54030 ** Force the value in register P1 to be numeric (either an
   54031 ** integer or a floating-point number.)
   54032 ** If the value is text or blob, try to convert it to an using the
   54033 ** equivalent of atoi() or atof() and store 0 if no such conversion
   54034 ** is possible.
   54035 **
   54036 ** A NULL value is not changed by this routine.  It remains NULL.
   54037 */
   54038 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
   54039   pIn1 = &aMem[pOp->p1];
   54040   if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
   54041     sqlite3VdbeMemNumerify(pIn1);
   54042   }
   54043   break;
   54044 }
   54045 #endif /* SQLITE_OMIT_CAST */
   54046 
   54047 /* Opcode: ToInt P1 * * * *
   54048 **
   54049 ** Force the value in register P1 be an integer.  If
   54050 ** The value is currently a real number, drop its fractional part.
   54051 ** If the value is text or blob, try to convert it to an integer using the
   54052 ** equivalent of atoi() and store 0 if no such conversion is possible.
   54053 **
   54054 ** A NULL value is not changed by this routine.  It remains NULL.
   54055 */
   54056 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
   54057   pIn1 = &aMem[pOp->p1];
   54058   if( (pIn1->flags & MEM_Null)==0 ){
   54059     sqlite3VdbeMemIntegerify(pIn1);
   54060   }
   54061   break;
   54062 }
   54063 
   54064 #ifndef SQLITE_OMIT_CAST
   54065 /* Opcode: ToReal P1 * * * *
   54066 **
   54067 ** Force the value in register P1 to be a floating point number.
   54068 ** If The value is currently an integer, convert it.
   54069 ** If the value is text or blob, try to convert it to an integer using the
   54070 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
   54071 **
   54072 ** A NULL value is not changed by this routine.  It remains NULL.
   54073 */
   54074 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
   54075   pIn1 = &aMem[pOp->p1];
   54076   if( (pIn1->flags & MEM_Null)==0 ){
   54077     sqlite3VdbeMemRealify(pIn1);
   54078   }
   54079   break;
   54080 }
   54081 #endif /* SQLITE_OMIT_CAST */
   54082 
   54083 /* Opcode: Lt P1 P2 P3 P4 P5
   54084 **
   54085 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
   54086 ** jump to address P2.
   54087 **
   54088 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
   54089 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
   54090 ** bit is clear then fall thru if either operand is NULL.
   54091 **
   54092 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
   54093 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
   54094 ** to coerce both inputs according to this affinity before the
   54095 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
   54096 ** affinity is used. Note that the affinity conversions are stored
   54097 ** back into the input registers P1 and P3.  So this opcode can cause
   54098 ** persistent changes to registers P1 and P3.
   54099 **
   54100 ** Once any conversions have taken place, and neither value is NULL,
   54101 ** the values are compared. If both values are blobs then memcmp() is
   54102 ** used to determine the results of the comparison.  If both values
   54103 ** are text, then the appropriate collating function specified in
   54104 ** P4 is  used to do the comparison.  If P4 is not specified then
   54105 ** memcmp() is used to compare text string.  If both values are
   54106 ** numeric, then a numeric comparison is used. If the two values
   54107 ** are of different types, then numbers are considered less than
   54108 ** strings and strings are considered less than blobs.
   54109 **
   54110 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
   54111 ** store a boolean result (either 0, or 1, or NULL) in register P2.
   54112 */
   54113 /* Opcode: Ne P1 P2 P3 P4 P5
   54114 **
   54115 ** This works just like the Lt opcode except that the jump is taken if
   54116 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
   54117 ** additional information.
   54118 **
   54119 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
   54120 ** true or false and is never NULL.  If both operands are NULL then the result
   54121 ** of comparison is false.  If either operand is NULL then the result is true.
   54122 ** If neither operand is NULL the the result is the same as it would be if
   54123 ** the SQLITE_NULLEQ flag were omitted from P5.
   54124 */
   54125 /* Opcode: Eq P1 P2 P3 P4 P5
   54126 **
   54127 ** This works just like the Lt opcode except that the jump is taken if
   54128 ** the operands in registers P1 and P3 are equal.
   54129 ** See the Lt opcode for additional information.
   54130 **
   54131 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
   54132 ** true or false and is never NULL.  If both operands are NULL then the result
   54133 ** of comparison is true.  If either operand is NULL then the result is false.
   54134 ** If neither operand is NULL the the result is the same as it would be if
   54135 ** the SQLITE_NULLEQ flag were omitted from P5.
   54136 */
   54137 /* Opcode: Le P1 P2 P3 P4 P5
   54138 **
   54139 ** This works just like the Lt opcode except that the jump is taken if
   54140 ** the content of register P3 is less than or equal to the content of
   54141 ** register P1.  See the Lt opcode for additional information.
   54142 */
   54143 /* Opcode: Gt P1 P2 P3 P4 P5
   54144 **
   54145 ** This works just like the Lt opcode except that the jump is taken if
   54146 ** the content of register P3 is greater than the content of
   54147 ** register P1.  See the Lt opcode for additional information.
   54148 */
   54149 /* Opcode: Ge P1 P2 P3 P4 P5
   54150 **
   54151 ** This works just like the Lt opcode except that the jump is taken if
   54152 ** the content of register P3 is greater than or equal to the content of
   54153 ** register P1.  See the Lt opcode for additional information.
   54154 */
   54155 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
   54156 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
   54157 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
   54158 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
   54159 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
   54160 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
   54161 #if 0  /* local variables moved into u.ai */
   54162   int res;            /* Result of the comparison of pIn1 against pIn3 */
   54163   char affinity;      /* Affinity to use for comparison */
   54164 #endif /* local variables moved into u.ai */
   54165 
   54166   pIn1 = &aMem[pOp->p1];
   54167   pIn3 = &aMem[pOp->p3];
   54168   if( (pIn1->flags | pIn3->flags)&MEM_Null ){
   54169     /* One or both operands are NULL */
   54170     if( pOp->p5 & SQLITE_NULLEQ ){
   54171       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
   54172       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
   54173       ** or not both operands are null.
   54174       */
   54175       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
   54176       u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
   54177     }else{
   54178       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
   54179       ** then the result is always NULL.
   54180       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
   54181       */
   54182       if( pOp->p5 & SQLITE_STOREP2 ){
   54183         pOut = &aMem[pOp->p2];
   54184         MemSetTypeFlag(pOut, MEM_Null);
   54185         REGISTER_TRACE(pOp->p2, pOut);
   54186       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
   54187         pc = pOp->p2-1;
   54188       }
   54189       break;
   54190     }
   54191   }else{
   54192     /* Neither operand is NULL.  Do a comparison. */
   54193     u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
   54194     if( u.ai.affinity ){
   54195       applyAffinity(pIn1, u.ai.affinity, encoding);
   54196       applyAffinity(pIn3, u.ai.affinity, encoding);
   54197       if( db->mallocFailed ) goto no_mem;
   54198     }
   54199 
   54200     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
   54201     ExpandBlob(pIn1);
   54202     ExpandBlob(pIn3);
   54203     u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
   54204   }
   54205   switch( pOp->opcode ){
   54206     case OP_Eq:    u.ai.res = u.ai.res==0;     break;
   54207     case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
   54208     case OP_Lt:    u.ai.res = u.ai.res<0;      break;
   54209     case OP_Le:    u.ai.res = u.ai.res<=0;     break;
   54210     case OP_Gt:    u.ai.res = u.ai.res>0;      break;
   54211     default:       u.ai.res = u.ai.res>=0;     break;
   54212   }
   54213 
   54214   if( pOp->p5 & SQLITE_STOREP2 ){
   54215     pOut = &aMem[pOp->p2];
   54216     MemSetTypeFlag(pOut, MEM_Int);
   54217     pOut->u.i = u.ai.res;
   54218     REGISTER_TRACE(pOp->p2, pOut);
   54219   }else if( u.ai.res ){
   54220     pc = pOp->p2-1;
   54221   }
   54222   break;
   54223 }
   54224 
   54225 /* Opcode: Permutation * * * P4 *
   54226 **
   54227 ** Set the permutation used by the OP_Compare operator to be the array
   54228 ** of integers in P4.
   54229 **
   54230 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
   54231 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
   54232 ** immediately prior to the OP_Compare.
   54233 */
   54234 case OP_Permutation: {
   54235   assert( pOp->p4type==P4_INTARRAY );
   54236   assert( pOp->p4.ai );
   54237   aPermute = pOp->p4.ai;
   54238   break;
   54239 }
   54240 
   54241 /* Opcode: Compare P1 P2 P3 P4 *
   54242 **
   54243 ** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
   54244 ** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
   54245 ** the comparison for use by the next OP_Jump instruct.
   54246 **
   54247 ** P4 is a KeyInfo structure that defines collating sequences and sort
   54248 ** orders for the comparison.  The permutation applies to registers
   54249 ** only.  The KeyInfo elements are used sequentially.
   54250 **
   54251 ** The comparison is a sort comparison, so NULLs compare equal,
   54252 ** NULLs are less than numbers, numbers are less than strings,
   54253 ** and strings are less than blobs.
   54254 */
   54255 case OP_Compare: {
   54256 #if 0  /* local variables moved into u.aj */
   54257   int n;
   54258   int i;
   54259   int p1;
   54260   int p2;
   54261   const KeyInfo *pKeyInfo;
   54262   int idx;
   54263   CollSeq *pColl;    /* Collating sequence to use on this term */
   54264   int bRev;          /* True for DESCENDING sort order */
   54265 #endif /* local variables moved into u.aj */
   54266 
   54267   u.aj.n = pOp->p3;
   54268   u.aj.pKeyInfo = pOp->p4.pKeyInfo;
   54269   assert( u.aj.n>0 );
   54270   assert( u.aj.pKeyInfo!=0 );
   54271   u.aj.p1 = pOp->p1;
   54272   u.aj.p2 = pOp->p2;
   54273 #if SQLITE_DEBUG
   54274   if( aPermute ){
   54275     int k, mx = 0;
   54276     for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
   54277     assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
   54278     assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
   54279   }else{
   54280     assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
   54281     assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
   54282   }
   54283 #endif /* SQLITE_DEBUG */
   54284   for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
   54285     u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
   54286     REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
   54287     REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
   54288     assert( u.aj.i<u.aj.pKeyInfo->nField );
   54289     u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
   54290     u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
   54291     iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
   54292     if( iCompare ){
   54293       if( u.aj.bRev ) iCompare = -iCompare;
   54294       break;
   54295     }
   54296   }
   54297   aPermute = 0;
   54298   break;
   54299 }
   54300 
   54301 /* Opcode: Jump P1 P2 P3 * *
   54302 **
   54303 ** Jump to the instruction at address P1, P2, or P3 depending on whether
   54304 ** in the most recent OP_Compare instruction the P1 vector was less than
   54305 ** equal to, or greater than the P2 vector, respectively.
   54306 */
   54307 case OP_Jump: {             /* jump */
   54308   if( iCompare<0 ){
   54309     pc = pOp->p1 - 1;
   54310   }else if( iCompare==0 ){
   54311     pc = pOp->p2 - 1;
   54312   }else{
   54313     pc = pOp->p3 - 1;
   54314   }
   54315   break;
   54316 }
   54317 
   54318 /* Opcode: And P1 P2 P3 * *
   54319 **
   54320 ** Take the logical AND of the values in registers P1 and P2 and
   54321 ** write the result into register P3.
   54322 **
   54323 ** If either P1 or P2 is 0 (false) then the result is 0 even if
   54324 ** the other input is NULL.  A NULL and true or two NULLs give
   54325 ** a NULL output.
   54326 */
   54327 /* Opcode: Or P1 P2 P3 * *
   54328 **
   54329 ** Take the logical OR of the values in register P1 and P2 and
   54330 ** store the answer in register P3.
   54331 **
   54332 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
   54333 ** even if the other input is NULL.  A NULL and false or two NULLs
   54334 ** give a NULL output.
   54335 */
   54336 case OP_And:              /* same as TK_AND, in1, in2, out3 */
   54337 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
   54338 #if 0  /* local variables moved into u.ak */
   54339   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   54340   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   54341 #endif /* local variables moved into u.ak */
   54342 
   54343   pIn1 = &aMem[pOp->p1];
   54344   if( pIn1->flags & MEM_Null ){
   54345     u.ak.v1 = 2;
   54346   }else{
   54347     u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
   54348   }
   54349   pIn2 = &aMem[pOp->p2];
   54350   if( pIn2->flags & MEM_Null ){
   54351     u.ak.v2 = 2;
   54352   }else{
   54353     u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
   54354   }
   54355   if( pOp->opcode==OP_And ){
   54356     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
   54357     u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
   54358   }else{
   54359     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
   54360     u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
   54361   }
   54362   pOut = &aMem[pOp->p3];
   54363   if( u.ak.v1==2 ){
   54364     MemSetTypeFlag(pOut, MEM_Null);
   54365   }else{
   54366     pOut->u.i = u.ak.v1;
   54367     MemSetTypeFlag(pOut, MEM_Int);
   54368   }
   54369   break;
   54370 }
   54371 
   54372 /* Opcode: Not P1 P2 * * *
   54373 **
   54374 ** Interpret the value in register P1 as a boolean value.  Store the
   54375 ** boolean complement in register P2.  If the value in register P1 is
   54376 ** NULL, then a NULL is stored in P2.
   54377 */
   54378 case OP_Not: {                /* same as TK_NOT, in1, out2 */
   54379   pIn1 = &aMem[pOp->p1];
   54380   pOut = &aMem[pOp->p2];
   54381   if( pIn1->flags & MEM_Null ){
   54382     sqlite3VdbeMemSetNull(pOut);
   54383   }else{
   54384     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
   54385   }
   54386   break;
   54387 }
   54388 
   54389 /* Opcode: BitNot P1 P2 * * *
   54390 **
   54391 ** Interpret the content of register P1 as an integer.  Store the
   54392 ** ones-complement of the P1 value into register P2.  If P1 holds
   54393 ** a NULL then store a NULL in P2.
   54394 */
   54395 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
   54396   pIn1 = &aMem[pOp->p1];
   54397   pOut = &aMem[pOp->p2];
   54398   if( pIn1->flags & MEM_Null ){
   54399     sqlite3VdbeMemSetNull(pOut);
   54400   }else{
   54401     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
   54402   }
   54403   break;
   54404 }
   54405 
   54406 /* Opcode: If P1 P2 P3 * *
   54407 **
   54408 ** Jump to P2 if the value in register P1 is true.  The value is
   54409 ** is considered true if it is numeric and non-zero.  If the value
   54410 ** in P1 is NULL then take the jump if P3 is true.
   54411 */
   54412 /* Opcode: IfNot P1 P2 P3 * *
   54413 **
   54414 ** Jump to P2 if the value in register P1 is False.  The value is
   54415 ** is considered true if it has a numeric value of zero.  If the value
   54416 ** in P1 is NULL then take the jump if P3 is true.
   54417 */
   54418 case OP_If:                 /* jump, in1 */
   54419 case OP_IfNot: {            /* jump, in1 */
   54420 #if 0  /* local variables moved into u.al */
   54421   int c;
   54422 #endif /* local variables moved into u.al */
   54423   pIn1 = &aMem[pOp->p1];
   54424   if( pIn1->flags & MEM_Null ){
   54425     u.al.c = pOp->p3;
   54426   }else{
   54427 #ifdef SQLITE_OMIT_FLOATING_POINT
   54428     u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
   54429 #else
   54430     u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
   54431 #endif
   54432     if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
   54433   }
   54434   if( u.al.c ){
   54435     pc = pOp->p2-1;
   54436   }
   54437   break;
   54438 }
   54439 
   54440 /* Opcode: IsNull P1 P2 * * *
   54441 **
   54442 ** Jump to P2 if the value in register P1 is NULL.
   54443 */
   54444 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
   54445   pIn1 = &aMem[pOp->p1];
   54446   if( (pIn1->flags & MEM_Null)!=0 ){
   54447     pc = pOp->p2 - 1;
   54448   }
   54449   break;
   54450 }
   54451 
   54452 /* Opcode: NotNull P1 P2 * * *
   54453 **
   54454 ** Jump to P2 if the value in register P1 is not NULL.
   54455 */
   54456 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
   54457   pIn1 = &aMem[pOp->p1];
   54458   if( (pIn1->flags & MEM_Null)==0 ){
   54459     pc = pOp->p2 - 1;
   54460   }
   54461   break;
   54462 }
   54463 
   54464 /* Opcode: Column P1 P2 P3 P4 P5
   54465 **
   54466 ** Interpret the data that cursor P1 points to as a structure built using
   54467 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
   54468 ** information about the format of the data.)  Extract the P2-th column
   54469 ** from this record.  If there are less that (P2+1)
   54470 ** values in the record, extract a NULL.
   54471 **
   54472 ** The value extracted is stored in register P3.
   54473 **
   54474 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
   54475 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
   54476 ** the result.
   54477 **
   54478 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
   54479 ** then the cache of the cursor is reset prior to extracting the column.
   54480 ** The first OP_Column against a pseudo-table after the value of the content
   54481 ** register has changed should have this bit set.
   54482 */
   54483 case OP_Column: {
   54484 #if 0  /* local variables moved into u.am */
   54485   u32 payloadSize;   /* Number of bytes in the record */
   54486   i64 payloadSize64; /* Number of bytes in the record */
   54487   int p1;            /* P1 value of the opcode */
   54488   int p2;            /* column number to retrieve */
   54489   VdbeCursor *pC;    /* The VDBE cursor */
   54490   char *zRec;        /* Pointer to complete record-data */
   54491   BtCursor *pCrsr;   /* The BTree cursor */
   54492   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
   54493   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
   54494   int nField;        /* number of fields in the record */
   54495   int len;           /* The length of the serialized data for the column */
   54496   int i;             /* Loop counter */
   54497   char *zData;       /* Part of the record being decoded */
   54498   Mem *pDest;        /* Where to write the extracted value */
   54499   Mem sMem;          /* For storing the record being decoded */
   54500   u8 *zIdx;          /* Index into header */
   54501   u8 *zEndHdr;       /* Pointer to first byte after the header */
   54502   u32 offset;        /* Offset into the data */
   54503   u32 szField;       /* Number of bytes in the content of a field */
   54504   int szHdr;         /* Size of the header size field at start of record */
   54505   int avail;         /* Number of bytes of available data */
   54506   Mem *pReg;         /* PseudoTable input register */
   54507 #endif /* local variables moved into u.am */
   54508 
   54509 
   54510   u.am.p1 = pOp->p1;
   54511   u.am.p2 = pOp->p2;
   54512   u.am.pC = 0;
   54513   memset(&u.am.sMem, 0, sizeof(u.am.sMem));
   54514   assert( u.am.p1<p->nCursor );
   54515   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   54516   u.am.pDest = &aMem[pOp->p3];
   54517   MemSetTypeFlag(u.am.pDest, MEM_Null);
   54518   u.am.zRec = 0;
   54519 
   54520   /* This block sets the variable u.am.payloadSize to be the total number of
   54521   ** bytes in the record.
   54522   **
   54523   ** u.am.zRec is set to be the complete text of the record if it is available.
   54524   ** The complete record text is always available for pseudo-tables
   54525   ** If the record is stored in a cursor, the complete record text
   54526   ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
   54527   ** If the data is unavailable,  u.am.zRec is set to NULL.
   54528   **
   54529   ** We also compute the number of columns in the record.  For cursors,
   54530   ** the number of columns is stored in the VdbeCursor.nField element.
   54531   */
   54532   u.am.pC = p->apCsr[u.am.p1];
   54533   assert( u.am.pC!=0 );
   54534 #ifndef SQLITE_OMIT_VIRTUALTABLE
   54535   assert( u.am.pC->pVtabCursor==0 );
   54536 #endif
   54537   u.am.pCrsr = u.am.pC->pCursor;
   54538   if( u.am.pCrsr!=0 ){
   54539     /* The record is stored in a B-Tree */
   54540     rc = sqlite3VdbeCursorMoveto(u.am.pC);
   54541     if( rc ) goto abort_due_to_error;
   54542     if( u.am.pC->nullRow ){
   54543       u.am.payloadSize = 0;
   54544     }else if( u.am.pC->cacheStatus==p->cacheCtr ){
   54545       u.am.payloadSize = u.am.pC->payloadSize;
   54546       u.am.zRec = (char*)u.am.pC->aRow;
   54547     }else if( u.am.pC->isIndex ){
   54548       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
   54549       rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
   54550       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
   54551       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
   54552       ** payload size, so it is impossible for u.am.payloadSize64 to be
   54553       ** larger than 32 bits. */
   54554       assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
   54555       u.am.payloadSize = (u32)u.am.payloadSize64;
   54556     }else{
   54557       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
   54558       rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
   54559       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
   54560     }
   54561   }else if( u.am.pC->pseudoTableReg>0 ){
   54562     u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
   54563     assert( u.am.pReg->flags & MEM_Blob );
   54564     u.am.payloadSize = u.am.pReg->n;
   54565     u.am.zRec = u.am.pReg->z;
   54566     u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
   54567     assert( u.am.payloadSize==0 || u.am.zRec!=0 );
   54568   }else{
   54569     /* Consider the row to be NULL */
   54570     u.am.payloadSize = 0;
   54571   }
   54572 
   54573   /* If u.am.payloadSize is 0, then just store a NULL */
   54574   if( u.am.payloadSize==0 ){
   54575     assert( u.am.pDest->flags&MEM_Null );
   54576     goto op_column_out;
   54577   }
   54578   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
   54579   if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   54580     goto too_big;
   54581   }
   54582 
   54583   u.am.nField = u.am.pC->nField;
   54584   assert( u.am.p2<u.am.nField );
   54585 
   54586   /* Read and parse the table header.  Store the results of the parse
   54587   ** into the record header cache fields of the cursor.
   54588   */
   54589   u.am.aType = u.am.pC->aType;
   54590   if( u.am.pC->cacheStatus==p->cacheCtr ){
   54591     u.am.aOffset = u.am.pC->aOffset;
   54592   }else{
   54593     assert(u.am.aType);
   54594     u.am.avail = 0;
   54595     u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
   54596     u.am.pC->payloadSize = u.am.payloadSize;
   54597     u.am.pC->cacheStatus = p->cacheCtr;
   54598 
   54599     /* Figure out how many bytes are in the header */
   54600     if( u.am.zRec ){
   54601       u.am.zData = u.am.zRec;
   54602     }else{
   54603       if( u.am.pC->isIndex ){
   54604         u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
   54605       }else{
   54606         u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
   54607       }
   54608       /* If KeyFetch()/DataFetch() managed to get the entire payload,
   54609       ** save the payload in the u.am.pC->aRow cache.  That will save us from
   54610       ** having to make additional calls to fetch the content portion of
   54611       ** the record.
   54612       */
   54613       assert( u.am.avail>=0 );
   54614       if( u.am.payloadSize <= (u32)u.am.avail ){
   54615         u.am.zRec = u.am.zData;
   54616         u.am.pC->aRow = (u8*)u.am.zData;
   54617       }else{
   54618         u.am.pC->aRow = 0;
   54619       }
   54620     }
   54621     /* The following assert is true in all cases accept when
   54622     ** the database file has been corrupted externally.
   54623     **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
   54624     u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
   54625 
   54626     /* Make sure a corrupt database has not given us an oversize header.
   54627     ** Do this now to avoid an oversize memory allocation.
   54628     **
   54629     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
   54630     ** types use so much data space that there can only be 4096 and 32 of
   54631     ** them, respectively.  So the maximum header length results from a
   54632     ** 3-byte type for each of the maximum of 32768 columns plus three
   54633     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
   54634     */
   54635     if( u.am.offset > 98307 ){
   54636       rc = SQLITE_CORRUPT_BKPT;
   54637       goto op_column_out;
   54638     }
   54639 
   54640     /* Compute in u.am.len the number of bytes of data we need to read in order
   54641     ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
   54642     ** u.am.nField might be significantly less than the true number of columns
   54643     ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
   54644     ** We want to minimize u.am.len in order to limit the size of the memory
   54645     ** allocation, especially if a corrupt database file has caused u.am.offset
   54646     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
   54647     ** still exceed Robson memory allocation limits on some configurations.
   54648     ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
   54649     ** will likely be much smaller since u.am.nField will likely be less than
   54650     ** 20 or so.  This insures that Robson memory allocation limits are
   54651     ** not exceeded even for corrupt database files.
   54652     */
   54653     u.am.len = u.am.nField*5 + 3;
   54654     if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
   54655 
   54656     /* The KeyFetch() or DataFetch() above are fast and will get the entire
   54657     ** record header in most cases.  But they will fail to get the complete
   54658     ** record header if the record header does not fit on a single page
   54659     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
   54660     ** acquire the complete header text.
   54661     */
   54662     if( !u.am.zRec && u.am.avail<u.am.len ){
   54663       u.am.sMem.flags = 0;
   54664       u.am.sMem.db = 0;
   54665       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
   54666       if( rc!=SQLITE_OK ){
   54667         goto op_column_out;
   54668       }
   54669       u.am.zData = u.am.sMem.z;
   54670     }
   54671     u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
   54672     u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
   54673 
   54674     /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
   54675     ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
   54676     ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
   54677     ** of the record to the start of the data for the u.am.i-th column
   54678     */
   54679     for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
   54680       if( u.am.zIdx<u.am.zEndHdr ){
   54681         u.am.aOffset[u.am.i] = u.am.offset;
   54682         u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
   54683         u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
   54684         u.am.offset += u.am.szField;
   54685         if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
   54686           u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
   54687           break;
   54688         }
   54689       }else{
   54690         /* If u.am.i is less that u.am.nField, then there are less fields in this
   54691         ** record than SetNumColumns indicated there are columns in the
   54692         ** table. Set the u.am.offset for any extra columns not present in
   54693         ** the record to 0. This tells code below to store a NULL
   54694         ** instead of deserializing a value from the record.
   54695         */
   54696         u.am.aOffset[u.am.i] = 0;
   54697       }
   54698     }
   54699     sqlite3VdbeMemRelease(&u.am.sMem);
   54700     u.am.sMem.flags = MEM_Null;
   54701 
   54702     /* If we have read more header data than was contained in the header,
   54703     ** or if the end of the last field appears to be past the end of the
   54704     ** record, or if the end of the last field appears to be before the end
   54705     ** of the record (when all fields present), then we must be dealing
   54706     ** with a corrupt database.
   54707     */
   54708     if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
   54709          || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
   54710       rc = SQLITE_CORRUPT_BKPT;
   54711       goto op_column_out;
   54712     }
   54713   }
   54714 
   54715   /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
   54716   ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
   54717   ** then there are not enough fields in the record to satisfy the
   54718   ** request.  In this case, set the value NULL or to P4 if P4 is
   54719   ** a pointer to a Mem object.
   54720   */
   54721   if( u.am.aOffset[u.am.p2] ){
   54722     assert( rc==SQLITE_OK );
   54723     if( u.am.zRec ){
   54724       sqlite3VdbeMemReleaseExternal(u.am.pDest);
   54725       sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
   54726     }else{
   54727       u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
   54728       sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
   54729       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
   54730       if( rc!=SQLITE_OK ){
   54731         goto op_column_out;
   54732       }
   54733       u.am.zData = u.am.sMem.z;
   54734       sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
   54735     }
   54736     u.am.pDest->enc = encoding;
   54737   }else{
   54738     if( pOp->p4type==P4_MEM ){
   54739       sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
   54740     }else{
   54741       assert( u.am.pDest->flags&MEM_Null );
   54742     }
   54743   }
   54744 
   54745   /* If we dynamically allocated space to hold the data (in the
   54746   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
   54747   ** dynamically allocated space over to the u.am.pDest structure.
   54748   ** This prevents a memory copy.
   54749   */
   54750   if( u.am.sMem.zMalloc ){
   54751     assert( u.am.sMem.z==u.am.sMem.zMalloc );
   54752     assert( !(u.am.pDest->flags & MEM_Dyn) );
   54753     assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
   54754     u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
   54755     u.am.pDest->flags |= MEM_Term;
   54756     u.am.pDest->z = u.am.sMem.z;
   54757     u.am.pDest->zMalloc = u.am.sMem.zMalloc;
   54758   }
   54759 
   54760   rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
   54761 
   54762 op_column_out:
   54763   UPDATE_MAX_BLOBSIZE(u.am.pDest);
   54764   REGISTER_TRACE(pOp->p3, u.am.pDest);
   54765   break;
   54766 }
   54767 
   54768 /* Opcode: Affinity P1 P2 * P4 *
   54769 **
   54770 ** Apply affinities to a range of P2 registers starting with P1.
   54771 **
   54772 ** P4 is a string that is P2 characters long. The nth character of the
   54773 ** string indicates the column affinity that should be used for the nth
   54774 ** memory cell in the range.
   54775 */
   54776 case OP_Affinity: {
   54777 #if 0  /* local variables moved into u.an */
   54778   const char *zAffinity;   /* The affinity to be applied */
   54779   char cAff;               /* A single character of affinity */
   54780 #endif /* local variables moved into u.an */
   54781 
   54782   u.an.zAffinity = pOp->p4.z;
   54783   assert( u.an.zAffinity!=0 );
   54784   assert( u.an.zAffinity[pOp->p2]==0 );
   54785   pIn1 = &aMem[pOp->p1];
   54786   while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
   54787     assert( pIn1 <= &p->aMem[p->nMem] );
   54788     ExpandBlob(pIn1);
   54789     applyAffinity(pIn1, u.an.cAff, encoding);
   54790     pIn1++;
   54791   }
   54792   break;
   54793 }
   54794 
   54795 /* Opcode: MakeRecord P1 P2 P3 P4 *
   54796 **
   54797 ** Convert P2 registers beginning with P1 into a single entry
   54798 ** suitable for use as a data record in a database table or as a key
   54799 ** in an index.  The details of the format are irrelevant as long as
   54800 ** the OP_Column opcode can decode the record later.
   54801 ** Refer to source code comments for the details of the record
   54802 ** format.
   54803 **
   54804 ** P4 may be a string that is P2 characters long.  The nth character of the
   54805 ** string indicates the column affinity that should be used for the nth
   54806 ** field of the index key.
   54807 **
   54808 ** The mapping from character to affinity is given by the SQLITE_AFF_
   54809 ** macros defined in sqliteInt.h.
   54810 **
   54811 ** If P4 is NULL then all index fields have the affinity NONE.
   54812 */
   54813 case OP_MakeRecord: {
   54814 #if 0  /* local variables moved into u.ao */
   54815   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
   54816   Mem *pRec;             /* The new record */
   54817   u64 nData;             /* Number of bytes of data space */
   54818   int nHdr;              /* Number of bytes of header space */
   54819   i64 nByte;             /* Data space required for this record */
   54820   int nZero;             /* Number of zero bytes at the end of the record */
   54821   int nVarint;           /* Number of bytes in a varint */
   54822   u32 serial_type;       /* Type field */
   54823   Mem *pData0;           /* First field to be combined into the record */
   54824   Mem *pLast;            /* Last field of the record */
   54825   int nField;            /* Number of fields in the record */
   54826   char *zAffinity;       /* The affinity string for the record */
   54827   int file_format;       /* File format to use for encoding */
   54828   int i;                 /* Space used in zNewRecord[] */
   54829   int len;               /* Length of a field */
   54830 #endif /* local variables moved into u.ao */
   54831 
   54832   /* Assuming the record contains N fields, the record format looks
   54833   ** like this:
   54834   **
   54835   ** ------------------------------------------------------------------------
   54836   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
   54837   ** ------------------------------------------------------------------------
   54838   **
   54839   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
   54840   ** and so froth.
   54841   **
   54842   ** Each type field is a varint representing the serial type of the
   54843   ** corresponding data element (see sqlite3VdbeSerialType()). The
   54844   ** hdr-size field is also a varint which is the offset from the beginning
   54845   ** of the record to data0.
   54846   */
   54847   u.ao.nData = 0;         /* Number of bytes of data space */
   54848   u.ao.nHdr = 0;          /* Number of bytes of header space */
   54849   u.ao.nByte = 0;         /* Data space required for this record */
   54850   u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
   54851   u.ao.nField = pOp->p1;
   54852   u.ao.zAffinity = pOp->p4.z;
   54853   assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
   54854   u.ao.pData0 = &aMem[u.ao.nField];
   54855   u.ao.nField = pOp->p2;
   54856   u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
   54857   u.ao.file_format = p->minWriteFileFormat;
   54858 
   54859   /* Loop through the elements that will make up the record to figure
   54860   ** out how much space is required for the new record.
   54861   */
   54862   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
   54863     if( u.ao.zAffinity ){
   54864       applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
   54865     }
   54866     if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
   54867       sqlite3VdbeMemExpandBlob(u.ao.pRec);
   54868     }
   54869     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
   54870     u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
   54871     u.ao.nData += u.ao.len;
   54872     u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
   54873     if( u.ao.pRec->flags & MEM_Zero ){
   54874       /* Only pure zero-filled BLOBs can be input to this Opcode.
   54875       ** We do not allow blobs with a prefix and a zero-filled tail. */
   54876       u.ao.nZero += u.ao.pRec->u.nZero;
   54877     }else if( u.ao.len ){
   54878       u.ao.nZero = 0;
   54879     }
   54880   }
   54881 
   54882   /* Add the initial header varint and total the size */
   54883   u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
   54884   if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
   54885     u.ao.nHdr++;
   54886   }
   54887   u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
   54888   if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   54889     goto too_big;
   54890   }
   54891 
   54892   /* Make sure the output register has a buffer large enough to store
   54893   ** the new record. The output register (pOp->p3) is not allowed to
   54894   ** be one of the input registers (because the following call to
   54895   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
   54896   */
   54897   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
   54898   pOut = &aMem[pOp->p3];
   54899   if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
   54900     goto no_mem;
   54901   }
   54902   u.ao.zNewRecord = (u8 *)pOut->z;
   54903 
   54904   /* Write the record */
   54905   u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
   54906   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
   54907     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
   54908     u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
   54909   }
   54910   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
   54911     u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
   54912   }
   54913   assert( u.ao.i==u.ao.nByte );
   54914 
   54915   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   54916   pOut->n = (int)u.ao.nByte;
   54917   pOut->flags = MEM_Blob | MEM_Dyn;
   54918   pOut->xDel = 0;
   54919   if( u.ao.nZero ){
   54920     pOut->u.nZero = u.ao.nZero;
   54921     pOut->flags |= MEM_Zero;
   54922   }
   54923   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
   54924   REGISTER_TRACE(pOp->p3, pOut);
   54925   UPDATE_MAX_BLOBSIZE(pOut);
   54926   break;
   54927 }
   54928 
   54929 /* Opcode: Count P1 P2 * * *
   54930 **
   54931 ** Store the number of entries (an integer value) in the table or index
   54932 ** opened by cursor P1 in register P2
   54933 */
   54934 #ifndef SQLITE_OMIT_BTREECOUNT
   54935 case OP_Count: {         /* out2-prerelease */
   54936 #if 0  /* local variables moved into u.ap */
   54937   i64 nEntry;
   54938   BtCursor *pCrsr;
   54939 #endif /* local variables moved into u.ap */
   54940 
   54941   u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
   54942   if( u.ap.pCrsr ){
   54943     rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
   54944   }else{
   54945     u.ap.nEntry = 0;
   54946   }
   54947   pOut->u.i = u.ap.nEntry;
   54948   break;
   54949 }
   54950 #endif
   54951 
   54952 /* Opcode: Savepoint P1 * * P4 *
   54953 **
   54954 ** Open, release or rollback the savepoint named by parameter P4, depending
   54955 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
   54956 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
   54957 */
   54958 case OP_Savepoint: {
   54959 #if 0  /* local variables moved into u.aq */
   54960   int p1;                         /* Value of P1 operand */
   54961   char *zName;                    /* Name of savepoint */
   54962   int nName;
   54963   Savepoint *pNew;
   54964   Savepoint *pSavepoint;
   54965   Savepoint *pTmp;
   54966   int iSavepoint;
   54967   int ii;
   54968 #endif /* local variables moved into u.aq */
   54969 
   54970   u.aq.p1 = pOp->p1;
   54971   u.aq.zName = pOp->p4.z;
   54972 
   54973   /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
   54974   ** transaction, then there cannot be any savepoints.
   54975   */
   54976   assert( db->pSavepoint==0 || db->autoCommit==0 );
   54977   assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
   54978   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
   54979   assert( checkSavepointCount(db) );
   54980 
   54981   if( u.aq.p1==SAVEPOINT_BEGIN ){
   54982     if( db->writeVdbeCnt>0 ){
   54983       /* A new savepoint cannot be created if there are active write
   54984       ** statements (i.e. open read/write incremental blob handles).
   54985       */
   54986       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
   54987         "SQL statements in progress");
   54988       rc = SQLITE_BUSY;
   54989     }else{
   54990       u.aq.nName = sqlite3Strlen30(u.aq.zName);
   54991 
   54992       /* Create a new savepoint structure. */
   54993       u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
   54994       if( u.aq.pNew ){
   54995         u.aq.pNew->zName = (char *)&u.aq.pNew[1];
   54996         memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
   54997 
   54998         /* If there is no open transaction, then mark this as a special
   54999         ** "transaction savepoint". */
   55000         if( db->autoCommit ){
   55001           db->autoCommit = 0;
   55002           db->isTransactionSavepoint = 1;
   55003         }else{
   55004           db->nSavepoint++;
   55005         }
   55006 
   55007         /* Link the new savepoint into the database handle's list. */
   55008         u.aq.pNew->pNext = db->pSavepoint;
   55009         db->pSavepoint = u.aq.pNew;
   55010         u.aq.pNew->nDeferredCons = db->nDeferredCons;
   55011       }
   55012     }
   55013   }else{
   55014     u.aq.iSavepoint = 0;
   55015 
   55016     /* Find the named savepoint. If there is no such savepoint, then an
   55017     ** an error is returned to the user.  */
   55018     for(
   55019       u.aq.pSavepoint = db->pSavepoint;
   55020       u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
   55021       u.aq.pSavepoint = u.aq.pSavepoint->pNext
   55022     ){
   55023       u.aq.iSavepoint++;
   55024     }
   55025     if( !u.aq.pSavepoint ){
   55026       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
   55027       rc = SQLITE_ERROR;
   55028     }else if(
   55029         db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
   55030     ){
   55031       /* It is not possible to release (commit) a savepoint if there are
   55032       ** active write statements. It is not possible to rollback a savepoint
   55033       ** if there are any active statements at all.
   55034       */
   55035       sqlite3SetString(&p->zErrMsg, db,
   55036         "cannot %s savepoint - SQL statements in progress",
   55037         (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
   55038       );
   55039       rc = SQLITE_BUSY;
   55040     }else{
   55041 
   55042       /* Determine whether or not this is a transaction savepoint. If so,
   55043       ** and this is a RELEASE command, then the current transaction
   55044       ** is committed.
   55045       */
   55046       int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
   55047       if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
   55048         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
   55049           goto vdbe_return;
   55050         }
   55051         db->autoCommit = 1;
   55052         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
   55053           p->pc = pc;
   55054           db->autoCommit = 0;
   55055           p->rc = rc = SQLITE_BUSY;
   55056           goto vdbe_return;
   55057         }
   55058         db->isTransactionSavepoint = 0;
   55059         rc = p->rc;
   55060       }else{
   55061         u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
   55062         for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
   55063           rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
   55064           if( rc!=SQLITE_OK ){
   55065             goto abort_due_to_error;
   55066           }
   55067         }
   55068         if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
   55069           sqlite3ExpirePreparedStatements(db);
   55070           sqlite3ResetInternalSchema(db, 0);
   55071         }
   55072       }
   55073 
   55074       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
   55075       ** savepoints nested inside of the savepoint being operated on. */
   55076       while( db->pSavepoint!=u.aq.pSavepoint ){
   55077         u.aq.pTmp = db->pSavepoint;
   55078         db->pSavepoint = u.aq.pTmp->pNext;
   55079         sqlite3DbFree(db, u.aq.pTmp);
   55080         db->nSavepoint--;
   55081       }
   55082 
   55083       /* If it is a RELEASE, then destroy the savepoint being operated on
   55084       ** too. If it is a ROLLBACK TO, then set the number of deferred
   55085       ** constraint violations present in the database to the value stored
   55086       ** when the savepoint was created.  */
   55087       if( u.aq.p1==SAVEPOINT_RELEASE ){
   55088         assert( u.aq.pSavepoint==db->pSavepoint );
   55089         db->pSavepoint = u.aq.pSavepoint->pNext;
   55090         sqlite3DbFree(db, u.aq.pSavepoint);
   55091         if( !isTransaction ){
   55092           db->nSavepoint--;
   55093         }
   55094       }else{
   55095         db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
   55096       }
   55097     }
   55098   }
   55099 
   55100   break;
   55101 }
   55102 
   55103 /* Opcode: AutoCommit P1 P2 * * *
   55104 **
   55105 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
   55106 ** back any currently active btree transactions. If there are any active
   55107 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
   55108 ** there are active writing VMs or active VMs that use shared cache.
   55109 **
   55110 ** This instruction causes the VM to halt.
   55111 */
   55112 case OP_AutoCommit: {
   55113 #if 0  /* local variables moved into u.ar */
   55114   int desiredAutoCommit;
   55115   int iRollback;
   55116   int turnOnAC;
   55117 #endif /* local variables moved into u.ar */
   55118 
   55119   u.ar.desiredAutoCommit = pOp->p1;
   55120   u.ar.iRollback = pOp->p2;
   55121   u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
   55122   assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
   55123   assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
   55124   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
   55125 
   55126   if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
   55127     /* If this instruction implements a ROLLBACK and other VMs are
   55128     ** still running, and a transaction is active, return an error indicating
   55129     ** that the other VMs must complete first.
   55130     */
   55131     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
   55132         "SQL statements in progress");
   55133     rc = SQLITE_BUSY;
   55134   }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
   55135     /* If this instruction implements a COMMIT and other VMs are writing
   55136     ** return an error indicating that the other VMs must complete first.
   55137     */
   55138     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
   55139         "SQL statements in progress");
   55140     rc = SQLITE_BUSY;
   55141   }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
   55142     if( u.ar.iRollback ){
   55143       assert( u.ar.desiredAutoCommit==1 );
   55144       sqlite3RollbackAll(db);
   55145       db->autoCommit = 1;
   55146     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
   55147       goto vdbe_return;
   55148     }else{
   55149       db->autoCommit = (u8)u.ar.desiredAutoCommit;
   55150       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
   55151         p->pc = pc;
   55152         db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
   55153         p->rc = rc = SQLITE_BUSY;
   55154         goto vdbe_return;
   55155       }
   55156     }
   55157     assert( db->nStatement==0 );
   55158     sqlite3CloseSavepoints(db);
   55159     if( p->rc==SQLITE_OK ){
   55160       rc = SQLITE_DONE;
   55161     }else{
   55162       rc = SQLITE_ERROR;
   55163     }
   55164     goto vdbe_return;
   55165   }else{
   55166     sqlite3SetString(&p->zErrMsg, db,
   55167         (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
   55168         (u.ar.iRollback)?"cannot rollback - no transaction is active":
   55169                    "cannot commit - no transaction is active"));
   55170 
   55171     rc = SQLITE_ERROR;
   55172   }
   55173   break;
   55174 }
   55175 
   55176 /* Opcode: Transaction P1 P2 * * *
   55177 **
   55178 ** Begin a transaction.  The transaction ends when a Commit or Rollback
   55179 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
   55180 ** transaction might also be rolled back if an error is encountered.
   55181 **
   55182 ** P1 is the index of the database file on which the transaction is
   55183 ** started.  Index 0 is the main database file and index 1 is the
   55184 ** file used for temporary tables.  Indices of 2 or more are used for
   55185 ** attached databases.
   55186 **
   55187 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
   55188 ** obtained on the database file when a write-transaction is started.  No
   55189 ** other process can start another write transaction while this transaction is
   55190 ** underway.  Starting a write transaction also creates a rollback journal. A
   55191 ** write transaction must be started before any changes can be made to the
   55192 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
   55193 ** on the file.
   55194 **
   55195 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
   55196 ** true (this flag is set if the Vdbe may modify more than one row and may
   55197 ** throw an ABORT exception), a statement transaction may also be opened.
   55198 ** More specifically, a statement transaction is opened iff the database
   55199 ** connection is currently not in autocommit mode, or if there are other
   55200 ** active statements. A statement transaction allows the affects of this
   55201 ** VDBE to be rolled back after an error without having to roll back the
   55202 ** entire transaction. If no error is encountered, the statement transaction
   55203 ** will automatically commit when the VDBE halts.
   55204 **
   55205 ** If P2 is zero, then a read-lock is obtained on the database file.
   55206 */
   55207 case OP_Transaction: {
   55208 #if 0  /* local variables moved into u.as */
   55209   Btree *pBt;
   55210 #endif /* local variables moved into u.as */
   55211 
   55212   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   55213   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
   55214   u.as.pBt = db->aDb[pOp->p1].pBt;
   55215 
   55216   if( u.as.pBt ){
   55217     rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
   55218     if( rc==SQLITE_BUSY ){
   55219       p->pc = pc;
   55220       p->rc = rc = SQLITE_BUSY;
   55221       goto vdbe_return;
   55222     }
   55223     if( rc!=SQLITE_OK ){
   55224       goto abort_due_to_error;
   55225     }
   55226 
   55227     if( pOp->p2 && p->usesStmtJournal
   55228      && (db->autoCommit==0 || db->activeVdbeCnt>1)
   55229     ){
   55230       assert( sqlite3BtreeIsInTrans(u.as.pBt) );
   55231       if( p->iStatement==0 ){
   55232         assert( db->nStatement>=0 && db->nSavepoint>=0 );
   55233         db->nStatement++;
   55234         p->iStatement = db->nSavepoint + db->nStatement;
   55235       }
   55236       rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
   55237 
   55238       /* Store the current value of the database handles deferred constraint
   55239       ** counter. If the statement transaction needs to be rolled back,
   55240       ** the value of this counter needs to be restored too.  */
   55241       p->nStmtDefCons = db->nDeferredCons;
   55242     }
   55243   }
   55244   break;
   55245 }
   55246 
   55247 /* Opcode: ReadCookie P1 P2 P3 * *
   55248 **
   55249 ** Read cookie number P3 from database P1 and write it into register P2.
   55250 ** P3==1 is the schema version.  P3==2 is the database format.
   55251 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
   55252 ** the main database file and P1==1 is the database file used to store
   55253 ** temporary tables.
   55254 **
   55255 ** There must be a read-lock on the database (either a transaction
   55256 ** must be started or there must be an open cursor) before
   55257 ** executing this instruction.
   55258 */
   55259 case OP_ReadCookie: {               /* out2-prerelease */
   55260 #if 0  /* local variables moved into u.at */
   55261   int iMeta;
   55262   int iDb;
   55263   int iCookie;
   55264 #endif /* local variables moved into u.at */
   55265 
   55266   u.at.iDb = pOp->p1;
   55267   u.at.iCookie = pOp->p3;
   55268   assert( pOp->p3<SQLITE_N_BTREE_META );
   55269   assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
   55270   assert( db->aDb[u.at.iDb].pBt!=0 );
   55271   assert( (p->btreeMask & (1<<u.at.iDb))!=0 );
   55272 
   55273   sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
   55274   pOut->u.i = u.at.iMeta;
   55275   break;
   55276 }
   55277 
   55278 /* Opcode: SetCookie P1 P2 P3 * *
   55279 **
   55280 ** Write the content of register P3 (interpreted as an integer)
   55281 ** into cookie number P2 of database P1.  P2==1 is the schema version.
   55282 ** P2==2 is the database format. P2==3 is the recommended pager cache
   55283 ** size, and so forth.  P1==0 is the main database file and P1==1 is the
   55284 ** database file used to store temporary tables.
   55285 **
   55286 ** A transaction must be started before executing this opcode.
   55287 */
   55288 case OP_SetCookie: {       /* in3 */
   55289 #if 0  /* local variables moved into u.au */
   55290   Db *pDb;
   55291 #endif /* local variables moved into u.au */
   55292   assert( pOp->p2<SQLITE_N_BTREE_META );
   55293   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   55294   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
   55295   u.au.pDb = &db->aDb[pOp->p1];
   55296   assert( u.au.pDb->pBt!=0 );
   55297   pIn3 = &aMem[pOp->p3];
   55298   sqlite3VdbeMemIntegerify(pIn3);
   55299   /* See note about index shifting on OP_ReadCookie */
   55300   rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
   55301   if( pOp->p2==BTREE_SCHEMA_VERSION ){
   55302     /* When the schema cookie changes, record the new cookie internally */
   55303     u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
   55304     db->flags |= SQLITE_InternChanges;
   55305   }else if( pOp->p2==BTREE_FILE_FORMAT ){
   55306     /* Record changes in the file format */
   55307     u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
   55308   }
   55309   if( pOp->p1==1 ){
   55310     /* Invalidate all prepared statements whenever the TEMP database
   55311     ** schema is changed.  Ticket #1644 */
   55312     sqlite3ExpirePreparedStatements(db);
   55313     p->expired = 0;
   55314   }
   55315   break;
   55316 }
   55317 
   55318 /* Opcode: VerifyCookie P1 P2 *
   55319 **
   55320 ** Check the value of global database parameter number 0 (the
   55321 ** schema version) and make sure it is equal to P2.
   55322 ** P1 is the database number which is 0 for the main database file
   55323 ** and 1 for the file holding temporary tables and some higher number
   55324 ** for auxiliary databases.
   55325 **
   55326 ** The cookie changes its value whenever the database schema changes.
   55327 ** This operation is used to detect when that the cookie has changed
   55328 ** and that the current process needs to reread the schema.
   55329 **
   55330 ** Either a transaction needs to have been started or an OP_Open needs
   55331 ** to be executed (to establish a read lock) before this opcode is
   55332 ** invoked.
   55333 */
   55334 case OP_VerifyCookie: {
   55335 #if 0  /* local variables moved into u.av */
   55336   int iMeta;
   55337   Btree *pBt;
   55338 #endif /* local variables moved into u.av */
   55339   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   55340   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
   55341   u.av.pBt = db->aDb[pOp->p1].pBt;
   55342   if( u.av.pBt ){
   55343     sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
   55344   }else{
   55345     u.av.iMeta = 0;
   55346   }
   55347   if( u.av.iMeta!=pOp->p2 ){
   55348     sqlite3DbFree(db, p->zErrMsg);
   55349     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
   55350     /* If the schema-cookie from the database file matches the cookie
   55351     ** stored with the in-memory representation of the schema, do
   55352     ** not reload the schema from the database file.
   55353     **
   55354     ** If virtual-tables are in use, this is not just an optimization.
   55355     ** Often, v-tables store their data in other SQLite tables, which
   55356     ** are queried from within xNext() and other v-table methods using
   55357     ** prepared queries. If such a query is out-of-date, we do not want to
   55358     ** discard the database schema, as the user code implementing the
   55359     ** v-table would have to be ready for the sqlite3_vtab structure itself
   55360     ** to be invalidated whenever sqlite3_step() is called from within
   55361     ** a v-table method.
   55362     */
   55363     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
   55364       sqlite3ResetInternalSchema(db, pOp->p1);
   55365     }
   55366 
   55367     sqlite3ExpirePreparedStatements(db);
   55368     rc = SQLITE_SCHEMA;
   55369   }
   55370   break;
   55371 }
   55372 
   55373 /* Opcode: OpenRead P1 P2 P3 P4 P5
   55374 **
   55375 ** Open a read-only cursor for the database table whose root page is
   55376 ** P2 in a database file.  The database file is determined by P3.
   55377 ** P3==0 means the main database, P3==1 means the database used for
   55378 ** temporary tables, and P3>1 means used the corresponding attached
   55379 ** database.  Give the new cursor an identifier of P1.  The P1
   55380 ** values need not be contiguous but all P1 values should be small integers.
   55381 ** It is an error for P1 to be negative.
   55382 **
   55383 ** If P5!=0 then use the content of register P2 as the root page, not
   55384 ** the value of P2 itself.
   55385 **
   55386 ** There will be a read lock on the database whenever there is an
   55387 ** open cursor.  If the database was unlocked prior to this instruction
   55388 ** then a read lock is acquired as part of this instruction.  A read
   55389 ** lock allows other processes to read the database but prohibits
   55390 ** any other process from modifying the database.  The read lock is
   55391 ** released when all cursors are closed.  If this instruction attempts
   55392 ** to get a read lock but fails, the script terminates with an
   55393 ** SQLITE_BUSY error code.
   55394 **
   55395 ** The P4 value may be either an integer (P4_INT32) or a pointer to
   55396 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
   55397 ** structure, then said structure defines the content and collating
   55398 ** sequence of the index being opened. Otherwise, if P4 is an integer
   55399 ** value, it is set to the number of columns in the table.
   55400 **
   55401 ** See also OpenWrite.
   55402 */
   55403 /* Opcode: OpenWrite P1 P2 P3 P4 P5
   55404 **
   55405 ** Open a read/write cursor named P1 on the table or index whose root
   55406 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
   55407 ** root page.
   55408 **
   55409 ** The P4 value may be either an integer (P4_INT32) or a pointer to
   55410 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
   55411 ** structure, then said structure defines the content and collating
   55412 ** sequence of the index being opened. Otherwise, if P4 is an integer
   55413 ** value, it is set to the number of columns in the table, or to the
   55414 ** largest index of any column of the table that is actually used.
   55415 **
   55416 ** This instruction works just like OpenRead except that it opens the cursor
   55417 ** in read/write mode.  For a given table, there can be one or more read-only
   55418 ** cursors or a single read/write cursor but not both.
   55419 **
   55420 ** See also OpenRead.
   55421 */
   55422 case OP_OpenRead:
   55423 case OP_OpenWrite: {
   55424 #if 0  /* local variables moved into u.aw */
   55425   int nField;
   55426   KeyInfo *pKeyInfo;
   55427   int p2;
   55428   int iDb;
   55429   int wrFlag;
   55430   Btree *pX;
   55431   VdbeCursor *pCur;
   55432   Db *pDb;
   55433 #endif /* local variables moved into u.aw */
   55434 
   55435   if( p->expired ){
   55436     rc = SQLITE_ABORT;
   55437     break;
   55438   }
   55439 
   55440   u.aw.nField = 0;
   55441   u.aw.pKeyInfo = 0;
   55442   u.aw.p2 = pOp->p2;
   55443   u.aw.iDb = pOp->p3;
   55444   assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
   55445   assert( (p->btreeMask & (1<<u.aw.iDb))!=0 );
   55446   u.aw.pDb = &db->aDb[u.aw.iDb];
   55447   u.aw.pX = u.aw.pDb->pBt;
   55448   assert( u.aw.pX!=0 );
   55449   if( pOp->opcode==OP_OpenWrite ){
   55450     u.aw.wrFlag = 1;
   55451     if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
   55452       p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
   55453     }
   55454   }else{
   55455     u.aw.wrFlag = 0;
   55456   }
   55457   if( pOp->p5 ){
   55458     assert( u.aw.p2>0 );
   55459     assert( u.aw.p2<=p->nMem );
   55460     pIn2 = &aMem[u.aw.p2];
   55461     sqlite3VdbeMemIntegerify(pIn2);
   55462     u.aw.p2 = (int)pIn2->u.i;
   55463     /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
   55464     ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
   55465     ** If there were a failure, the prepared statement would have halted
   55466     ** before reaching this instruction. */
   55467     if( NEVER(u.aw.p2<2) ) {
   55468       rc = SQLITE_CORRUPT_BKPT;
   55469       goto abort_due_to_error;
   55470     }
   55471   }
   55472   if( pOp->p4type==P4_KEYINFO ){
   55473     u.aw.pKeyInfo = pOp->p4.pKeyInfo;
   55474     u.aw.pKeyInfo->enc = ENC(p->db);
   55475     u.aw.nField = u.aw.pKeyInfo->nField+1;
   55476   }else if( pOp->p4type==P4_INT32 ){
   55477     u.aw.nField = pOp->p4.i;
   55478   }
   55479   assert( pOp->p1>=0 );
   55480   u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
   55481   if( u.aw.pCur==0 ) goto no_mem;
   55482   u.aw.pCur->nullRow = 1;
   55483   rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
   55484   u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
   55485 
   55486   /* Since it performs no memory allocation or IO, the only values that
   55487   ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
   55488   ** SQLITE_EMPTY is only returned when attempting to open the table
   55489   ** rooted at page 1 of a zero-byte database.  */
   55490   assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
   55491   if( rc==SQLITE_EMPTY ){
   55492     u.aw.pCur->pCursor = 0;
   55493     rc = SQLITE_OK;
   55494   }
   55495 
   55496   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
   55497   ** SQLite used to check if the root-page flags were sane at this point
   55498   ** and report database corruption if they were not, but this check has
   55499   ** since moved into the btree layer.  */
   55500   u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
   55501   u.aw.pCur->isIndex = !u.aw.pCur->isTable;
   55502   break;
   55503 }
   55504 
   55505 /* Opcode: OpenEphemeral P1 P2 * P4 *
   55506 **
   55507 ** Open a new cursor P1 to a transient table.
   55508 ** The cursor is always opened read/write even if
   55509 ** the main database is read-only.  The transient or virtual
   55510 ** table is deleted automatically when the cursor is closed.
   55511 **
   55512 ** P2 is the number of columns in the virtual table.
   55513 ** The cursor points to a BTree table if P4==0 and to a BTree index
   55514 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
   55515 ** that defines the format of keys in the index.
   55516 **
   55517 ** This opcode was once called OpenTemp.  But that created
   55518 ** confusion because the term "temp table", might refer either
   55519 ** to a TEMP table at the SQL level, or to a table opened by
   55520 ** this opcode.  Then this opcode was call OpenVirtual.  But
   55521 ** that created confusion with the whole virtual-table idea.
   55522 */
   55523 case OP_OpenEphemeral: {
   55524 #if 0  /* local variables moved into u.ax */
   55525   VdbeCursor *pCx;
   55526 #endif /* local variables moved into u.ax */
   55527   static const int openFlags =
   55528       SQLITE_OPEN_READWRITE |
   55529       SQLITE_OPEN_CREATE |
   55530       SQLITE_OPEN_EXCLUSIVE |
   55531       SQLITE_OPEN_DELETEONCLOSE |
   55532       SQLITE_OPEN_TRANSIENT_DB;
   55533 
   55534   assert( pOp->p1>=0 );
   55535   u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
   55536   if( u.ax.pCx==0 ) goto no_mem;
   55537   u.ax.pCx->nullRow = 1;
   55538   rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
   55539                            &u.ax.pCx->pBt);
   55540   if( rc==SQLITE_OK ){
   55541     rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
   55542   }
   55543   if( rc==SQLITE_OK ){
   55544     /* If a transient index is required, create it by calling
   55545     ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
   55546     ** opening it. If a transient table is required, just use the
   55547     ** automatically created table with root-page 1 (an INTKEY table).
   55548     */
   55549     if( pOp->p4.pKeyInfo ){
   55550       int pgno;
   55551       assert( pOp->p4type==P4_KEYINFO );
   55552       rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_ZERODATA);
   55553       if( rc==SQLITE_OK ){
   55554         assert( pgno==MASTER_ROOT+1 );
   55555         rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
   55556                                 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
   55557         u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
   55558         u.ax.pCx->pKeyInfo->enc = ENC(p->db);
   55559       }
   55560       u.ax.pCx->isTable = 0;
   55561     }else{
   55562       rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
   55563       u.ax.pCx->isTable = 1;
   55564     }
   55565   }
   55566   u.ax.pCx->isIndex = !u.ax.pCx->isTable;
   55567   break;
   55568 }
   55569 
   55570 /* Opcode: OpenPseudo P1 P2 P3 * *
   55571 **
   55572 ** Open a new cursor that points to a fake table that contains a single
   55573 ** row of data.  The content of that one row in the content of memory
   55574 ** register P2.  In other words, cursor P1 becomes an alias for the
   55575 ** MEM_Blob content contained in register P2.
   55576 **
   55577 ** A pseudo-table created by this opcode is used to hold the a single
   55578 ** row output from the sorter so that the row can be decomposed into
   55579 ** individual columns using the OP_Column opcode.  The OP_Column opcode
   55580 ** is the only cursor opcode that works with a pseudo-table.
   55581 **
   55582 ** P3 is the number of fields in the records that will be stored by
   55583 ** the pseudo-table.
   55584 */
   55585 case OP_OpenPseudo: {
   55586 #if 0  /* local variables moved into u.ay */
   55587   VdbeCursor *pCx;
   55588 #endif /* local variables moved into u.ay */
   55589 
   55590   assert( pOp->p1>=0 );
   55591   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
   55592   if( u.ay.pCx==0 ) goto no_mem;
   55593   u.ay.pCx->nullRow = 1;
   55594   u.ay.pCx->pseudoTableReg = pOp->p2;
   55595   u.ay.pCx->isTable = 1;
   55596   u.ay.pCx->isIndex = 0;
   55597   break;
   55598 }
   55599 
   55600 /* Opcode: Close P1 * * * *
   55601 **
   55602 ** Close a cursor previously opened as P1.  If P1 is not
   55603 ** currently open, this instruction is a no-op.
   55604 */
   55605 case OP_Close: {
   55606   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   55607   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
   55608   p->apCsr[pOp->p1] = 0;
   55609   break;
   55610 }
   55611 
   55612 /* Opcode: SeekGe P1 P2 P3 P4 *
   55613 **
   55614 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   55615 ** use the value in register P3 as the key.  If cursor P1 refers
   55616 ** to an SQL index, then P3 is the first in an array of P4 registers
   55617 ** that are used as an unpacked index key.
   55618 **
   55619 ** Reposition cursor P1 so that  it points to the smallest entry that
   55620 ** is greater than or equal to the key value. If there are no records
   55621 ** greater than or equal to the key and P2 is not zero, then jump to P2.
   55622 **
   55623 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
   55624 */
   55625 /* Opcode: SeekGt P1 P2 P3 P4 *
   55626 **
   55627 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   55628 ** use the value in register P3 as a key. If cursor P1 refers
   55629 ** to an SQL index, then P3 is the first in an array of P4 registers
   55630 ** that are used as an unpacked index key.
   55631 **
   55632 ** Reposition cursor P1 so that  it points to the smallest entry that
   55633 ** is greater than the key value. If there are no records greater than
   55634 ** the key and P2 is not zero, then jump to P2.
   55635 **
   55636 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
   55637 */
   55638 /* Opcode: SeekLt P1 P2 P3 P4 *
   55639 **
   55640 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   55641 ** use the value in register P3 as a key. If cursor P1 refers
   55642 ** to an SQL index, then P3 is the first in an array of P4 registers
   55643 ** that are used as an unpacked index key.
   55644 **
   55645 ** Reposition cursor P1 so that  it points to the largest entry that
   55646 ** is less than the key value. If there are no records less than
   55647 ** the key and P2 is not zero, then jump to P2.
   55648 **
   55649 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
   55650 */
   55651 /* Opcode: SeekLe P1 P2 P3 P4 *
   55652 **
   55653 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   55654 ** use the value in register P3 as a key. If cursor P1 refers
   55655 ** to an SQL index, then P3 is the first in an array of P4 registers
   55656 ** that are used as an unpacked index key.
   55657 **
   55658 ** Reposition cursor P1 so that it points to the largest entry that
   55659 ** is less than or equal to the key value. If there are no records
   55660 ** less than or equal to the key and P2 is not zero, then jump to P2.
   55661 **
   55662 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
   55663 */
   55664 case OP_SeekLt:         /* jump, in3 */
   55665 case OP_SeekLe:         /* jump, in3 */
   55666 case OP_SeekGe:         /* jump, in3 */
   55667 case OP_SeekGt: {       /* jump, in3 */
   55668 #if 0  /* local variables moved into u.az */
   55669   int res;
   55670   int oc;
   55671   VdbeCursor *pC;
   55672   UnpackedRecord r;
   55673   int nField;
   55674   i64 iKey;      /* The rowid we are to seek to */
   55675 #endif /* local variables moved into u.az */
   55676 
   55677   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   55678   assert( pOp->p2!=0 );
   55679   u.az.pC = p->apCsr[pOp->p1];
   55680   assert( u.az.pC!=0 );
   55681   assert( u.az.pC->pseudoTableReg==0 );
   55682   assert( OP_SeekLe == OP_SeekLt+1 );
   55683   assert( OP_SeekGe == OP_SeekLt+2 );
   55684   assert( OP_SeekGt == OP_SeekLt+3 );
   55685   if( u.az.pC->pCursor!=0 ){
   55686     u.az.oc = pOp->opcode;
   55687     u.az.pC->nullRow = 0;
   55688     if( u.az.pC->isTable ){
   55689       /* The input value in P3 might be of any type: integer, real, string,
   55690       ** blob, or NULL.  But it needs to be an integer before we can do
   55691       ** the seek, so covert it. */
   55692       pIn3 = &aMem[pOp->p3];
   55693       applyNumericAffinity(pIn3);
   55694       u.az.iKey = sqlite3VdbeIntValue(pIn3);
   55695       u.az.pC->rowidIsValid = 0;
   55696 
   55697       /* If the P3 value could not be converted into an integer without
   55698       ** loss of information, then special processing is required... */
   55699       if( (pIn3->flags & MEM_Int)==0 ){
   55700         if( (pIn3->flags & MEM_Real)==0 ){
   55701           /* If the P3 value cannot be converted into any kind of a number,
   55702           ** then the seek is not possible, so jump to P2 */
   55703           pc = pOp->p2 - 1;
   55704           break;
   55705         }
   55706         /* If we reach this point, then the P3 value must be a floating
   55707         ** point number. */
   55708         assert( (pIn3->flags & MEM_Real)!=0 );
   55709 
   55710         if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
   55711           /* The P3 value is too large in magnitude to be expressed as an
   55712           ** integer. */
   55713           u.az.res = 1;
   55714           if( pIn3->r<0 ){
   55715             if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
   55716               rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
   55717               if( rc!=SQLITE_OK ) goto abort_due_to_error;
   55718             }
   55719           }else{
   55720             if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
   55721               rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
   55722               if( rc!=SQLITE_OK ) goto abort_due_to_error;
   55723             }
   55724           }
   55725           if( u.az.res ){
   55726             pc = pOp->p2 - 1;
   55727           }
   55728           break;
   55729         }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
   55730           /* Use the ceiling() function to convert real->int */
   55731           if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
   55732         }else{
   55733           /* Use the floor() function to convert real->int */
   55734           assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
   55735           if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
   55736         }
   55737       }
   55738       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
   55739       if( rc!=SQLITE_OK ){
   55740         goto abort_due_to_error;
   55741       }
   55742       if( u.az.res==0 ){
   55743         u.az.pC->rowidIsValid = 1;
   55744         u.az.pC->lastRowid = u.az.iKey;
   55745       }
   55746     }else{
   55747       u.az.nField = pOp->p4.i;
   55748       assert( pOp->p4type==P4_INT32 );
   55749       assert( u.az.nField>0 );
   55750       u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
   55751       u.az.r.nField = (u16)u.az.nField;
   55752 
   55753       /* The next line of code computes as follows, only faster:
   55754       **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
   55755       **     u.az.r.flags = UNPACKED_INCRKEY;
   55756       **   }else{
   55757       **     u.az.r.flags = 0;
   55758       **   }
   55759       */
   55760       u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
   55761       assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
   55762       assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
   55763       assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
   55764       assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
   55765 
   55766       u.az.r.aMem = &aMem[pOp->p3];
   55767       ExpandBlob(u.az.r.aMem);
   55768       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
   55769       if( rc!=SQLITE_OK ){
   55770         goto abort_due_to_error;
   55771       }
   55772       u.az.pC->rowidIsValid = 0;
   55773     }
   55774     u.az.pC->deferredMoveto = 0;
   55775     u.az.pC->cacheStatus = CACHE_STALE;
   55776 #ifdef SQLITE_TEST
   55777     sqlite3_search_count++;
   55778 #endif
   55779     if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
   55780       if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
   55781         rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
   55782         if( rc!=SQLITE_OK ) goto abort_due_to_error;
   55783         u.az.pC->rowidIsValid = 0;
   55784       }else{
   55785         u.az.res = 0;
   55786       }
   55787     }else{
   55788       assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
   55789       if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
   55790         rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
   55791         if( rc!=SQLITE_OK ) goto abort_due_to_error;
   55792         u.az.pC->rowidIsValid = 0;
   55793       }else{
   55794         /* u.az.res might be negative because the table is empty.  Check to
   55795         ** see if this is the case.
   55796         */
   55797         u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
   55798       }
   55799     }
   55800     assert( pOp->p2>0 );
   55801     if( u.az.res ){
   55802       pc = pOp->p2 - 1;
   55803     }
   55804   }else{
   55805     /* This happens when attempting to open the sqlite3_master table
   55806     ** for read access returns SQLITE_EMPTY. In this case always
   55807     ** take the jump (since there are no records in the table).
   55808     */
   55809     pc = pOp->p2 - 1;
   55810   }
   55811   break;
   55812 }
   55813 
   55814 /* Opcode: Seek P1 P2 * * *
   55815 **
   55816 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
   55817 ** for P1 to move so that it points to the rowid given by P2.
   55818 **
   55819 ** This is actually a deferred seek.  Nothing actually happens until
   55820 ** the cursor is used to read a record.  That way, if no reads
   55821 ** occur, no unnecessary I/O happens.
   55822 */
   55823 case OP_Seek: {    /* in2 */
   55824 #if 0  /* local variables moved into u.ba */
   55825   VdbeCursor *pC;
   55826 #endif /* local variables moved into u.ba */
   55827 
   55828   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   55829   u.ba.pC = p->apCsr[pOp->p1];
   55830   assert( u.ba.pC!=0 );
   55831   if( ALWAYS(u.ba.pC->pCursor!=0) ){
   55832     assert( u.ba.pC->isTable );
   55833     u.ba.pC->nullRow = 0;
   55834     pIn2 = &aMem[pOp->p2];
   55835     u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
   55836     u.ba.pC->rowidIsValid = 0;
   55837     u.ba.pC->deferredMoveto = 1;
   55838   }
   55839   break;
   55840 }
   55841 
   55842 
   55843 /* Opcode: Found P1 P2 P3 P4 *
   55844 **
   55845 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   55846 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   55847 ** record.
   55848 **
   55849 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   55850 ** is a prefix of any entry in P1 then a jump is made to P2 and
   55851 ** P1 is left pointing at the matching entry.
   55852 */
   55853 /* Opcode: NotFound P1 P2 P3 P4 *
   55854 **
   55855 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   55856 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   55857 ** record.
   55858 **
   55859 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   55860 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
   55861 ** does contain an entry whose prefix matches the P3/P4 record then control
   55862 ** falls through to the next instruction and P1 is left pointing at the
   55863 ** matching entry.
   55864 **
   55865 ** See also: Found, NotExists, IsUnique
   55866 */
   55867 case OP_NotFound:       /* jump, in3 */
   55868 case OP_Found: {        /* jump, in3 */
   55869 #if 0  /* local variables moved into u.bb */
   55870   int alreadyExists;
   55871   VdbeCursor *pC;
   55872   int res;
   55873   UnpackedRecord *pIdxKey;
   55874   UnpackedRecord r;
   55875   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
   55876 #endif /* local variables moved into u.bb */
   55877 
   55878 #ifdef SQLITE_TEST
   55879   sqlite3_found_count++;
   55880 #endif
   55881 
   55882   u.bb.alreadyExists = 0;
   55883   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   55884   assert( pOp->p4type==P4_INT32 );
   55885   u.bb.pC = p->apCsr[pOp->p1];
   55886   assert( u.bb.pC!=0 );
   55887   pIn3 = &aMem[pOp->p3];
   55888   if( ALWAYS(u.bb.pC->pCursor!=0) ){
   55889 
   55890     assert( u.bb.pC->isTable==0 );
   55891     if( pOp->p4.i>0 ){
   55892       u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
   55893       u.bb.r.nField = (u16)pOp->p4.i;
   55894       u.bb.r.aMem = pIn3;
   55895       u.bb.r.flags = UNPACKED_PREFIX_MATCH;
   55896       u.bb.pIdxKey = &u.bb.r;
   55897     }else{
   55898       assert( pIn3->flags & MEM_Blob );
   55899       ExpandBlob(pIn3);
   55900       u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
   55901                                         u.bb.aTempRec, sizeof(u.bb.aTempRec));
   55902       if( u.bb.pIdxKey==0 ){
   55903         goto no_mem;
   55904       }
   55905       u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
   55906     }
   55907     rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
   55908     if( pOp->p4.i==0 ){
   55909       sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
   55910     }
   55911     if( rc!=SQLITE_OK ){
   55912       break;
   55913     }
   55914     u.bb.alreadyExists = (u.bb.res==0);
   55915     u.bb.pC->deferredMoveto = 0;
   55916     u.bb.pC->cacheStatus = CACHE_STALE;
   55917   }
   55918   if( pOp->opcode==OP_Found ){
   55919     if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
   55920   }else{
   55921     if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
   55922   }
   55923   break;
   55924 }
   55925 
   55926 /* Opcode: IsUnique P1 P2 P3 P4 *
   55927 **
   55928 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
   55929 ** no data and where the key are records generated by OP_MakeRecord with
   55930 ** the list field being the integer ROWID of the entry that the index
   55931 ** entry refers to.
   55932 **
   55933 ** The P3 register contains an integer record number. Call this record
   55934 ** number R. Register P4 is the first in a set of N contiguous registers
   55935 ** that make up an unpacked index key that can be used with cursor P1.
   55936 ** The value of N can be inferred from the cursor. N includes the rowid
   55937 ** value appended to the end of the index record. This rowid value may
   55938 ** or may not be the same as R.
   55939 **
   55940 ** If any of the N registers beginning with register P4 contains a NULL
   55941 ** value, jump immediately to P2.
   55942 **
   55943 ** Otherwise, this instruction checks if cursor P1 contains an entry
   55944 ** where the first (N-1) fields match but the rowid value at the end
   55945 ** of the index entry is not R. If there is no such entry, control jumps
   55946 ** to instruction P2. Otherwise, the rowid of the conflicting index
   55947 ** entry is copied to register P3 and control falls through to the next
   55948 ** instruction.
   55949 **
   55950 ** See also: NotFound, NotExists, Found
   55951 */
   55952 case OP_IsUnique: {        /* jump, in3 */
   55953 #if 0  /* local variables moved into u.bc */
   55954   u16 ii;
   55955   VdbeCursor *pCx;
   55956   BtCursor *pCrsr;
   55957   u16 nField;
   55958   Mem *aMx;
   55959   UnpackedRecord r;                  /* B-Tree index search key */
   55960   i64 R;                             /* Rowid stored in register P3 */
   55961 #endif /* local variables moved into u.bc */
   55962 
   55963   pIn3 = &aMem[pOp->p3];
   55964   u.bc.aMx = &aMem[pOp->p4.i];
   55965   /* Assert that the values of parameters P1 and P4 are in range. */
   55966   assert( pOp->p4type==P4_INT32 );
   55967   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
   55968   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   55969 
   55970   /* Find the index cursor. */
   55971   u.bc.pCx = p->apCsr[pOp->p1];
   55972   assert( u.bc.pCx->deferredMoveto==0 );
   55973   u.bc.pCx->seekResult = 0;
   55974   u.bc.pCx->cacheStatus = CACHE_STALE;
   55975   u.bc.pCrsr = u.bc.pCx->pCursor;
   55976 
   55977   /* If any of the values are NULL, take the jump. */
   55978   u.bc.nField = u.bc.pCx->pKeyInfo->nField;
   55979   for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
   55980     if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
   55981       pc = pOp->p2 - 1;
   55982       u.bc.pCrsr = 0;
   55983       break;
   55984     }
   55985   }
   55986   assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
   55987 
   55988   if( u.bc.pCrsr!=0 ){
   55989     /* Populate the index search key. */
   55990     u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
   55991     u.bc.r.nField = u.bc.nField + 1;
   55992     u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
   55993     u.bc.r.aMem = u.bc.aMx;
   55994 
   55995     /* Extract the value of u.bc.R from register P3. */
   55996     sqlite3VdbeMemIntegerify(pIn3);
   55997     u.bc.R = pIn3->u.i;
   55998 
   55999     /* Search the B-Tree index. If no conflicting record is found, jump
   56000     ** to P2. Otherwise, copy the rowid of the conflicting record to
   56001     ** register P3 and fall through to the next instruction.  */
   56002     rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
   56003     if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
   56004       pc = pOp->p2 - 1;
   56005     }else{
   56006       pIn3->u.i = u.bc.r.rowid;
   56007     }
   56008   }
   56009   break;
   56010 }
   56011 
   56012 /* Opcode: NotExists P1 P2 P3 * *
   56013 **
   56014 ** Use the content of register P3 as a integer key.  If a record
   56015 ** with that key does not exist in table of P1, then jump to P2.
   56016 ** If the record does exist, then fall thru.  The cursor is left
   56017 ** pointing to the record if it exists.
   56018 **
   56019 ** The difference between this operation and NotFound is that this
   56020 ** operation assumes the key is an integer and that P1 is a table whereas
   56021 ** NotFound assumes key is a blob constructed from MakeRecord and
   56022 ** P1 is an index.
   56023 **
   56024 ** See also: Found, NotFound, IsUnique
   56025 */
   56026 case OP_NotExists: {        /* jump, in3 */
   56027 #if 0  /* local variables moved into u.bd */
   56028   VdbeCursor *pC;
   56029   BtCursor *pCrsr;
   56030   int res;
   56031   u64 iKey;
   56032 #endif /* local variables moved into u.bd */
   56033 
   56034   pIn3 = &aMem[pOp->p3];
   56035   assert( pIn3->flags & MEM_Int );
   56036   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   56037   u.bd.pC = p->apCsr[pOp->p1];
   56038   assert( u.bd.pC!=0 );
   56039   assert( u.bd.pC->isTable );
   56040   assert( u.bd.pC->pseudoTableReg==0 );
   56041   u.bd.pCrsr = u.bd.pC->pCursor;
   56042   if( u.bd.pCrsr!=0 ){
   56043     u.bd.res = 0;
   56044     u.bd.iKey = pIn3->u.i;
   56045     rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
   56046     u.bd.pC->lastRowid = pIn3->u.i;
   56047     u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
   56048     u.bd.pC->nullRow = 0;
   56049     u.bd.pC->cacheStatus = CACHE_STALE;
   56050     u.bd.pC->deferredMoveto = 0;
   56051     if( u.bd.res!=0 ){
   56052       pc = pOp->p2 - 1;
   56053       assert( u.bd.pC->rowidIsValid==0 );
   56054     }
   56055     u.bd.pC->seekResult = u.bd.res;
   56056   }else{
   56057     /* This happens when an attempt to open a read cursor on the
   56058     ** sqlite_master table returns SQLITE_EMPTY.
   56059     */
   56060     pc = pOp->p2 - 1;
   56061     assert( u.bd.pC->rowidIsValid==0 );
   56062     u.bd.pC->seekResult = 0;
   56063   }
   56064   break;
   56065 }
   56066 
   56067 /* Opcode: Sequence P1 P2 * * *
   56068 **
   56069 ** Find the next available sequence number for cursor P1.
   56070 ** Write the sequence number into register P2.
   56071 ** The sequence number on the cursor is incremented after this
   56072 ** instruction.
   56073 */
   56074 case OP_Sequence: {           /* out2-prerelease */
   56075   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   56076   assert( p->apCsr[pOp->p1]!=0 );
   56077   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
   56078   break;
   56079 }
   56080 
   56081 
   56082 /* Opcode: NewRowid P1 P2 P3 * *
   56083 **
   56084 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
   56085 ** The record number is not previously used as a key in the database
   56086 ** table that cursor P1 points to.  The new record number is written
   56087 ** written to register P2.
   56088 **
   56089 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
   56090 ** the largest previously generated record number. No new record numbers are
   56091 ** allowed to be less than this value. When this value reaches its maximum,
   56092 ** a SQLITE_FULL error is generated. The P3 register is updated with the '
   56093 ** generated record number. This P3 mechanism is used to help implement the
   56094 ** AUTOINCREMENT feature.
   56095 */
   56096 case OP_NewRowid: {           /* out2-prerelease */
   56097 #if 0  /* local variables moved into u.be */
   56098   i64 v;                 /* The new rowid */
   56099   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
   56100   int res;               /* Result of an sqlite3BtreeLast() */
   56101   int cnt;               /* Counter to limit the number of searches */
   56102   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
   56103   VdbeFrame *pFrame;     /* Root frame of VDBE */
   56104 #endif /* local variables moved into u.be */
   56105 
   56106   u.be.v = 0;
   56107   u.be.res = 0;
   56108   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   56109   u.be.pC = p->apCsr[pOp->p1];
   56110   assert( u.be.pC!=0 );
   56111   if( NEVER(u.be.pC->pCursor==0) ){
   56112     /* The zero initialization above is all that is needed */
   56113   }else{
   56114     /* The next rowid or record number (different terms for the same
   56115     ** thing) is obtained in a two-step algorithm.
   56116     **
   56117     ** First we attempt to find the largest existing rowid and add one
   56118     ** to that.  But if the largest existing rowid is already the maximum
   56119     ** positive integer, we have to fall through to the second
   56120     ** probabilistic algorithm
   56121     **
   56122     ** The second algorithm is to select a rowid at random and see if
   56123     ** it already exists in the table.  If it does not exist, we have
   56124     ** succeeded.  If the random rowid does exist, we select a new one
   56125     ** and try again, up to 100 times.
   56126     */
   56127     assert( u.be.pC->isTable );
   56128     u.be.cnt = 0;
   56129 
   56130 #ifdef SQLITE_32BIT_ROWID
   56131 #   define MAX_ROWID 0x7fffffff
   56132 #else
   56133     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
   56134     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
   56135     ** to provide the constant while making all compilers happy.
   56136     */
   56137 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
   56138 #endif
   56139 
   56140     if( !u.be.pC->useRandomRowid ){
   56141       u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
   56142       if( u.be.v==0 ){
   56143         rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
   56144         if( rc!=SQLITE_OK ){
   56145           goto abort_due_to_error;
   56146         }
   56147         if( u.be.res ){
   56148           u.be.v = 1;   /* IMP: R-61914-48074 */
   56149         }else{
   56150           assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
   56151           rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
   56152           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
   56153           if( u.be.v==MAX_ROWID ){
   56154             u.be.pC->useRandomRowid = 1;
   56155           }else{
   56156             u.be.v++;   /* IMP: R-29538-34987 */
   56157           }
   56158         }
   56159       }
   56160 
   56161 #ifndef SQLITE_OMIT_AUTOINCREMENT
   56162       if( pOp->p3 ){
   56163         /* Assert that P3 is a valid memory cell. */
   56164         assert( pOp->p3>0 );
   56165         if( p->pFrame ){
   56166           for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
   56167           /* Assert that P3 is a valid memory cell. */
   56168           assert( pOp->p3<=u.be.pFrame->nMem );
   56169           u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
   56170         }else{
   56171           /* Assert that P3 is a valid memory cell. */
   56172           assert( pOp->p3<=p->nMem );
   56173           u.be.pMem = &aMem[pOp->p3];
   56174         }
   56175 
   56176         REGISTER_TRACE(pOp->p3, u.be.pMem);
   56177         sqlite3VdbeMemIntegerify(u.be.pMem);
   56178         assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
   56179         if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
   56180           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
   56181           goto abort_due_to_error;
   56182         }
   56183         if( u.be.v<u.be.pMem->u.i+1 ){
   56184           u.be.v = u.be.pMem->u.i + 1;
   56185         }
   56186         u.be.pMem->u.i = u.be.v;
   56187       }
   56188 #endif
   56189 
   56190       sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
   56191     }
   56192     if( u.be.pC->useRandomRowid ){
   56193       /* IMPLEMENTATION-OF: R-48598-02938 If the largest ROWID is equal to the
   56194       ** largest possible integer (9223372036854775807) then the database
   56195       ** engine starts picking candidate ROWIDs at random until it finds one
   56196       ** that is not previously used.
   56197       */
   56198       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
   56199                              ** an AUTOINCREMENT table. */
   56200       u.be.v = db->lastRowid;
   56201       u.be.cnt = 0;
   56202       do{
   56203         if( u.be.cnt==0 && (u.be.v&0xffffff)==u.be.v ){
   56204           u.be.v++;
   56205         }else{
   56206           sqlite3_randomness(sizeof(u.be.v), &u.be.v);
   56207           if( u.be.cnt<5 ) u.be.v &= 0xffffff;
   56208         }
   56209         rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v, 0, &u.be.res);
   56210         u.be.cnt++;
   56211       }while( u.be.cnt<100 && rc==SQLITE_OK && u.be.res==0 );
   56212       if( rc==SQLITE_OK && u.be.res==0 ){
   56213         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
   56214         goto abort_due_to_error;
   56215       }
   56216     }
   56217     u.be.pC->rowidIsValid = 0;
   56218     u.be.pC->deferredMoveto = 0;
   56219     u.be.pC->cacheStatus = CACHE_STALE;
   56220   }
   56221   pOut->u.i = u.be.v;
   56222   break;
   56223 }
   56224 
   56225 /* Opcode: Insert P1 P2 P3 P4 P5
   56226 **
   56227 ** Write an entry into the table of cursor P1.  A new entry is
   56228 ** created if it doesn't already exist or the data for an existing
   56229 ** entry is overwritten.  The data is the value MEM_Blob stored in register
   56230 ** number P2. The key is stored in register P3. The key must
   56231 ** be a MEM_Int.
   56232 **
   56233 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
   56234 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
   56235 ** then rowid is stored for subsequent return by the
   56236 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
   56237 **
   56238 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
   56239 ** the last seek operation (OP_NotExists) was a success, then this
   56240 ** operation will not attempt to find the appropriate row before doing
   56241 ** the insert but will instead overwrite the row that the cursor is
   56242 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
   56243 ** has already positioned the cursor correctly.  This is an optimization
   56244 ** that boosts performance by avoiding redundant seeks.
   56245 **
   56246 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
   56247 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
   56248 ** is part of an INSERT operation.  The difference is only important to
   56249 ** the update hook.
   56250 **
   56251 ** Parameter P4 may point to a string containing the table-name, or
   56252 ** may be NULL. If it is not NULL, then the update-hook
   56253 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
   56254 **
   56255 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
   56256 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
   56257 ** and register P2 becomes ephemeral.  If the cursor is changed, the
   56258 ** value of register P2 will then change.  Make sure this does not
   56259 ** cause any problems.)
   56260 **
   56261 ** This instruction only works on tables.  The equivalent instruction
   56262 ** for indices is OP_IdxInsert.
   56263 */
   56264 /* Opcode: InsertInt P1 P2 P3 P4 P5
   56265 **
   56266 ** This works exactly like OP_Insert except that the key is the
   56267 ** integer value P3, not the value of the integer stored in register P3.
   56268 */
   56269 case OP_Insert:
   56270 case OP_InsertInt: {
   56271 #if 0  /* local variables moved into u.bf */
   56272   Mem *pData;       /* MEM cell holding data for the record to be inserted */
   56273   Mem *pKey;        /* MEM cell holding key  for the record */
   56274   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
   56275   VdbeCursor *pC;   /* Cursor to table into which insert is written */
   56276   int nZero;        /* Number of zero-bytes to append */
   56277   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
   56278   const char *zDb;  /* database name - used by the update hook */
   56279   const char *zTbl; /* Table name - used by the opdate hook */
   56280   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
   56281 #endif /* local variables moved into u.bf */
   56282 
   56283   u.bf.pData = &aMem[pOp->p2];
   56284   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   56285   u.bf.pC = p->apCsr[pOp->p1];
   56286   assert( u.bf.pC!=0 );
   56287   assert( u.bf.pC->pCursor!=0 );
   56288   assert( u.bf.pC->pseudoTableReg==0 );
   56289   assert( u.bf.pC->isTable );
   56290   REGISTER_TRACE(pOp->p2, u.bf.pData);
   56291 
   56292   if( pOp->opcode==OP_Insert ){
   56293     u.bf.pKey = &aMem[pOp->p3];
   56294     assert( u.bf.pKey->flags & MEM_Int );
   56295     REGISTER_TRACE(pOp->p3, u.bf.pKey);
   56296     u.bf.iKey = u.bf.pKey->u.i;
   56297   }else{
   56298     assert( pOp->opcode==OP_InsertInt );
   56299     u.bf.iKey = pOp->p3;
   56300   }
   56301 
   56302   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
   56303   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
   56304   if( u.bf.pData->flags & MEM_Null ){
   56305     u.bf.pData->z = 0;
   56306     u.bf.pData->n = 0;
   56307   }else{
   56308     assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
   56309   }
   56310   u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
   56311   if( u.bf.pData->flags & MEM_Zero ){
   56312     u.bf.nZero = u.bf.pData->u.nZero;
   56313   }else{
   56314     u.bf.nZero = 0;
   56315   }
   56316   sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
   56317   rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
   56318                           u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
   56319                           pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
   56320   );
   56321   u.bf.pC->rowidIsValid = 0;
   56322   u.bf.pC->deferredMoveto = 0;
   56323   u.bf.pC->cacheStatus = CACHE_STALE;
   56324 
   56325   /* Invoke the update-hook if required. */
   56326   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
   56327     u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
   56328     u.bf.zTbl = pOp->p4.z;
   56329     u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
   56330     assert( u.bf.pC->isTable );
   56331     db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
   56332     assert( u.bf.pC->iDb>=0 );
   56333   }
   56334   break;
   56335 }
   56336 
   56337 /* Opcode: Delete P1 P2 * P4 *
   56338 **
   56339 ** Delete the record at which the P1 cursor is currently pointing.
   56340 **
   56341 ** The cursor will be left pointing at either the next or the previous
   56342 ** record in the table. If it is left pointing at the next record, then
   56343 ** the next Next instruction will be a no-op.  Hence it is OK to delete
   56344 ** a record from within an Next loop.
   56345 **
   56346 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
   56347 ** incremented (otherwise not).
   56348 **
   56349 ** P1 must not be pseudo-table.  It has to be a real table with
   56350 ** multiple rows.
   56351 **
   56352 ** If P4 is not NULL, then it is the name of the table that P1 is
   56353 ** pointing to.  The update hook will be invoked, if it exists.
   56354 ** If P4 is not NULL then the P1 cursor must have been positioned
   56355 ** using OP_NotFound prior to invoking this opcode.
   56356 */
   56357 case OP_Delete: {
   56358 #if 0  /* local variables moved into u.bg */
   56359   i64 iKey;
   56360   VdbeCursor *pC;
   56361 #endif /* local variables moved into u.bg */
   56362 
   56363   u.bg.iKey = 0;
   56364   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   56365   u.bg.pC = p->apCsr[pOp->p1];
   56366   assert( u.bg.pC!=0 );
   56367   assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
   56368 
   56369   /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
   56370   ** row being deleted.
   56371   */
   56372   if( db->xUpdateCallback && pOp->p4.z ){
   56373     assert( u.bg.pC->isTable );
   56374     assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
   56375     u.bg.iKey = u.bg.pC->lastRowid;
   56376   }
   56377 
   56378   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
   56379   ** OP_Column on the same table without any intervening operations that
   56380   ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
   56381   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
   56382   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
   56383   ** to guard against future changes to the code generator.
   56384   **/
   56385   assert( u.bg.pC->deferredMoveto==0 );
   56386   rc = sqlite3VdbeCursorMoveto(u.bg.pC);
   56387   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
   56388 
   56389   sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
   56390   rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
   56391   u.bg.pC->cacheStatus = CACHE_STALE;
   56392 
   56393   /* Invoke the update-hook if required. */
   56394   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
   56395     const char *zDb = db->aDb[u.bg.pC->iDb].zName;
   56396     const char *zTbl = pOp->p4.z;
   56397     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
   56398     assert( u.bg.pC->iDb>=0 );
   56399   }
   56400   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
   56401   break;
   56402 }
   56403 /* Opcode: ResetCount * * * * *
   56404 **
   56405 ** The value of the change counter is copied to the database handle
   56406 ** change counter (returned by subsequent calls to sqlite3_changes()).
   56407 ** Then the VMs internal change counter resets to 0.
   56408 ** This is used by trigger programs.
   56409 */
   56410 case OP_ResetCount: {
   56411   sqlite3VdbeSetChanges(db, p->nChange);
   56412   p->nChange = 0;
   56413   break;
   56414 }
   56415 
   56416 /* Opcode: RowData P1 P2 * * *
   56417 **
   56418 ** Write into register P2 the complete row data for cursor P1.
   56419 ** There is no interpretation of the data.
   56420 ** It is just copied onto the P2 register exactly as
   56421 ** it is found in the database file.
   56422 **
   56423 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
   56424 ** of a real table, not a pseudo-table.
   56425 */
   56426 /* Opcode: RowKey P1 P2 * * *
   56427 **
   56428 ** Write into register P2 the complete row key for cursor P1.
   56429 ** There is no interpretation of the data.
   56430 ** The key is copied onto the P3 register exactly as
   56431 ** it is found in the database file.
   56432 **
   56433 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
   56434 ** of a real table, not a pseudo-table.
   56435 */
   56436 case OP_RowKey:
   56437 case OP_RowData: {
   56438 #if 0  /* local variables moved into u.bh */
   56439   VdbeCursor *pC;
   56440   BtCursor *pCrsr;
   56441   u32 n;
   56442   i64 n64;
   56443 #endif /* local variables moved into u.bh */
   56444 
   56445   pOut = &aMem[pOp->p2];
   56446 
   56447   /* Note that RowKey and RowData are really exactly the same instruction */
   56448   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   56449   u.bh.pC = p->apCsr[pOp->p1];
   56450   assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
   56451   assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
   56452   assert( u.bh.pC!=0 );
   56453   assert( u.bh.pC->nullRow==0 );
   56454   assert( u.bh.pC->pseudoTableReg==0 );
   56455   assert( u.bh.pC->pCursor!=0 );
   56456   u.bh.pCrsr = u.bh.pC->pCursor;
   56457   assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
   56458 
   56459   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
   56460   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
   56461   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
   56462   ** a no-op and can never fail.  But we leave it in place as a safety.
   56463   */
   56464   assert( u.bh.pC->deferredMoveto==0 );
   56465   rc = sqlite3VdbeCursorMoveto(u.bh.pC);
   56466   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
   56467 
   56468   if( u.bh.pC->isIndex ){
   56469     assert( !u.bh.pC->isTable );
   56470     rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
   56471     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
   56472     if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   56473       goto too_big;
   56474     }
   56475     u.bh.n = (u32)u.bh.n64;
   56476   }else{
   56477     rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
   56478     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
   56479     if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   56480       goto too_big;
   56481     }
   56482   }
   56483   if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
   56484     goto no_mem;
   56485   }
   56486   pOut->n = u.bh.n;
   56487   MemSetTypeFlag(pOut, MEM_Blob);
   56488   if( u.bh.pC->isIndex ){
   56489     rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
   56490   }else{
   56491     rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
   56492   }
   56493   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
   56494   UPDATE_MAX_BLOBSIZE(pOut);
   56495   break;
   56496 }
   56497 
   56498 /* Opcode: Rowid P1 P2 * * *
   56499 **
   56500 ** Store in register P2 an integer which is the key of the table entry that
   56501 ** P1 is currently point to.
   56502 **
   56503 ** P1 can be either an ordinary table or a virtual table.  There used to
   56504 ** be a separate OP_VRowid opcode for use with virtual tables, but this
   56505 ** one opcode now works for both table types.
   56506 */
   56507 case OP_Rowid: {                 /* out2-prerelease */
   56508 #if 0  /* local variables moved into u.bi */
   56509   VdbeCursor *pC;
   56510   i64 v;
   56511   sqlite3_vtab *pVtab;
   56512   const sqlite3_module *pModule;
   56513 #endif /* local variables moved into u.bi */
   56514 
   56515   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   56516   u.bi.pC = p->apCsr[pOp->p1];
   56517   assert( u.bi.pC!=0 );
   56518   assert( u.bi.pC->pseudoTableReg==0 );
   56519   if( u.bi.pC->nullRow ){
   56520     pOut->flags = MEM_Null;
   56521     break;
   56522   }else if( u.bi.pC->deferredMoveto ){
   56523     u.bi.v = u.bi.pC->movetoTarget;
   56524 #ifndef SQLITE_OMIT_VIRTUALTABLE
   56525   }else if( u.bi.pC->pVtabCursor ){
   56526     u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
   56527     u.bi.pModule = u.bi.pVtab->pModule;
   56528     assert( u.bi.pModule->xRowid );
   56529     rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
   56530     sqlite3DbFree(db, p->zErrMsg);
   56531     p->zErrMsg = u.bi.pVtab->zErrMsg;
   56532     u.bi.pVtab->zErrMsg = 0;
   56533 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   56534   }else{
   56535     assert( u.bi.pC->pCursor!=0 );
   56536     rc = sqlite3VdbeCursorMoveto(u.bi.pC);
   56537     if( rc ) goto abort_due_to_error;
   56538     if( u.bi.pC->rowidIsValid ){
   56539       u.bi.v = u.bi.pC->lastRowid;
   56540     }else{
   56541       rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
   56542       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
   56543     }
   56544   }
   56545   pOut->u.i = u.bi.v;
   56546   break;
   56547 }
   56548 
   56549 /* Opcode: NullRow P1 * * * *
   56550 **
   56551 ** Move the cursor P1 to a null row.  Any OP_Column operations
   56552 ** that occur while the cursor is on the null row will always
   56553 ** write a NULL.
   56554 */
   56555 case OP_NullRow: {
   56556 #if 0  /* local variables moved into u.bj */
   56557   VdbeCursor *pC;
   56558 #endif /* local variables moved into u.bj */
   56559 
   56560   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   56561   u.bj.pC = p->apCsr[pOp->p1];
   56562   assert( u.bj.pC!=0 );
   56563   u.bj.pC->nullRow = 1;
   56564   u.bj.pC->rowidIsValid = 0;
   56565   if( u.bj.pC->pCursor ){
   56566     sqlite3BtreeClearCursor(u.bj.pC->pCursor);
   56567   }
   56568   break;
   56569 }
   56570 
   56571 /* Opcode: Last P1 P2 * * *
   56572 **
   56573 ** The next use of the Rowid or Column or Next instruction for P1
   56574 ** will refer to the last entry in the database table or index.
   56575 ** If the table or index is empty and P2>0, then jump immediately to P2.
   56576 ** If P2 is 0 or if the table or index is not empty, fall through
   56577 ** to the following instruction.
   56578 */
   56579 case OP_Last: {        /* jump */
   56580 #if 0  /* local variables moved into u.bk */
   56581   VdbeCursor *pC;
   56582   BtCursor *pCrsr;
   56583   int res;
   56584 #endif /* local variables moved into u.bk */
   56585 
   56586   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   56587   u.bk.pC = p->apCsr[pOp->p1];
   56588   assert( u.bk.pC!=0 );
   56589   u.bk.pCrsr = u.bk.pC->pCursor;
   56590   if( u.bk.pCrsr==0 ){
   56591     u.bk.res = 1;
   56592   }else{
   56593     rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
   56594   }
   56595   u.bk.pC->nullRow = (u8)u.bk.res;
   56596   u.bk.pC->deferredMoveto = 0;
   56597   u.bk.pC->rowidIsValid = 0;
   56598   u.bk.pC->cacheStatus = CACHE_STALE;
   56599   if( pOp->p2>0 && u.bk.res ){
   56600     pc = pOp->p2 - 1;
   56601   }
   56602   break;
   56603 }
   56604 
   56605 
   56606 /* Opcode: Sort P1 P2 * * *
   56607 **
   56608 ** This opcode does exactly the same thing as OP_Rewind except that
   56609 ** it increments an undocumented global variable used for testing.
   56610 **
   56611 ** Sorting is accomplished by writing records into a sorting index,
   56612 ** then rewinding that index and playing it back from beginning to
   56613 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
   56614 ** rewinding so that the global variable will be incremented and
   56615 ** regression tests can determine whether or not the optimizer is
   56616 ** correctly optimizing out sorts.
   56617 */
   56618 case OP_Sort: {        /* jump */
   56619 #ifdef SQLITE_TEST
   56620   sqlite3_sort_count++;
   56621   sqlite3_search_count--;
   56622 #endif
   56623   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
   56624   /* Fall through into OP_Rewind */
   56625 }
   56626 /* Opcode: Rewind P1 P2 * * *
   56627 **
   56628 ** The next use of the Rowid or Column or Next instruction for P1
   56629 ** will refer to the first entry in the database table or index.
   56630 ** If the table or index is empty and P2>0, then jump immediately to P2.
   56631 ** If P2 is 0 or if the table or index is not empty, fall through
   56632 ** to the following instruction.
   56633 */
   56634 case OP_Rewind: {        /* jump */
   56635 #if 0  /* local variables moved into u.bl */
   56636   VdbeCursor *pC;
   56637   BtCursor *pCrsr;
   56638   int res;
   56639 #endif /* local variables moved into u.bl */
   56640 
   56641   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   56642   u.bl.pC = p->apCsr[pOp->p1];
   56643   assert( u.bl.pC!=0 );
   56644   if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
   56645     rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
   56646     u.bl.pC->atFirst = u.bl.res==0 ?1:0;
   56647     u.bl.pC->deferredMoveto = 0;
   56648     u.bl.pC->cacheStatus = CACHE_STALE;
   56649     u.bl.pC->rowidIsValid = 0;
   56650   }else{
   56651     u.bl.res = 1;
   56652   }
   56653   u.bl.pC->nullRow = (u8)u.bl.res;
   56654   assert( pOp->p2>0 && pOp->p2<p->nOp );
   56655   if( u.bl.res ){
   56656     pc = pOp->p2 - 1;
   56657   }
   56658   break;
   56659 }
   56660 
   56661 /* Opcode: Next P1 P2 * * *
   56662 **
   56663 ** Advance cursor P1 so that it points to the next key/data pair in its
   56664 ** table or index.  If there are no more key/value pairs then fall through
   56665 ** to the following instruction.  But if the cursor advance was successful,
   56666 ** jump immediately to P2.
   56667 **
   56668 ** The P1 cursor must be for a real table, not a pseudo-table.
   56669 **
   56670 ** See also: Prev
   56671 */
   56672 /* Opcode: Prev P1 P2 * * *
   56673 **
   56674 ** Back up cursor P1 so that it points to the previous key/data pair in its
   56675 ** table or index.  If there is no previous key/value pairs then fall through
   56676 ** to the following instruction.  But if the cursor backup was successful,
   56677 ** jump immediately to P2.
   56678 **
   56679 ** The P1 cursor must be for a real table, not a pseudo-table.
   56680 */
   56681 case OP_Prev:          /* jump */
   56682 case OP_Next: {        /* jump */
   56683 #if 0  /* local variables moved into u.bm */
   56684   VdbeCursor *pC;
   56685   BtCursor *pCrsr;
   56686   int res;
   56687 #endif /* local variables moved into u.bm */
   56688 
   56689   CHECK_FOR_INTERRUPT;
   56690   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   56691   u.bm.pC = p->apCsr[pOp->p1];
   56692   if( u.bm.pC==0 ){
   56693     break;  /* See ticket #2273 */
   56694   }
   56695   u.bm.pCrsr = u.bm.pC->pCursor;
   56696   if( u.bm.pCrsr==0 ){
   56697     u.bm.pC->nullRow = 1;
   56698     break;
   56699   }
   56700   u.bm.res = 1;
   56701   assert( u.bm.pC->deferredMoveto==0 );
   56702   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
   56703                               sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
   56704   u.bm.pC->nullRow = (u8)u.bm.res;
   56705   u.bm.pC->cacheStatus = CACHE_STALE;
   56706   if( u.bm.res==0 ){
   56707     pc = pOp->p2 - 1;
   56708     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
   56709 #ifdef SQLITE_TEST
   56710     sqlite3_search_count++;
   56711 #endif
   56712   }
   56713   u.bm.pC->rowidIsValid = 0;
   56714   break;
   56715 }
   56716 
   56717 /* Opcode: IdxInsert P1 P2 P3 * P5
   56718 **
   56719 ** Register P2 holds a SQL index key made using the
   56720 ** MakeRecord instructions.  This opcode writes that key
   56721 ** into the index P1.  Data for the entry is nil.
   56722 **
   56723 ** P3 is a flag that provides a hint to the b-tree layer that this
   56724 ** insert is likely to be an append.
   56725 **
   56726 ** This instruction only works for indices.  The equivalent instruction
   56727 ** for tables is OP_Insert.
   56728 */
   56729 case OP_IdxInsert: {        /* in2 */
   56730 #if 0  /* local variables moved into u.bn */
   56731   VdbeCursor *pC;
   56732   BtCursor *pCrsr;
   56733   int nKey;
   56734   const char *zKey;
   56735 #endif /* local variables moved into u.bn */
   56736 
   56737   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   56738   u.bn.pC = p->apCsr[pOp->p1];
   56739   assert( u.bn.pC!=0 );
   56740   pIn2 = &aMem[pOp->p2];
   56741   assert( pIn2->flags & MEM_Blob );
   56742   u.bn.pCrsr = u.bn.pC->pCursor;
   56743   if( ALWAYS(u.bn.pCrsr!=0) ){
   56744     assert( u.bn.pC->isTable==0 );
   56745     rc = ExpandBlob(pIn2);
   56746     if( rc==SQLITE_OK ){
   56747       u.bn.nKey = pIn2->n;
   56748       u.bn.zKey = pIn2->z;
   56749       rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
   56750           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
   56751       );
   56752       assert( u.bn.pC->deferredMoveto==0 );
   56753       u.bn.pC->cacheStatus = CACHE_STALE;
   56754     }
   56755   }
   56756   break;
   56757 }
   56758 
   56759 /* Opcode: IdxDelete P1 P2 P3 * *
   56760 **
   56761 ** The content of P3 registers starting at register P2 form
   56762 ** an unpacked index key. This opcode removes that entry from the
   56763 ** index opened by cursor P1.
   56764 */
   56765 case OP_IdxDelete: {
   56766 #if 0  /* local variables moved into u.bo */
   56767   VdbeCursor *pC;
   56768   BtCursor *pCrsr;
   56769   int res;
   56770   UnpackedRecord r;
   56771 #endif /* local variables moved into u.bo */
   56772 
   56773   assert( pOp->p3>0 );
   56774   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
   56775   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   56776   u.bo.pC = p->apCsr[pOp->p1];
   56777   assert( u.bo.pC!=0 );
   56778   u.bo.pCrsr = u.bo.pC->pCursor;
   56779   if( ALWAYS(u.bo.pCrsr!=0) ){
   56780     u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
   56781     u.bo.r.nField = (u16)pOp->p3;
   56782     u.bo.r.flags = 0;
   56783     u.bo.r.aMem = &aMem[pOp->p2];
   56784     rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
   56785     if( rc==SQLITE_OK && u.bo.res==0 ){
   56786       rc = sqlite3BtreeDelete(u.bo.pCrsr);
   56787     }
   56788     assert( u.bo.pC->deferredMoveto==0 );
   56789     u.bo.pC->cacheStatus = CACHE_STALE;
   56790   }
   56791   break;
   56792 }
   56793 
   56794 /* Opcode: IdxRowid P1 P2 * * *
   56795 **
   56796 ** Write into register P2 an integer which is the last entry in the record at
   56797 ** the end of the index key pointed to by cursor P1.  This integer should be
   56798 ** the rowid of the table entry to which this index entry points.
   56799 **
   56800 ** See also: Rowid, MakeRecord.
   56801 */
   56802 case OP_IdxRowid: {              /* out2-prerelease */
   56803 #if 0  /* local variables moved into u.bp */
   56804   BtCursor *pCrsr;
   56805   VdbeCursor *pC;
   56806   i64 rowid;
   56807 #endif /* local variables moved into u.bp */
   56808 
   56809   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   56810   u.bp.pC = p->apCsr[pOp->p1];
   56811   assert( u.bp.pC!=0 );
   56812   u.bp.pCrsr = u.bp.pC->pCursor;
   56813   pOut->flags = MEM_Null;
   56814   if( ALWAYS(u.bp.pCrsr!=0) ){
   56815     rc = sqlite3VdbeCursorMoveto(u.bp.pC);
   56816     if( NEVER(rc) ) goto abort_due_to_error;
   56817     assert( u.bp.pC->deferredMoveto==0 );
   56818     assert( u.bp.pC->isTable==0 );
   56819     if( !u.bp.pC->nullRow ){
   56820       rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
   56821       if( rc!=SQLITE_OK ){
   56822         goto abort_due_to_error;
   56823       }
   56824       pOut->u.i = u.bp.rowid;
   56825       pOut->flags = MEM_Int;
   56826     }
   56827   }
   56828   break;
   56829 }
   56830 
   56831 /* Opcode: IdxGE P1 P2 P3 P4 P5
   56832 **
   56833 ** The P4 register values beginning with P3 form an unpacked index
   56834 ** key that omits the ROWID.  Compare this key value against the index
   56835 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
   56836 **
   56837 ** If the P1 index entry is greater than or equal to the key value
   56838 ** then jump to P2.  Otherwise fall through to the next instruction.
   56839 **
   56840 ** If P5 is non-zero then the key value is increased by an epsilon
   56841 ** prior to the comparison.  This make the opcode work like IdxGT except
   56842 ** that if the key from register P3 is a prefix of the key in the cursor,
   56843 ** the result is false whereas it would be true with IdxGT.
   56844 */
   56845 /* Opcode: IdxLT P1 P2 P3 * P5
   56846 **
   56847 ** The P4 register values beginning with P3 form an unpacked index
   56848 ** key that omits the ROWID.  Compare this key value against the index
   56849 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
   56850 **
   56851 ** If the P1 index entry is less than the key value then jump to P2.
   56852 ** Otherwise fall through to the next instruction.
   56853 **
   56854 ** If P5 is non-zero then the key value is increased by an epsilon prior
   56855 ** to the comparison.  This makes the opcode work like IdxLE.
   56856 */
   56857 case OP_IdxLT:          /* jump */
   56858 case OP_IdxGE: {        /* jump */
   56859 #if 0  /* local variables moved into u.bq */
   56860   VdbeCursor *pC;
   56861   int res;
   56862   UnpackedRecord r;
   56863 #endif /* local variables moved into u.bq */
   56864 
   56865   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   56866   u.bq.pC = p->apCsr[pOp->p1];
   56867   assert( u.bq.pC!=0 );
   56868   if( ALWAYS(u.bq.pC->pCursor!=0) ){
   56869     assert( u.bq.pC->deferredMoveto==0 );
   56870     assert( pOp->p5==0 || pOp->p5==1 );
   56871     assert( pOp->p4type==P4_INT32 );
   56872     u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
   56873     u.bq.r.nField = (u16)pOp->p4.i;
   56874     if( pOp->p5 ){
   56875       u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
   56876     }else{
   56877       u.bq.r.flags = UNPACKED_IGNORE_ROWID;
   56878     }
   56879     u.bq.r.aMem = &aMem[pOp->p3];
   56880     rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
   56881     if( pOp->opcode==OP_IdxLT ){
   56882       u.bq.res = -u.bq.res;
   56883     }else{
   56884       assert( pOp->opcode==OP_IdxGE );
   56885       u.bq.res++;
   56886     }
   56887     if( u.bq.res>0 ){
   56888       pc = pOp->p2 - 1 ;
   56889     }
   56890   }
   56891   break;
   56892 }
   56893 
   56894 /* Opcode: Destroy P1 P2 P3 * *
   56895 **
   56896 ** Delete an entire database table or index whose root page in the database
   56897 ** file is given by P1.
   56898 **
   56899 ** The table being destroyed is in the main database file if P3==0.  If
   56900 ** P3==1 then the table to be clear is in the auxiliary database file
   56901 ** that is used to store tables create using CREATE TEMPORARY TABLE.
   56902 **
   56903 ** If AUTOVACUUM is enabled then it is possible that another root page
   56904 ** might be moved into the newly deleted root page in order to keep all
   56905 ** root pages contiguous at the beginning of the database.  The former
   56906 ** value of the root page that moved - its value before the move occurred -
   56907 ** is stored in register P2.  If no page
   56908 ** movement was required (because the table being dropped was already
   56909 ** the last one in the database) then a zero is stored in register P2.
   56910 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
   56911 **
   56912 ** See also: Clear
   56913 */
   56914 case OP_Destroy: {     /* out2-prerelease */
   56915 #if 0  /* local variables moved into u.br */
   56916   int iMoved;
   56917   int iCnt;
   56918   Vdbe *pVdbe;
   56919   int iDb;
   56920 #endif /* local variables moved into u.br */
   56921 #ifndef SQLITE_OMIT_VIRTUALTABLE
   56922   u.br.iCnt = 0;
   56923   for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
   56924     if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
   56925       u.br.iCnt++;
   56926     }
   56927   }
   56928 #else
   56929   u.br.iCnt = db->activeVdbeCnt;
   56930 #endif
   56931   pOut->flags = MEM_Null;
   56932   if( u.br.iCnt>1 ){
   56933     rc = SQLITE_LOCKED;
   56934     p->errorAction = OE_Abort;
   56935   }else{
   56936     u.br.iDb = pOp->p3;
   56937     assert( u.br.iCnt==1 );
   56938     assert( (p->btreeMask & (1<<u.br.iDb))!=0 );
   56939     rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
   56940     pOut->flags = MEM_Int;
   56941     pOut->u.i = u.br.iMoved;
   56942 #ifndef SQLITE_OMIT_AUTOVACUUM
   56943     if( rc==SQLITE_OK && u.br.iMoved!=0 ){
   56944       sqlite3RootPageMoved(&db->aDb[u.br.iDb], u.br.iMoved, pOp->p1);
   56945       resetSchemaOnFault = 1;
   56946     }
   56947 #endif
   56948   }
   56949   break;
   56950 }
   56951 
   56952 /* Opcode: Clear P1 P2 P3
   56953 **
   56954 ** Delete all contents of the database table or index whose root page
   56955 ** in the database file is given by P1.  But, unlike Destroy, do not
   56956 ** remove the table or index from the database file.
   56957 **
   56958 ** The table being clear is in the main database file if P2==0.  If
   56959 ** P2==1 then the table to be clear is in the auxiliary database file
   56960 ** that is used to store tables create using CREATE TEMPORARY TABLE.
   56961 **
   56962 ** If the P3 value is non-zero, then the table referred to must be an
   56963 ** intkey table (an SQL table, not an index). In this case the row change
   56964 ** count is incremented by the number of rows in the table being cleared.
   56965 ** If P3 is greater than zero, then the value stored in register P3 is
   56966 ** also incremented by the number of rows in the table being cleared.
   56967 **
   56968 ** See also: Destroy
   56969 */
   56970 case OP_Clear: {
   56971 #if 0  /* local variables moved into u.bs */
   56972   int nChange;
   56973 #endif /* local variables moved into u.bs */
   56974 
   56975   u.bs.nChange = 0;
   56976   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
   56977   rc = sqlite3BtreeClearTable(
   56978       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
   56979   );
   56980   if( pOp->p3 ){
   56981     p->nChange += u.bs.nChange;
   56982     if( pOp->p3>0 ){
   56983       aMem[pOp->p3].u.i += u.bs.nChange;
   56984     }
   56985   }
   56986   break;
   56987 }
   56988 
   56989 /* Opcode: CreateTable P1 P2 * * *
   56990 **
   56991 ** Allocate a new table in the main database file if P1==0 or in the
   56992 ** auxiliary database file if P1==1 or in an attached database if
   56993 ** P1>1.  Write the root page number of the new table into
   56994 ** register P2
   56995 **
   56996 ** The difference between a table and an index is this:  A table must
   56997 ** have a 4-byte integer key and can have arbitrary data.  An index
   56998 ** has an arbitrary key but no data.
   56999 **
   57000 ** See also: CreateIndex
   57001 */
   57002 /* Opcode: CreateIndex P1 P2 * * *
   57003 **
   57004 ** Allocate a new index in the main database file if P1==0 or in the
   57005 ** auxiliary database file if P1==1 or in an attached database if
   57006 ** P1>1.  Write the root page number of the new table into
   57007 ** register P2.
   57008 **
   57009 ** See documentation on OP_CreateTable for additional information.
   57010 */
   57011 case OP_CreateIndex:            /* out2-prerelease */
   57012 case OP_CreateTable: {          /* out2-prerelease */
   57013 #if 0  /* local variables moved into u.bt */
   57014   int pgno;
   57015   int flags;
   57016   Db *pDb;
   57017 #endif /* local variables moved into u.bt */
   57018 
   57019   u.bt.pgno = 0;
   57020   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   57021   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
   57022   u.bt.pDb = &db->aDb[pOp->p1];
   57023   assert( u.bt.pDb->pBt!=0 );
   57024   if( pOp->opcode==OP_CreateTable ){
   57025     /* u.bt.flags = BTREE_INTKEY; */
   57026     u.bt.flags = BTREE_LEAFDATA|BTREE_INTKEY;
   57027   }else{
   57028     u.bt.flags = BTREE_ZERODATA;
   57029   }
   57030   rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
   57031   pOut->u.i = u.bt.pgno;
   57032   break;
   57033 }
   57034 
   57035 /* Opcode: ParseSchema P1 P2 * P4 *
   57036 **
   57037 ** Read and parse all entries from the SQLITE_MASTER table of database P1
   57038 ** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
   57039 ** the parsing if P2 is true.  If P2 is false, then this routine is a
   57040 ** no-op if the schema is not currently loaded.  In other words, if P2
   57041 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
   57042 ** schema is already loaded into the symbol table.
   57043 **
   57044 ** This opcode invokes the parser to create a new virtual machine,
   57045 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
   57046 */
   57047 case OP_ParseSchema: {
   57048 #if 0  /* local variables moved into u.bu */
   57049   int iDb;
   57050   const char *zMaster;
   57051   char *zSql;
   57052   InitData initData;
   57053 #endif /* local variables moved into u.bu */
   57054 
   57055   u.bu.iDb = pOp->p1;
   57056   assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
   57057 
   57058   /* If pOp->p2 is 0, then this opcode is being executed to read a
   57059   ** single row, for example the row corresponding to a new index
   57060   ** created by this VDBE, from the sqlite_master table. It only
   57061   ** does this if the corresponding in-memory schema is currently
   57062   ** loaded. Otherwise, the new index definition can be loaded along
   57063   ** with the rest of the schema when it is required.
   57064   **
   57065   ** Although the mutex on the BtShared object that corresponds to
   57066   ** database u.bu.iDb (the database containing the sqlite_master table
   57067   ** read by this instruction) is currently held, it is necessary to
   57068   ** obtain the mutexes on all attached databases before checking if
   57069   ** the schema of u.bu.iDb is loaded. This is because, at the start of
   57070   ** the sqlite3_exec() call below, SQLite will invoke
   57071   ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
   57072   ** u.bu.iDb mutex may be temporarily released to avoid deadlock. If
   57073   ** this happens, then some other thread may delete the in-memory
   57074   ** schema of database u.bu.iDb before the SQL statement runs. The schema
   57075   ** will not be reloaded becuase the db->init.busy flag is set. This
   57076   ** can result in a "no such table: sqlite_master" or "malformed
   57077   ** database schema" error being returned to the user.
   57078   */
   57079   assert( sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
   57080   sqlite3BtreeEnterAll(db);
   57081   if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){
   57082     u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
   57083     u.bu.initData.db = db;
   57084     u.bu.initData.iDb = pOp->p1;
   57085     u.bu.initData.pzErrMsg = &p->zErrMsg;
   57086     u.bu.zSql = sqlite3MPrintf(db,
   57087        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
   57088        db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
   57089     if( u.bu.zSql==0 ){
   57090       rc = SQLITE_NOMEM;
   57091     }else{
   57092       assert( db->init.busy==0 );
   57093       db->init.busy = 1;
   57094       u.bu.initData.rc = SQLITE_OK;
   57095       assert( !db->mallocFailed );
   57096       rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
   57097       if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
   57098       sqlite3DbFree(db, u.bu.zSql);
   57099       db->init.busy = 0;
   57100     }
   57101   }
   57102   sqlite3BtreeLeaveAll(db);
   57103   if( rc==SQLITE_NOMEM ){
   57104     goto no_mem;
   57105   }
   57106   break;
   57107 }
   57108 
   57109 #if !defined(SQLITE_OMIT_ANALYZE)
   57110 /* Opcode: LoadAnalysis P1 * * * *
   57111 **
   57112 ** Read the sqlite_stat1 table for database P1 and load the content
   57113 ** of that table into the internal index hash table.  This will cause
   57114 ** the analysis to be used when preparing all subsequent queries.
   57115 */
   57116 case OP_LoadAnalysis: {
   57117   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   57118   rc = sqlite3AnalysisLoad(db, pOp->p1);
   57119   break;
   57120 }
   57121 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
   57122 
   57123 /* Opcode: DropTable P1 * * P4 *
   57124 **
   57125 ** Remove the internal (in-memory) data structures that describe
   57126 ** the table named P4 in database P1.  This is called after a table
   57127 ** is dropped in order to keep the internal representation of the
   57128 ** schema consistent with what is on disk.
   57129 */
   57130 case OP_DropTable: {
   57131   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
   57132   break;
   57133 }
   57134 
   57135 /* Opcode: DropIndex P1 * * P4 *
   57136 **
   57137 ** Remove the internal (in-memory) data structures that describe
   57138 ** the index named P4 in database P1.  This is called after an index
   57139 ** is dropped in order to keep the internal representation of the
   57140 ** schema consistent with what is on disk.
   57141 */
   57142 case OP_DropIndex: {
   57143   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
   57144   break;
   57145 }
   57146 
   57147 /* Opcode: DropTrigger P1 * * P4 *
   57148 **
   57149 ** Remove the internal (in-memory) data structures that describe
   57150 ** the trigger named P4 in database P1.  This is called after a trigger
   57151 ** is dropped in order to keep the internal representation of the
   57152 ** schema consistent with what is on disk.
   57153 */
   57154 case OP_DropTrigger: {
   57155   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
   57156   break;
   57157 }
   57158 
   57159 
   57160 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   57161 /* Opcode: IntegrityCk P1 P2 P3 * P5
   57162 **
   57163 ** Do an analysis of the currently open database.  Store in
   57164 ** register P1 the text of an error message describing any problems.
   57165 ** If no problems are found, store a NULL in register P1.
   57166 **
   57167 ** The register P3 contains the maximum number of allowed errors.
   57168 ** At most reg(P3) errors will be reported.
   57169 ** In other words, the analysis stops as soon as reg(P1) errors are
   57170 ** seen.  Reg(P1) is updated with the number of errors remaining.
   57171 **
   57172 ** The root page numbers of all tables in the database are integer
   57173 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
   57174 ** total.
   57175 **
   57176 ** If P5 is not zero, the check is done on the auxiliary database
   57177 ** file, not the main database file.
   57178 **
   57179 ** This opcode is used to implement the integrity_check pragma.
   57180 */
   57181 case OP_IntegrityCk: {
   57182 #if 0  /* local variables moved into u.bv */
   57183   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
   57184   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
   57185   int j;          /* Loop counter */
   57186   int nErr;       /* Number of errors reported */
   57187   char *z;        /* Text of the error report */
   57188   Mem *pnErr;     /* Register keeping track of errors remaining */
   57189 #endif /* local variables moved into u.bv */
   57190 
   57191   u.bv.nRoot = pOp->p2;
   57192   assert( u.bv.nRoot>0 );
   57193   u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
   57194   if( u.bv.aRoot==0 ) goto no_mem;
   57195   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   57196   u.bv.pnErr = &aMem[pOp->p3];
   57197   assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
   57198   assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
   57199   pIn1 = &aMem[pOp->p1];
   57200   for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
   57201     u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
   57202   }
   57203   u.bv.aRoot[u.bv.j] = 0;
   57204   assert( pOp->p5<db->nDb );
   57205   assert( (p->btreeMask & (1<<pOp->p5))!=0 );
   57206   u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
   57207                                  (int)u.bv.pnErr->u.i, &u.bv.nErr);
   57208   sqlite3DbFree(db, u.bv.aRoot);
   57209   u.bv.pnErr->u.i -= u.bv.nErr;
   57210   sqlite3VdbeMemSetNull(pIn1);
   57211   if( u.bv.nErr==0 ){
   57212     assert( u.bv.z==0 );
   57213   }else if( u.bv.z==0 ){
   57214     goto no_mem;
   57215   }else{
   57216     sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
   57217   }
   57218   UPDATE_MAX_BLOBSIZE(pIn1);
   57219   sqlite3VdbeChangeEncoding(pIn1, encoding);
   57220   break;
   57221 }
   57222 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   57223 
   57224 /* Opcode: RowSetAdd P1 P2 * * *
   57225 **
   57226 ** Insert the integer value held by register P2 into a boolean index
   57227 ** held in register P1.
   57228 **
   57229 ** An assertion fails if P2 is not an integer.
   57230 */
   57231 case OP_RowSetAdd: {       /* in1, in2 */
   57232   pIn1 = &aMem[pOp->p1];
   57233   pIn2 = &aMem[pOp->p2];
   57234   assert( (pIn2->flags & MEM_Int)!=0 );
   57235   if( (pIn1->flags & MEM_RowSet)==0 ){
   57236     sqlite3VdbeMemSetRowSet(pIn1);
   57237     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
   57238   }
   57239   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
   57240   break;
   57241 }
   57242 
   57243 /* Opcode: RowSetRead P1 P2 P3 * *
   57244 **
   57245 ** Extract the smallest value from boolean index P1 and put that value into
   57246 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
   57247 ** unchanged and jump to instruction P2.
   57248 */
   57249 case OP_RowSetRead: {       /* jump, in1, out3 */
   57250 #if 0  /* local variables moved into u.bw */
   57251   i64 val;
   57252 #endif /* local variables moved into u.bw */
   57253   CHECK_FOR_INTERRUPT;
   57254   pIn1 = &aMem[pOp->p1];
   57255   if( (pIn1->flags & MEM_RowSet)==0
   57256    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
   57257   ){
   57258     /* The boolean index is empty */
   57259     sqlite3VdbeMemSetNull(pIn1);
   57260     pc = pOp->p2 - 1;
   57261   }else{
   57262     /* A value was pulled from the index */
   57263     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
   57264   }
   57265   break;
   57266 }
   57267 
   57268 /* Opcode: RowSetTest P1 P2 P3 P4
   57269 **
   57270 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
   57271 ** contains a RowSet object and that RowSet object contains
   57272 ** the value held in P3, jump to register P2. Otherwise, insert the
   57273 ** integer in P3 into the RowSet and continue on to the
   57274 ** next opcode.
   57275 **
   57276 ** The RowSet object is optimized for the case where successive sets
   57277 ** of integers, where each set contains no duplicates. Each set
   57278 ** of values is identified by a unique P4 value. The first set
   57279 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
   57280 ** non-negative.  For non-negative values of P4 only the lower 4
   57281 ** bits are significant.
   57282 **
   57283 ** This allows optimizations: (a) when P4==0 there is no need to test
   57284 ** the rowset object for P3, as it is guaranteed not to contain it,
   57285 ** (b) when P4==-1 there is no need to insert the value, as it will
   57286 ** never be tested for, and (c) when a value that is part of set X is
   57287 ** inserted, there is no need to search to see if the same value was
   57288 ** previously inserted as part of set X (only if it was previously
   57289 ** inserted as part of some other set).
   57290 */
   57291 case OP_RowSetTest: {                     /* jump, in1, in3 */
   57292 #if 0  /* local variables moved into u.bx */
   57293   int iSet;
   57294   int exists;
   57295 #endif /* local variables moved into u.bx */
   57296 
   57297   pIn1 = &aMem[pOp->p1];
   57298   pIn3 = &aMem[pOp->p3];
   57299   u.bx.iSet = pOp->p4.i;
   57300   assert( pIn3->flags&MEM_Int );
   57301 
   57302   /* If there is anything other than a rowset object in memory cell P1,
   57303   ** delete it now and initialize P1 with an empty rowset
   57304   */
   57305   if( (pIn1->flags & MEM_RowSet)==0 ){
   57306     sqlite3VdbeMemSetRowSet(pIn1);
   57307     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
   57308   }
   57309 
   57310   assert( pOp->p4type==P4_INT32 );
   57311   assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
   57312   if( u.bx.iSet ){
   57313     u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
   57314                                (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
   57315                                pIn3->u.i);
   57316     if( u.bx.exists ){
   57317       pc = pOp->p2 - 1;
   57318       break;
   57319     }
   57320   }
   57321   if( u.bx.iSet>=0 ){
   57322     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
   57323   }
   57324   break;
   57325 }
   57326 
   57327 
   57328 #ifndef SQLITE_OMIT_TRIGGER
   57329 
   57330 /* Opcode: Program P1 P2 P3 P4 *
   57331 **
   57332 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
   57333 **
   57334 ** P1 contains the address of the memory cell that contains the first memory
   57335 ** cell in an array of values used as arguments to the sub-program. P2
   57336 ** contains the address to jump to if the sub-program throws an IGNORE
   57337 ** exception using the RAISE() function. Register P3 contains the address
   57338 ** of a memory cell in this (the parent) VM that is used to allocate the
   57339 ** memory required by the sub-vdbe at runtime.
   57340 **
   57341 ** P4 is a pointer to the VM containing the trigger program.
   57342 */
   57343 case OP_Program: {        /* jump */
   57344 #if 0  /* local variables moved into u.by */
   57345   int nMem;               /* Number of memory registers for sub-program */
   57346   int nByte;              /* Bytes of runtime space required for sub-program */
   57347   Mem *pRt;               /* Register to allocate runtime space */
   57348   Mem *pMem;              /* Used to iterate through memory cells */
   57349   Mem *pEnd;              /* Last memory cell in new array */
   57350   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
   57351   SubProgram *pProgram;   /* Sub-program to execute */
   57352   void *t;                /* Token identifying trigger */
   57353 #endif /* local variables moved into u.by */
   57354 
   57355   u.by.pProgram = pOp->p4.pProgram;
   57356   u.by.pRt = &aMem[pOp->p3];
   57357   assert( u.by.pProgram->nOp>0 );
   57358 
   57359   /* If the p5 flag is clear, then recursive invocation of triggers is
   57360   ** disabled for backwards compatibility (p5 is set if this sub-program
   57361   ** is really a trigger, not a foreign key action, and the flag set
   57362   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
   57363   **
   57364   ** It is recursive invocation of triggers, at the SQL level, that is
   57365   ** disabled. In some cases a single trigger may generate more than one
   57366   ** SubProgram (if the trigger may be executed with more than one different
   57367   ** ON CONFLICT algorithm). SubProgram structures associated with a
   57368   ** single trigger all have the same value for the SubProgram.token
   57369   ** variable.  */
   57370   if( pOp->p5 ){
   57371     u.by.t = u.by.pProgram->token;
   57372     for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
   57373     if( u.by.pFrame ) break;
   57374   }
   57375 
   57376   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
   57377     rc = SQLITE_ERROR;
   57378     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
   57379     break;
   57380   }
   57381 
   57382   /* Register u.by.pRt is used to store the memory required to save the state
   57383   ** of the current program, and the memory required at runtime to execute
   57384   ** the trigger program. If this trigger has been fired before, then u.by.pRt
   57385   ** is already allocated. Otherwise, it must be initialized.  */
   57386   if( (u.by.pRt->flags&MEM_Frame)==0 ){
   57387     /* SubProgram.nMem is set to the number of memory cells used by the
   57388     ** program stored in SubProgram.aOp. As well as these, one memory
   57389     ** cell is required for each cursor used by the program. Set local
   57390     ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
   57391     */
   57392     u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
   57393     u.by.nByte = ROUND8(sizeof(VdbeFrame))
   57394               + u.by.nMem * sizeof(Mem)
   57395               + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
   57396     u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
   57397     if( !u.by.pFrame ){
   57398       goto no_mem;
   57399     }
   57400     sqlite3VdbeMemRelease(u.by.pRt);
   57401     u.by.pRt->flags = MEM_Frame;
   57402     u.by.pRt->u.pFrame = u.by.pFrame;
   57403 
   57404     u.by.pFrame->v = p;
   57405     u.by.pFrame->nChildMem = u.by.nMem;
   57406     u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
   57407     u.by.pFrame->pc = pc;
   57408     u.by.pFrame->aMem = p->aMem;
   57409     u.by.pFrame->nMem = p->nMem;
   57410     u.by.pFrame->apCsr = p->apCsr;
   57411     u.by.pFrame->nCursor = p->nCursor;
   57412     u.by.pFrame->aOp = p->aOp;
   57413     u.by.pFrame->nOp = p->nOp;
   57414     u.by.pFrame->token = u.by.pProgram->token;
   57415 
   57416     u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
   57417     for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
   57418       u.by.pMem->flags = MEM_Null;
   57419       u.by.pMem->db = db;
   57420     }
   57421   }else{
   57422     u.by.pFrame = u.by.pRt->u.pFrame;
   57423     assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
   57424     assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
   57425     assert( pc==u.by.pFrame->pc );
   57426   }
   57427 
   57428   p->nFrame++;
   57429   u.by.pFrame->pParent = p->pFrame;
   57430   u.by.pFrame->lastRowid = db->lastRowid;
   57431   u.by.pFrame->nChange = p->nChange;
   57432   p->nChange = 0;
   57433   p->pFrame = u.by.pFrame;
   57434   p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
   57435   p->nMem = u.by.pFrame->nChildMem;
   57436   p->nCursor = (u16)u.by.pFrame->nChildCsr;
   57437   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
   57438   p->aOp = aOp = u.by.pProgram->aOp;
   57439   p->nOp = u.by.pProgram->nOp;
   57440   pc = -1;
   57441 
   57442   break;
   57443 }
   57444 
   57445 /* Opcode: Param P1 P2 * * *
   57446 **
   57447 ** This opcode is only ever present in sub-programs called via the
   57448 ** OP_Program instruction. Copy a value currently stored in a memory
   57449 ** cell of the calling (parent) frame to cell P2 in the current frames
   57450 ** address space. This is used by trigger programs to access the new.*
   57451 ** and old.* values.
   57452 **
   57453 ** The address of the cell in the parent frame is determined by adding
   57454 ** the value of the P1 argument to the value of the P1 argument to the
   57455 ** calling OP_Program instruction.
   57456 */
   57457 case OP_Param: {           /* out2-prerelease */
   57458 #if 0  /* local variables moved into u.bz */
   57459   VdbeFrame *pFrame;
   57460   Mem *pIn;
   57461 #endif /* local variables moved into u.bz */
   57462   u.bz.pFrame = p->pFrame;
   57463   u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
   57464   sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
   57465   break;
   57466 }
   57467 
   57468 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
   57469 
   57470 #ifndef SQLITE_OMIT_FOREIGN_KEY
   57471 /* Opcode: FkCounter P1 P2 * * *
   57472 **
   57473 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
   57474 ** If P1 is non-zero, the database constraint counter is incremented
   57475 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
   57476 ** statement counter is incremented (immediate foreign key constraints).
   57477 */
   57478 case OP_FkCounter: {
   57479   if( pOp->p1 ){
   57480     db->nDeferredCons += pOp->p2;
   57481   }else{
   57482     p->nFkConstraint += pOp->p2;
   57483   }
   57484   break;
   57485 }
   57486 
   57487 /* Opcode: FkIfZero P1 P2 * * *
   57488 **
   57489 ** This opcode tests if a foreign key constraint-counter is currently zero.
   57490 ** If so, jump to instruction P2. Otherwise, fall through to the next
   57491 ** instruction.
   57492 **
   57493 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
   57494 ** is zero (the one that counts deferred constraint violations). If P1 is
   57495 ** zero, the jump is taken if the statement constraint-counter is zero
   57496 ** (immediate foreign key constraint violations).
   57497 */
   57498 case OP_FkIfZero: {         /* jump */
   57499   if( pOp->p1 ){
   57500     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
   57501   }else{
   57502     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
   57503   }
   57504   break;
   57505 }
   57506 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
   57507 
   57508 #ifndef SQLITE_OMIT_AUTOINCREMENT
   57509 /* Opcode: MemMax P1 P2 * * *
   57510 **
   57511 ** P1 is a register in the root frame of this VM (the root frame is
   57512 ** different from the current frame if this instruction is being executed
   57513 ** within a sub-program). Set the value of register P1 to the maximum of
   57514 ** its current value and the value in register P2.
   57515 **
   57516 ** This instruction throws an error if the memory cell is not initially
   57517 ** an integer.
   57518 */
   57519 case OP_MemMax: {        /* in2 */
   57520 #if 0  /* local variables moved into u.ca */
   57521   Mem *pIn1;
   57522   VdbeFrame *pFrame;
   57523 #endif /* local variables moved into u.ca */
   57524   if( p->pFrame ){
   57525     for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
   57526     u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
   57527   }else{
   57528     u.ca.pIn1 = &aMem[pOp->p1];
   57529   }
   57530   sqlite3VdbeMemIntegerify(u.ca.pIn1);
   57531   pIn2 = &aMem[pOp->p2];
   57532   sqlite3VdbeMemIntegerify(pIn2);
   57533   if( u.ca.pIn1->u.i<pIn2->u.i){
   57534     u.ca.pIn1->u.i = pIn2->u.i;
   57535   }
   57536   break;
   57537 }
   57538 #endif /* SQLITE_OMIT_AUTOINCREMENT */
   57539 
   57540 /* Opcode: IfPos P1 P2 * * *
   57541 **
   57542 ** If the value of register P1 is 1 or greater, jump to P2.
   57543 **
   57544 ** It is illegal to use this instruction on a register that does
   57545 ** not contain an integer.  An assertion fault will result if you try.
   57546 */
   57547 case OP_IfPos: {        /* jump, in1 */
   57548   pIn1 = &aMem[pOp->p1];
   57549   assert( pIn1->flags&MEM_Int );
   57550   if( pIn1->u.i>0 ){
   57551      pc = pOp->p2 - 1;
   57552   }
   57553   break;
   57554 }
   57555 
   57556 /* Opcode: IfNeg P1 P2 * * *
   57557 **
   57558 ** If the value of register P1 is less than zero, jump to P2.
   57559 **
   57560 ** It is illegal to use this instruction on a register that does
   57561 ** not contain an integer.  An assertion fault will result if you try.
   57562 */
   57563 case OP_IfNeg: {        /* jump, in1 */
   57564   pIn1 = &aMem[pOp->p1];
   57565   assert( pIn1->flags&MEM_Int );
   57566   if( pIn1->u.i<0 ){
   57567      pc = pOp->p2 - 1;
   57568   }
   57569   break;
   57570 }
   57571 
   57572 /* Opcode: IfZero P1 P2 P3 * *
   57573 **
   57574 ** The register P1 must contain an integer.  Add literal P3 to the
   57575 ** value in register P1.  If the result is exactly 0, jump to P2.
   57576 **
   57577 ** It is illegal to use this instruction on a register that does
   57578 ** not contain an integer.  An assertion fault will result if you try.
   57579 */
   57580 case OP_IfZero: {        /* jump, in1 */
   57581   pIn1 = &aMem[pOp->p1];
   57582   assert( pIn1->flags&MEM_Int );
   57583   pIn1->u.i += pOp->p3;
   57584   if( pIn1->u.i==0 ){
   57585      pc = pOp->p2 - 1;
   57586   }
   57587   break;
   57588 }
   57589 
   57590 /* Opcode: AggStep * P2 P3 P4 P5
   57591 **
   57592 ** Execute the step function for an aggregate.  The
   57593 ** function has P5 arguments.   P4 is a pointer to the FuncDef
   57594 ** structure that specifies the function.  Use register
   57595 ** P3 as the accumulator.
   57596 **
   57597 ** The P5 arguments are taken from register P2 and its
   57598 ** successors.
   57599 */
   57600 case OP_AggStep: {
   57601 #if 0  /* local variables moved into u.cb */
   57602   int n;
   57603   int i;
   57604   Mem *pMem;
   57605   Mem *pRec;
   57606   sqlite3_context ctx;
   57607   sqlite3_value **apVal;
   57608 #endif /* local variables moved into u.cb */
   57609 
   57610   u.cb.n = pOp->p5;
   57611   assert( u.cb.n>=0 );
   57612   u.cb.pRec = &aMem[pOp->p2];
   57613   u.cb.apVal = p->apArg;
   57614   assert( u.cb.apVal || u.cb.n==0 );
   57615   for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
   57616     u.cb.apVal[u.cb.i] = u.cb.pRec;
   57617     sqlite3VdbeMemStoreType(u.cb.pRec);
   57618   }
   57619   u.cb.ctx.pFunc = pOp->p4.pFunc;
   57620   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   57621   u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
   57622   u.cb.pMem->n++;
   57623   u.cb.ctx.s.flags = MEM_Null;
   57624   u.cb.ctx.s.z = 0;
   57625   u.cb.ctx.s.zMalloc = 0;
   57626   u.cb.ctx.s.xDel = 0;
   57627   u.cb.ctx.s.db = db;
   57628   u.cb.ctx.isError = 0;
   57629   u.cb.ctx.pColl = 0;
   57630   if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
   57631     assert( pOp>p->aOp );
   57632     assert( pOp[-1].p4type==P4_COLLSEQ );
   57633     assert( pOp[-1].opcode==OP_CollSeq );
   57634     u.cb.ctx.pColl = pOp[-1].p4.pColl;
   57635   }
   57636   (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal);
   57637   if( u.cb.ctx.isError ){
   57638     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
   57639     rc = u.cb.ctx.isError;
   57640   }
   57641   sqlite3VdbeMemRelease(&u.cb.ctx.s);
   57642   break;
   57643 }
   57644 
   57645 /* Opcode: AggFinal P1 P2 * P4 *
   57646 **
   57647 ** Execute the finalizer function for an aggregate.  P1 is
   57648 ** the memory location that is the accumulator for the aggregate.
   57649 **
   57650 ** P2 is the number of arguments that the step function takes and
   57651 ** P4 is a pointer to the FuncDef for this function.  The P2
   57652 ** argument is not used by this opcode.  It is only there to disambiguate
   57653 ** functions that can take varying numbers of arguments.  The
   57654 ** P4 argument is only needed for the degenerate case where
   57655 ** the step function was not previously called.
   57656 */
   57657 case OP_AggFinal: {
   57658 #if 0  /* local variables moved into u.cc */
   57659   Mem *pMem;
   57660 #endif /* local variables moved into u.cc */
   57661   assert( pOp->p1>0 && pOp->p1<=p->nMem );
   57662   u.cc.pMem = &aMem[pOp->p1];
   57663   assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
   57664   rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
   57665   if( rc ){
   57666     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
   57667   }
   57668   sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
   57669   UPDATE_MAX_BLOBSIZE(u.cc.pMem);
   57670   if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
   57671     goto too_big;
   57672   }
   57673   break;
   57674 }
   57675 
   57676 
   57677 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
   57678 /* Opcode: Vacuum * * * * *
   57679 **
   57680 ** Vacuum the entire database.  This opcode will cause other virtual
   57681 ** machines to be created and run.  It may not be called from within
   57682 ** a transaction.
   57683 */
   57684 case OP_Vacuum: {
   57685   rc = sqlite3RunVacuum(&p->zErrMsg, db);
   57686   break;
   57687 }
   57688 #endif
   57689 
   57690 #if !defined(SQLITE_OMIT_AUTOVACUUM)
   57691 /* Opcode: IncrVacuum P1 P2 * * *
   57692 **
   57693 ** Perform a single step of the incremental vacuum procedure on
   57694 ** the P1 database. If the vacuum has finished, jump to instruction
   57695 ** P2. Otherwise, fall through to the next instruction.
   57696 */
   57697 case OP_IncrVacuum: {        /* jump */
   57698 #if 0  /* local variables moved into u.cd */
   57699   Btree *pBt;
   57700 #endif /* local variables moved into u.cd */
   57701 
   57702   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   57703   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
   57704   u.cd.pBt = db->aDb[pOp->p1].pBt;
   57705   rc = sqlite3BtreeIncrVacuum(u.cd.pBt);
   57706   if( rc==SQLITE_DONE ){
   57707     pc = pOp->p2 - 1;
   57708     rc = SQLITE_OK;
   57709   }
   57710   break;
   57711 }
   57712 #endif
   57713 
   57714 /* Opcode: Expire P1 * * * *
   57715 **
   57716 ** Cause precompiled statements to become expired. An expired statement
   57717 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
   57718 ** (via sqlite3_step()).
   57719 **
   57720 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
   57721 ** then only the currently executing statement is affected.
   57722 */
   57723 case OP_Expire: {
   57724   if( !pOp->p1 ){
   57725     sqlite3ExpirePreparedStatements(db);
   57726   }else{
   57727     p->expired = 1;
   57728   }
   57729   break;
   57730 }
   57731 
   57732 #ifndef SQLITE_OMIT_SHARED_CACHE
   57733 /* Opcode: TableLock P1 P2 P3 P4 *
   57734 **
   57735 ** Obtain a lock on a particular table. This instruction is only used when
   57736 ** the shared-cache feature is enabled.
   57737 **
   57738 ** P1 is the index of the database in sqlite3.aDb[] of the database
   57739 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
   57740 ** a write lock if P3==1.
   57741 **
   57742 ** P2 contains the root-page of the table to lock.
   57743 **
   57744 ** P4 contains a pointer to the name of the table being locked. This is only
   57745 ** used to generate an error message if the lock cannot be obtained.
   57746 */
   57747 case OP_TableLock: {
   57748   u8 isWriteLock = (u8)pOp->p3;
   57749   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
   57750     int p1 = pOp->p1;
   57751     assert( p1>=0 && p1<db->nDb );
   57752     assert( (p->btreeMask & (1<<p1))!=0 );
   57753     assert( isWriteLock==0 || isWriteLock==1 );
   57754     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
   57755     if( (rc&0xFF)==SQLITE_LOCKED ){
   57756       const char *z = pOp->p4.z;
   57757       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
   57758     }
   57759   }
   57760   break;
   57761 }
   57762 #endif /* SQLITE_OMIT_SHARED_CACHE */
   57763 
   57764 #ifndef SQLITE_OMIT_VIRTUALTABLE
   57765 /* Opcode: VBegin * * * P4 *
   57766 **
   57767 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
   57768 ** xBegin method for that table.
   57769 **
   57770 ** Also, whether or not P4 is set, check that this is not being called from
   57771 ** within a callback to a virtual table xSync() method. If it is, the error
   57772 ** code will be set to SQLITE_LOCKED.
   57773 */
   57774 case OP_VBegin: {
   57775 #if 0  /* local variables moved into u.ce */
   57776   VTable *pVTab;
   57777 #endif /* local variables moved into u.ce */
   57778   u.ce.pVTab = pOp->p4.pVtab;
   57779   rc = sqlite3VtabBegin(db, u.ce.pVTab);
   57780   if( u.ce.pVTab ){
   57781     sqlite3DbFree(db, p->zErrMsg);
   57782     p->zErrMsg = u.ce.pVTab->pVtab->zErrMsg;
   57783     u.ce.pVTab->pVtab->zErrMsg = 0;
   57784   }
   57785   break;
   57786 }
   57787 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   57788 
   57789 #ifndef SQLITE_OMIT_VIRTUALTABLE
   57790 /* Opcode: VCreate P1 * * P4 *
   57791 **
   57792 ** P4 is the name of a virtual table in database P1. Call the xCreate method
   57793 ** for that table.
   57794 */
   57795 case OP_VCreate: {
   57796   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
   57797   break;
   57798 }
   57799 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   57800 
   57801 #ifndef SQLITE_OMIT_VIRTUALTABLE
   57802 /* Opcode: VDestroy P1 * * P4 *
   57803 **
   57804 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
   57805 ** of that table.
   57806 */
   57807 case OP_VDestroy: {
   57808   p->inVtabMethod = 2;
   57809   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
   57810   p->inVtabMethod = 0;
   57811   break;
   57812 }
   57813 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   57814 
   57815 #ifndef SQLITE_OMIT_VIRTUALTABLE
   57816 /* Opcode: VOpen P1 * * P4 *
   57817 **
   57818 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   57819 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
   57820 ** table and stores that cursor in P1.
   57821 */
   57822 case OP_VOpen: {
   57823 #if 0  /* local variables moved into u.cf */
   57824   VdbeCursor *pCur;
   57825   sqlite3_vtab_cursor *pVtabCursor;
   57826   sqlite3_vtab *pVtab;
   57827   sqlite3_module *pModule;
   57828 #endif /* local variables moved into u.cf */
   57829 
   57830   u.cf.pCur = 0;
   57831   u.cf.pVtabCursor = 0;
   57832   u.cf.pVtab = pOp->p4.pVtab->pVtab;
   57833   u.cf.pModule = (sqlite3_module *)u.cf.pVtab->pModule;
   57834   assert(u.cf.pVtab && u.cf.pModule);
   57835   rc = u.cf.pModule->xOpen(u.cf.pVtab, &u.cf.pVtabCursor);
   57836   sqlite3DbFree(db, p->zErrMsg);
   57837   p->zErrMsg = u.cf.pVtab->zErrMsg;
   57838   u.cf.pVtab->zErrMsg = 0;
   57839   if( SQLITE_OK==rc ){
   57840     /* Initialize sqlite3_vtab_cursor base class */
   57841     u.cf.pVtabCursor->pVtab = u.cf.pVtab;
   57842 
   57843     /* Initialise vdbe cursor object */
   57844     u.cf.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
   57845     if( u.cf.pCur ){
   57846       u.cf.pCur->pVtabCursor = u.cf.pVtabCursor;
   57847       u.cf.pCur->pModule = u.cf.pVtabCursor->pVtab->pModule;
   57848     }else{
   57849       db->mallocFailed = 1;
   57850       u.cf.pModule->xClose(u.cf.pVtabCursor);
   57851     }
   57852   }
   57853   break;
   57854 }
   57855 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   57856 
   57857 #ifndef SQLITE_OMIT_VIRTUALTABLE
   57858 /* Opcode: VFilter P1 P2 P3 P4 *
   57859 **
   57860 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
   57861 ** the filtered result set is empty.
   57862 **
   57863 ** P4 is either NULL or a string that was generated by the xBestIndex
   57864 ** method of the module.  The interpretation of the P4 string is left
   57865 ** to the module implementation.
   57866 **
   57867 ** This opcode invokes the xFilter method on the virtual table specified
   57868 ** by P1.  The integer query plan parameter to xFilter is stored in register
   57869 ** P3. Register P3+1 stores the argc parameter to be passed to the
   57870 ** xFilter method. Registers P3+2..P3+1+argc are the argc
   57871 ** additional parameters which are passed to
   57872 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
   57873 **
   57874 ** A jump is made to P2 if the result set after filtering would be empty.
   57875 */
   57876 case OP_VFilter: {   /* jump */
   57877 #if 0  /* local variables moved into u.cg */
   57878   int nArg;
   57879   int iQuery;
   57880   const sqlite3_module *pModule;
   57881   Mem *pQuery;
   57882   Mem *pArgc;
   57883   sqlite3_vtab_cursor *pVtabCursor;
   57884   sqlite3_vtab *pVtab;
   57885   VdbeCursor *pCur;
   57886   int res;
   57887   int i;
   57888   Mem **apArg;
   57889 #endif /* local variables moved into u.cg */
   57890 
   57891   u.cg.pQuery = &aMem[pOp->p3];
   57892   u.cg.pArgc = &u.cg.pQuery[1];
   57893   u.cg.pCur = p->apCsr[pOp->p1];
   57894   REGISTER_TRACE(pOp->p3, u.cg.pQuery);
   57895   assert( u.cg.pCur->pVtabCursor );
   57896   u.cg.pVtabCursor = u.cg.pCur->pVtabCursor;
   57897   u.cg.pVtab = u.cg.pVtabCursor->pVtab;
   57898   u.cg.pModule = u.cg.pVtab->pModule;
   57899 
   57900   /* Grab the index number and argc parameters */
   57901   assert( (u.cg.pQuery->flags&MEM_Int)!=0 && u.cg.pArgc->flags==MEM_Int );
   57902   u.cg.nArg = (int)u.cg.pArgc->u.i;
   57903   u.cg.iQuery = (int)u.cg.pQuery->u.i;
   57904 
   57905   /* Invoke the xFilter method */
   57906   {
   57907     u.cg.res = 0;
   57908     u.cg.apArg = p->apArg;
   57909     for(u.cg.i = 0; u.cg.i<u.cg.nArg; u.cg.i++){
   57910       u.cg.apArg[u.cg.i] = &u.cg.pArgc[u.cg.i+1];
   57911       sqlite3VdbeMemStoreType(u.cg.apArg[u.cg.i]);
   57912     }
   57913 
   57914     p->inVtabMethod = 1;
   57915     rc = u.cg.pModule->xFilter(u.cg.pVtabCursor, u.cg.iQuery, pOp->p4.z, u.cg.nArg, u.cg.apArg);
   57916     p->inVtabMethod = 0;
   57917     sqlite3DbFree(db, p->zErrMsg);
   57918     p->zErrMsg = u.cg.pVtab->zErrMsg;
   57919     u.cg.pVtab->zErrMsg = 0;
   57920     if( rc==SQLITE_OK ){
   57921       u.cg.res = u.cg.pModule->xEof(u.cg.pVtabCursor);
   57922     }
   57923 
   57924     if( u.cg.res ){
   57925       pc = pOp->p2 - 1;
   57926     }
   57927   }
   57928   u.cg.pCur->nullRow = 0;
   57929 
   57930   break;
   57931 }
   57932 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   57933 
   57934 #ifndef SQLITE_OMIT_VIRTUALTABLE
   57935 /* Opcode: VColumn P1 P2 P3 * *
   57936 **
   57937 ** Store the value of the P2-th column of
   57938 ** the row of the virtual-table that the
   57939 ** P1 cursor is pointing to into register P3.
   57940 */
   57941 case OP_VColumn: {
   57942 #if 0  /* local variables moved into u.ch */
   57943   sqlite3_vtab *pVtab;
   57944   const sqlite3_module *pModule;
   57945   Mem *pDest;
   57946   sqlite3_context sContext;
   57947 #endif /* local variables moved into u.ch */
   57948 
   57949   VdbeCursor *pCur = p->apCsr[pOp->p1];
   57950   assert( pCur->pVtabCursor );
   57951   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   57952   u.ch.pDest = &aMem[pOp->p3];
   57953   if( pCur->nullRow ){
   57954     sqlite3VdbeMemSetNull(u.ch.pDest);
   57955     break;
   57956   }
   57957   u.ch.pVtab = pCur->pVtabCursor->pVtab;
   57958   u.ch.pModule = u.ch.pVtab->pModule;
   57959   assert( u.ch.pModule->xColumn );
   57960   memset(&u.ch.sContext, 0, sizeof(u.ch.sContext));
   57961 
   57962   /* The output cell may already have a buffer allocated. Move
   57963   ** the current contents to u.ch.sContext.s so in case the user-function
   57964   ** can use the already allocated buffer instead of allocating a
   57965   ** new one.
   57966   */
   57967   sqlite3VdbeMemMove(&u.ch.sContext.s, u.ch.pDest);
   57968   MemSetTypeFlag(&u.ch.sContext.s, MEM_Null);
   57969 
   57970   rc = u.ch.pModule->xColumn(pCur->pVtabCursor, &u.ch.sContext, pOp->p2);
   57971   sqlite3DbFree(db, p->zErrMsg);
   57972   p->zErrMsg = u.ch.pVtab->zErrMsg;
   57973   u.ch.pVtab->zErrMsg = 0;
   57974   if( u.ch.sContext.isError ){
   57975     rc = u.ch.sContext.isError;
   57976   }
   57977 
   57978   /* Copy the result of the function to the P3 register. We
   57979   ** do this regardless of whether or not an error occurred to ensure any
   57980   ** dynamic allocation in u.ch.sContext.s (a Mem struct) is  released.
   57981   */
   57982   sqlite3VdbeChangeEncoding(&u.ch.sContext.s, encoding);
   57983   sqlite3VdbeMemMove(u.ch.pDest, &u.ch.sContext.s);
   57984   REGISTER_TRACE(pOp->p3, u.ch.pDest);
   57985   UPDATE_MAX_BLOBSIZE(u.ch.pDest);
   57986 
   57987   if( sqlite3VdbeMemTooBig(u.ch.pDest) ){
   57988     goto too_big;
   57989   }
   57990   break;
   57991 }
   57992 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   57993 
   57994 #ifndef SQLITE_OMIT_VIRTUALTABLE
   57995 /* Opcode: VNext P1 P2 * * *
   57996 **
   57997 ** Advance virtual table P1 to the next row in its result set and
   57998 ** jump to instruction P2.  Or, if the virtual table has reached
   57999 ** the end of its result set, then fall through to the next instruction.
   58000 */
   58001 case OP_VNext: {   /* jump */
   58002 #if 0  /* local variables moved into u.ci */
   58003   sqlite3_vtab *pVtab;
   58004   const sqlite3_module *pModule;
   58005   int res;
   58006   VdbeCursor *pCur;
   58007 #endif /* local variables moved into u.ci */
   58008 
   58009   u.ci.res = 0;
   58010   u.ci.pCur = p->apCsr[pOp->p1];
   58011   assert( u.ci.pCur->pVtabCursor );
   58012   if( u.ci.pCur->nullRow ){
   58013     break;
   58014   }
   58015   u.ci.pVtab = u.ci.pCur->pVtabCursor->pVtab;
   58016   u.ci.pModule = u.ci.pVtab->pModule;
   58017   assert( u.ci.pModule->xNext );
   58018 
   58019   /* Invoke the xNext() method of the module. There is no way for the
   58020   ** underlying implementation to return an error if one occurs during
   58021   ** xNext(). Instead, if an error occurs, true is returned (indicating that
   58022   ** data is available) and the error code returned when xColumn or
   58023   ** some other method is next invoked on the save virtual table cursor.
   58024   */
   58025   p->inVtabMethod = 1;
   58026   rc = u.ci.pModule->xNext(u.ci.pCur->pVtabCursor);
   58027   p->inVtabMethod = 0;
   58028   sqlite3DbFree(db, p->zErrMsg);
   58029   p->zErrMsg = u.ci.pVtab->zErrMsg;
   58030   u.ci.pVtab->zErrMsg = 0;
   58031   if( rc==SQLITE_OK ){
   58032     u.ci.res = u.ci.pModule->xEof(u.ci.pCur->pVtabCursor);
   58033   }
   58034 
   58035   if( !u.ci.res ){
   58036     /* If there is data, jump to P2 */
   58037     pc = pOp->p2 - 1;
   58038   }
   58039   break;
   58040 }
   58041 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   58042 
   58043 #ifndef SQLITE_OMIT_VIRTUALTABLE
   58044 /* Opcode: VRename P1 * * P4 *
   58045 **
   58046 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   58047 ** This opcode invokes the corresponding xRename method. The value
   58048 ** in register P1 is passed as the zName argument to the xRename method.
   58049 */
   58050 case OP_VRename: {
   58051 #if 0  /* local variables moved into u.cj */
   58052   sqlite3_vtab *pVtab;
   58053   Mem *pName;
   58054 #endif /* local variables moved into u.cj */
   58055 
   58056   u.cj.pVtab = pOp->p4.pVtab->pVtab;
   58057   u.cj.pName = &aMem[pOp->p1];
   58058   assert( u.cj.pVtab->pModule->xRename );
   58059   REGISTER_TRACE(pOp->p1, u.cj.pName);
   58060   assert( u.cj.pName->flags & MEM_Str );
   58061   rc = u.cj.pVtab->pModule->xRename(u.cj.pVtab, u.cj.pName->z);
   58062   sqlite3DbFree(db, p->zErrMsg);
   58063   p->zErrMsg = u.cj.pVtab->zErrMsg;
   58064   u.cj.pVtab->zErrMsg = 0;
   58065 
   58066   break;
   58067 }
   58068 #endif
   58069 
   58070 #ifndef SQLITE_OMIT_VIRTUALTABLE
   58071 /* Opcode: VUpdate P1 P2 P3 P4 *
   58072 **
   58073 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   58074 ** This opcode invokes the corresponding xUpdate method. P2 values
   58075 ** are contiguous memory cells starting at P3 to pass to the xUpdate
   58076 ** invocation. The value in register (P3+P2-1) corresponds to the
   58077 ** p2th element of the argv array passed to xUpdate.
   58078 **
   58079 ** The xUpdate method will do a DELETE or an INSERT or both.
   58080 ** The argv[0] element (which corresponds to memory cell P3)
   58081 ** is the rowid of a row to delete.  If argv[0] is NULL then no
   58082 ** deletion occurs.  The argv[1] element is the rowid of the new
   58083 ** row.  This can be NULL to have the virtual table select the new
   58084 ** rowid for itself.  The subsequent elements in the array are
   58085 ** the values of columns in the new row.
   58086 **
   58087 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
   58088 ** a row to delete.
   58089 **
   58090 ** P1 is a boolean flag. If it is set to true and the xUpdate call
   58091 ** is successful, then the value returned by sqlite3_last_insert_rowid()
   58092 ** is set to the value of the rowid for the row just inserted.
   58093 */
   58094 case OP_VUpdate: {
   58095 #if 0  /* local variables moved into u.ck */
   58096   sqlite3_vtab *pVtab;
   58097   sqlite3_module *pModule;
   58098   int nArg;
   58099   int i;
   58100   sqlite_int64 rowid;
   58101   Mem **apArg;
   58102   Mem *pX;
   58103 #endif /* local variables moved into u.ck */
   58104 
   58105   u.ck.pVtab = pOp->p4.pVtab->pVtab;
   58106   u.ck.pModule = (sqlite3_module *)u.ck.pVtab->pModule;
   58107   u.ck.nArg = pOp->p2;
   58108   assert( pOp->p4type==P4_VTAB );
   58109   if( ALWAYS(u.ck.pModule->xUpdate) ){
   58110     u.ck.apArg = p->apArg;
   58111     u.ck.pX = &aMem[pOp->p3];
   58112     for(u.ck.i=0; u.ck.i<u.ck.nArg; u.ck.i++){
   58113       sqlite3VdbeMemStoreType(u.ck.pX);
   58114       u.ck.apArg[u.ck.i] = u.ck.pX;
   58115       u.ck.pX++;
   58116     }
   58117     rc = u.ck.pModule->xUpdate(u.ck.pVtab, u.ck.nArg, u.ck.apArg, &u.ck.rowid);
   58118     sqlite3DbFree(db, p->zErrMsg);
   58119     p->zErrMsg = u.ck.pVtab->zErrMsg;
   58120     u.ck.pVtab->zErrMsg = 0;
   58121     if( rc==SQLITE_OK && pOp->p1 ){
   58122       assert( u.ck.nArg>1 && u.ck.apArg[0] && (u.ck.apArg[0]->flags&MEM_Null) );
   58123       db->lastRowid = u.ck.rowid;
   58124     }
   58125     p->nChange++;
   58126   }
   58127   break;
   58128 }
   58129 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   58130 
   58131 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
   58132 /* Opcode: Pagecount P1 P2 * * *
   58133 **
   58134 ** Write the current number of pages in database P1 to memory cell P2.
   58135 */
   58136 case OP_Pagecount: {            /* out2-prerelease */
   58137 #if 0  /* local variables moved into u.cl */
   58138   int p1;
   58139   int nPage;
   58140   Pager *pPager;
   58141 #endif /* local variables moved into u.cl */
   58142 
   58143   u.cl.p1 = pOp->p1;
   58144   u.cl.pPager = sqlite3BtreePager(db->aDb[u.cl.p1].pBt);
   58145   rc = sqlite3PagerPagecount(u.cl.pPager, &u.cl.nPage);
   58146   /* OP_Pagecount is always called from within a read transaction.  The
   58147   ** page count has already been successfully read and cached.  So the
   58148   ** sqlite3PagerPagecount() call above cannot fail. */
   58149   if( ALWAYS(rc==SQLITE_OK) ){
   58150     pOut->u.i = u.cl.nPage;
   58151   }
   58152   break;
   58153 }
   58154 #endif
   58155 
   58156 #ifndef SQLITE_OMIT_TRACE
   58157 /* Opcode: Trace * * * P4 *
   58158 **
   58159 ** If tracing is enabled (by the sqlite3_trace()) interface, then
   58160 ** the UTF-8 string contained in P4 is emitted on the trace callback.
   58161 */
   58162 case OP_Trace: {
   58163 #if 0  /* local variables moved into u.cm */
   58164   char *zTrace;
   58165 #endif /* local variables moved into u.cm */
   58166 
   58167   u.cm.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
   58168   if( u.cm.zTrace ){
   58169     if( db->xTrace ){
   58170       char *z = sqlite3VdbeExpandSql(p, u.cm.zTrace);
   58171       db->xTrace(db->pTraceArg, z);
   58172       sqlite3DbFree(db, z);
   58173     }
   58174 #ifdef SQLITE_DEBUG
   58175     if( (db->flags & SQLITE_SqlTrace)!=0 ){
   58176       sqlite3DebugPrintf("SQL-trace: %s\n", u.cm.zTrace);
   58177     }
   58178 #endif /* SQLITE_DEBUG */
   58179   }
   58180   break;
   58181 }
   58182 #endif
   58183 
   58184 
   58185 /* Opcode: Noop * * * * *
   58186 **
   58187 ** Do nothing.  This instruction is often useful as a jump
   58188 ** destination.
   58189 */
   58190 /*
   58191 ** The magic Explain opcode are only inserted when explain==2 (which
   58192 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
   58193 ** This opcode records information from the optimizer.  It is the
   58194 ** the same as a no-op.  This opcodesnever appears in a real VM program.
   58195 */
   58196 default: {          /* This is really OP_Noop and OP_Explain */
   58197   break;
   58198 }
   58199 
   58200 /*****************************************************************************
   58201 ** The cases of the switch statement above this line should all be indented
   58202 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
   58203 ** readability.  From this point on down, the normal indentation rules are
   58204 ** restored.
   58205 *****************************************************************************/
   58206     }
   58207 
   58208 #ifdef VDBE_PROFILE
   58209     {
   58210       u64 elapsed = sqlite3Hwtime() - start;
   58211       pOp->cycles += elapsed;
   58212       pOp->cnt++;
   58213 #if 0
   58214         fprintf(stdout, "%10llu ", elapsed);
   58215         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
   58216 #endif
   58217     }
   58218 #endif
   58219 
   58220     /* The following code adds nothing to the actual functionality
   58221     ** of the program.  It is only here for testing and debugging.
   58222     ** On the other hand, it does burn CPU cycles every time through
   58223     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
   58224     */
   58225 #ifndef NDEBUG
   58226     assert( pc>=-1 && pc<p->nOp );
   58227 
   58228 #ifdef SQLITE_DEBUG
   58229     if( p->trace ){
   58230       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
   58231       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
   58232         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
   58233       }
   58234       if( pOp->opflags & OPFLG_OUT3 ){
   58235         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
   58236       }
   58237     }
   58238 #endif  /* SQLITE_DEBUG */
   58239 #endif  /* NDEBUG */
   58240   }  /* The end of the for(;;) loop the loops through opcodes */
   58241 
   58242   /* If we reach this point, it means that execution is finished with
   58243   ** an error of some kind.
   58244   */
   58245 vdbe_error_halt:
   58246   assert( rc );
   58247   p->rc = rc;
   58248   sqlite3_log(rc, "prepared statement aborts at %d: [%s]", pc, p->zSql);
   58249   sqlite3VdbeHalt(p);
   58250   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
   58251   rc = SQLITE_ERROR;
   58252   if( resetSchemaOnFault ) sqlite3ResetInternalSchema(db, 0);
   58253 
   58254   /* This is the only way out of this procedure.  We have to
   58255   ** release the mutexes on btrees that were acquired at the
   58256   ** top. */
   58257 vdbe_return:
   58258   sqlite3BtreeMutexArrayLeave(&p->aMutex);
   58259   return rc;
   58260 
   58261   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
   58262   ** is encountered.
   58263   */
   58264 too_big:
   58265   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
   58266   rc = SQLITE_TOOBIG;
   58267   goto vdbe_error_halt;
   58268 
   58269   /* Jump to here if a malloc() fails.
   58270   */
   58271 no_mem:
   58272   db->mallocFailed = 1;
   58273   sqlite3SetString(&p->zErrMsg, db, "out of memory");
   58274   rc = SQLITE_NOMEM;
   58275   goto vdbe_error_halt;
   58276 
   58277   /* Jump to here for any other kind of fatal error.  The "rc" variable
   58278   ** should hold the error number.
   58279   */
   58280 abort_due_to_error:
   58281   assert( p->zErrMsg==0 );
   58282   if( db->mallocFailed ) rc = SQLITE_NOMEM;
   58283   if( rc!=SQLITE_IOERR_NOMEM ){
   58284     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
   58285   }
   58286   goto vdbe_error_halt;
   58287 
   58288   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
   58289   ** flag.
   58290   */
   58291 abort_due_to_interrupt:
   58292   assert( db->u1.isInterrupted );
   58293   rc = SQLITE_INTERRUPT;
   58294   p->rc = rc;
   58295   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
   58296   goto vdbe_error_halt;
   58297 }
   58298 
   58299 /************** End of vdbe.c ************************************************/
   58300 /************** Begin file vdbeblob.c ****************************************/
   58301 /*
   58302 ** 2007 May 1
   58303 **
   58304 ** The author disclaims copyright to this source code.  In place of
   58305 ** a legal notice, here is a blessing:
   58306 **
   58307 **    May you do good and not evil.
   58308 **    May you find forgiveness for yourself and forgive others.
   58309 **    May you share freely, never taking more than you give.
   58310 **
   58311 *************************************************************************
   58312 **
   58313 ** This file contains code used to implement incremental BLOB I/O.
   58314 */
   58315 
   58316 
   58317 #ifndef SQLITE_OMIT_INCRBLOB
   58318 
   58319 /*
   58320 ** Valid sqlite3_blob* handles point to Incrblob structures.
   58321 */
   58322 typedef struct Incrblob Incrblob;
   58323 struct Incrblob {
   58324   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
   58325   int nByte;              /* Size of open blob, in bytes */
   58326   int iOffset;            /* Byte offset of blob in cursor data */
   58327   BtCursor *pCsr;         /* Cursor pointing at blob row */
   58328   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
   58329   sqlite3 *db;            /* The associated database */
   58330 };
   58331 
   58332 /*
   58333 ** Open a blob handle.
   58334 */
   58335 SQLITE_API int sqlite3_blob_open(
   58336   sqlite3* db,            /* The database connection */
   58337   const char *zDb,        /* The attached database containing the blob */
   58338   const char *zTable,     /* The table containing the blob */
   58339   const char *zColumn,    /* The column containing the blob */
   58340   sqlite_int64 iRow,      /* The row containing the glob */
   58341   int flags,              /* True -> read/write access, false -> read-only */
   58342   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
   58343 ){
   58344   int nAttempt = 0;
   58345   int iCol;               /* Index of zColumn in row-record */
   58346 
   58347   /* This VDBE program seeks a btree cursor to the identified
   58348   ** db/table/row entry. The reason for using a vdbe program instead
   58349   ** of writing code to use the b-tree layer directly is that the
   58350   ** vdbe program will take advantage of the various transaction,
   58351   ** locking and error handling infrastructure built into the vdbe.
   58352   **
   58353   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
   58354   ** Code external to the Vdbe then "borrows" the b-tree cursor and
   58355   ** uses it to implement the blob_read(), blob_write() and
   58356   ** blob_bytes() functions.
   58357   **
   58358   ** The sqlite3_blob_close() function finalizes the vdbe program,
   58359   ** which closes the b-tree cursor and (possibly) commits the
   58360   ** transaction.
   58361   */
   58362   static const VdbeOpList openBlob[] = {
   58363     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
   58364     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
   58365     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
   58366 
   58367     /* One of the following two instructions is replaced by an OP_Noop. */
   58368     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
   58369     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
   58370 
   58371     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
   58372     {OP_NotExists, 0, 9, 1},       /* 6: Seek the cursor */
   58373     {OP_Column, 0, 0, 1},          /* 7  */
   58374     {OP_ResultRow, 1, 0, 0},       /* 8  */
   58375     {OP_Close, 0, 0, 0},           /* 9  */
   58376     {OP_Halt, 0, 0, 0},            /* 10 */
   58377   };
   58378 
   58379   Vdbe *v = 0;
   58380   int rc = SQLITE_OK;
   58381   char *zErr = 0;
   58382   Table *pTab;
   58383   Parse *pParse;
   58384 
   58385   *ppBlob = 0;
   58386   sqlite3_mutex_enter(db->mutex);
   58387   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
   58388   if( pParse==0 ){
   58389     rc = SQLITE_NOMEM;
   58390     goto blob_open_out;
   58391   }
   58392   do {
   58393     memset(pParse, 0, sizeof(Parse));
   58394     pParse->db = db;
   58395 
   58396     sqlite3BtreeEnterAll(db);
   58397     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
   58398     if( pTab && IsVirtual(pTab) ){
   58399       pTab = 0;
   58400       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
   58401     }
   58402 #ifndef SQLITE_OMIT_VIEW
   58403     if( pTab && pTab->pSelect ){
   58404       pTab = 0;
   58405       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
   58406     }
   58407 #endif
   58408     if( !pTab ){
   58409       if( pParse->zErrMsg ){
   58410         sqlite3DbFree(db, zErr);
   58411         zErr = pParse->zErrMsg;
   58412         pParse->zErrMsg = 0;
   58413       }
   58414       rc = SQLITE_ERROR;
   58415       sqlite3BtreeLeaveAll(db);
   58416       goto blob_open_out;
   58417     }
   58418 
   58419     /* Now search pTab for the exact column. */
   58420     for(iCol=0; iCol < pTab->nCol; iCol++) {
   58421       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
   58422         break;
   58423       }
   58424     }
   58425     if( iCol==pTab->nCol ){
   58426       sqlite3DbFree(db, zErr);
   58427       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
   58428       rc = SQLITE_ERROR;
   58429       sqlite3BtreeLeaveAll(db);
   58430       goto blob_open_out;
   58431     }
   58432 
   58433     /* If the value is being opened for writing, check that the
   58434     ** column is not indexed, and that it is not part of a foreign key.
   58435     ** It is against the rules to open a column to which either of these
   58436     ** descriptions applies for writing.  */
   58437     if( flags ){
   58438       const char *zFault = 0;
   58439       Index *pIdx;
   58440 #ifndef SQLITE_OMIT_FOREIGN_KEY
   58441       if( db->flags&SQLITE_ForeignKeys ){
   58442         /* Check that the column is not part of an FK child key definition. It
   58443         ** is not necessary to check if it is part of a parent key, as parent
   58444         ** key columns must be indexed. The check below will pick up this
   58445         ** case.  */
   58446         FKey *pFKey;
   58447         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
   58448           int j;
   58449           for(j=0; j<pFKey->nCol; j++){
   58450             if( pFKey->aCol[j].iFrom==iCol ){
   58451               zFault = "foreign key";
   58452             }
   58453           }
   58454         }
   58455       }
   58456 #endif
   58457       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   58458         int j;
   58459         for(j=0; j<pIdx->nColumn; j++){
   58460           if( pIdx->aiColumn[j]==iCol ){
   58461             zFault = "indexed";
   58462           }
   58463         }
   58464       }
   58465       if( zFault ){
   58466         sqlite3DbFree(db, zErr);
   58467         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
   58468         rc = SQLITE_ERROR;
   58469         sqlite3BtreeLeaveAll(db);
   58470         goto blob_open_out;
   58471       }
   58472     }
   58473 
   58474     v = sqlite3VdbeCreate(db);
   58475     if( v ){
   58476       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   58477       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
   58478       flags = !!flags;                 /* flags = (flags ? 1 : 0); */
   58479 
   58480       /* Configure the OP_Transaction */
   58481       sqlite3VdbeChangeP1(v, 0, iDb);
   58482       sqlite3VdbeChangeP2(v, 0, flags);
   58483 
   58484       /* Configure the OP_VerifyCookie */
   58485       sqlite3VdbeChangeP1(v, 1, iDb);
   58486       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
   58487 
   58488       /* Make sure a mutex is held on the table to be accessed */
   58489       sqlite3VdbeUsesBtree(v, iDb);
   58490 
   58491       /* Configure the OP_TableLock instruction */
   58492       sqlite3VdbeChangeP1(v, 2, iDb);
   58493       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
   58494       sqlite3VdbeChangeP3(v, 2, flags);
   58495       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
   58496 
   58497       /* Remove either the OP_OpenWrite or OpenRead. Set the P2
   58498       ** parameter of the other to pTab->tnum.  */
   58499       sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
   58500       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
   58501       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
   58502 
   58503       /* Configure the number of columns. Configure the cursor to
   58504       ** think that the table has one more column than it really
   58505       ** does. An OP_Column to retrieve this imaginary column will
   58506       ** always return an SQL NULL. This is useful because it means
   58507       ** we can invoke OP_Column to fill in the vdbe cursors type
   58508       ** and offset cache without causing any IO.
   58509       */
   58510       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
   58511       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
   58512       if( !db->mallocFailed ){
   58513         sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
   58514       }
   58515     }
   58516 
   58517     sqlite3BtreeLeaveAll(db);
   58518     if( db->mallocFailed ){
   58519       goto blob_open_out;
   58520     }
   58521 
   58522     sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
   58523     rc = sqlite3_step((sqlite3_stmt *)v);
   58524     if( rc!=SQLITE_ROW ){
   58525       nAttempt++;
   58526       rc = sqlite3_finalize((sqlite3_stmt *)v);
   58527       sqlite3DbFree(db, zErr);
   58528       zErr = sqlite3MPrintf(db, sqlite3_errmsg(db));
   58529       v = 0;
   58530     }
   58531   } while( nAttempt<5 && rc==SQLITE_SCHEMA );
   58532 
   58533   if( rc==SQLITE_ROW ){
   58534     /* The row-record has been opened successfully. Check that the
   58535     ** column in question contains text or a blob. If it contains
   58536     ** text, it is up to the caller to get the encoding right.
   58537     */
   58538     Incrblob *pBlob;
   58539     u32 type = v->apCsr[0]->aType[iCol];
   58540 
   58541     if( type<12 ){
   58542       sqlite3DbFree(db, zErr);
   58543       zErr = sqlite3MPrintf(db, "cannot open value of type %s",
   58544           type==0?"null": type==7?"real": "integer"
   58545       );
   58546       rc = SQLITE_ERROR;
   58547       goto blob_open_out;
   58548     }
   58549     pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
   58550     if( db->mallocFailed ){
   58551       sqlite3DbFree(db, pBlob);
   58552       goto blob_open_out;
   58553     }
   58554     pBlob->flags = flags;
   58555     pBlob->pCsr =  v->apCsr[0]->pCursor;
   58556     sqlite3BtreeEnterCursor(pBlob->pCsr);
   58557     sqlite3BtreeCacheOverflow(pBlob->pCsr);
   58558     sqlite3BtreeLeaveCursor(pBlob->pCsr);
   58559     pBlob->pStmt = (sqlite3_stmt *)v;
   58560     pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
   58561     pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
   58562     pBlob->db = db;
   58563     *ppBlob = (sqlite3_blob *)pBlob;
   58564     rc = SQLITE_OK;
   58565   }else if( rc==SQLITE_OK ){
   58566     sqlite3DbFree(db, zErr);
   58567     zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow);
   58568     rc = SQLITE_ERROR;
   58569   }
   58570 
   58571 blob_open_out:
   58572   if( v && (rc!=SQLITE_OK || db->mallocFailed) ){
   58573     sqlite3VdbeFinalize(v);
   58574   }
   58575   sqlite3Error(db, rc, zErr);
   58576   sqlite3DbFree(db, zErr);
   58577   sqlite3StackFree(db, pParse);
   58578   rc = sqlite3ApiExit(db, rc);
   58579   sqlite3_mutex_leave(db->mutex);
   58580   return rc;
   58581 }
   58582 
   58583 /*
   58584 ** Close a blob handle that was previously created using
   58585 ** sqlite3_blob_open().
   58586 */
   58587 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
   58588   Incrblob *p = (Incrblob *)pBlob;
   58589   int rc;
   58590   sqlite3 *db;
   58591 
   58592   if( p ){
   58593     db = p->db;
   58594     sqlite3_mutex_enter(db->mutex);
   58595     rc = sqlite3_finalize(p->pStmt);
   58596     sqlite3DbFree(db, p);
   58597     sqlite3_mutex_leave(db->mutex);
   58598   }else{
   58599     rc = SQLITE_OK;
   58600   }
   58601   return rc;
   58602 }
   58603 
   58604 /*
   58605 ** Perform a read or write operation on a blob
   58606 */
   58607 static int blobReadWrite(
   58608   sqlite3_blob *pBlob,
   58609   void *z,
   58610   int n,
   58611   int iOffset,
   58612   int (*xCall)(BtCursor*, u32, u32, void*)
   58613 ){
   58614   int rc;
   58615   Incrblob *p = (Incrblob *)pBlob;
   58616   Vdbe *v;
   58617   sqlite3 *db;
   58618 
   58619   if( p==0 ) return SQLITE_MISUSE_BKPT;
   58620   db = p->db;
   58621   sqlite3_mutex_enter(db->mutex);
   58622   v = (Vdbe*)p->pStmt;
   58623 
   58624   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
   58625     /* Request is out of range. Return a transient error. */
   58626     rc = SQLITE_ERROR;
   58627     sqlite3Error(db, SQLITE_ERROR, 0);
   58628   } else if( v==0 ){
   58629     /* If there is no statement handle, then the blob-handle has
   58630     ** already been invalidated. Return SQLITE_ABORT in this case.
   58631     */
   58632     rc = SQLITE_ABORT;
   58633   }else{
   58634     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
   58635     ** returned, clean-up the statement handle.
   58636     */
   58637     assert( db == v->db );
   58638     sqlite3BtreeEnterCursor(p->pCsr);
   58639     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
   58640     sqlite3BtreeLeaveCursor(p->pCsr);
   58641     if( rc==SQLITE_ABORT ){
   58642       sqlite3VdbeFinalize(v);
   58643       p->pStmt = 0;
   58644     }else{
   58645       db->errCode = rc;
   58646       v->rc = rc;
   58647     }
   58648   }
   58649   rc = sqlite3ApiExit(db, rc);
   58650   sqlite3_mutex_leave(db->mutex);
   58651   return rc;
   58652 }
   58653 
   58654 /*
   58655 ** Read data from a blob handle.
   58656 */
   58657 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
   58658   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
   58659 }
   58660 
   58661 /*
   58662 ** Write data to a blob handle.
   58663 */
   58664 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
   58665   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
   58666 }
   58667 
   58668 /*
   58669 ** Query a blob handle for the size of the data.
   58670 **
   58671 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
   58672 ** so no mutex is required for access.
   58673 */
   58674 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
   58675   Incrblob *p = (Incrblob *)pBlob;
   58676   return p ? p->nByte : 0;
   58677 }
   58678 
   58679 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
   58680 
   58681 /************** End of vdbeblob.c ********************************************/
   58682 /************** Begin file journal.c *****************************************/
   58683 /*
   58684 ** 2007 August 22
   58685 **
   58686 ** The author disclaims copyright to this source code.  In place of
   58687 ** a legal notice, here is a blessing:
   58688 **
   58689 **    May you do good and not evil.
   58690 **    May you find forgiveness for yourself and forgive others.
   58691 **    May you share freely, never taking more than you give.
   58692 **
   58693 *************************************************************************
   58694 **
   58695 ** This file implements a special kind of sqlite3_file object used
   58696 ** by SQLite to create journal files if the atomic-write optimization
   58697 ** is enabled.
   58698 **
   58699 ** The distinctive characteristic of this sqlite3_file is that the
   58700 ** actual on disk file is created lazily. When the file is created,
   58701 ** the caller specifies a buffer size for an in-memory buffer to
   58702 ** be used to service read() and write() requests. The actual file
   58703 ** on disk is not created or populated until either:
   58704 **
   58705 **   1) The in-memory representation grows too large for the allocated
   58706 **      buffer, or
   58707 **   2) The sqlite3JournalCreate() function is called.
   58708 */
   58709 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   58710 
   58711 
   58712 /*
   58713 ** A JournalFile object is a subclass of sqlite3_file used by
   58714 ** as an open file handle for journal files.
   58715 */
   58716 struct JournalFile {
   58717   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
   58718   int nBuf;                       /* Size of zBuf[] in bytes */
   58719   char *zBuf;                     /* Space to buffer journal writes */
   58720   int iSize;                      /* Amount of zBuf[] currently used */
   58721   int flags;                      /* xOpen flags */
   58722   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
   58723   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
   58724   const char *zJournal;           /* Name of the journal file */
   58725 };
   58726 typedef struct JournalFile JournalFile;
   58727 
   58728 /*
   58729 ** If it does not already exists, create and populate the on-disk file
   58730 ** for JournalFile p.
   58731 */
   58732 static int createFile(JournalFile *p){
   58733   int rc = SQLITE_OK;
   58734   if( !p->pReal ){
   58735     sqlite3_file *pReal = (sqlite3_file *)&p[1];
   58736     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
   58737     if( rc==SQLITE_OK ){
   58738       p->pReal = pReal;
   58739       if( p->iSize>0 ){
   58740         assert(p->iSize<=p->nBuf);
   58741         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
   58742       }
   58743     }
   58744   }
   58745   return rc;
   58746 }
   58747 
   58748 /*
   58749 ** Close the file.
   58750 */
   58751 static int jrnlClose(sqlite3_file *pJfd){
   58752   JournalFile *p = (JournalFile *)pJfd;
   58753   if( p->pReal ){
   58754     sqlite3OsClose(p->pReal);
   58755   }
   58756   sqlite3_free(p->zBuf);
   58757   return SQLITE_OK;
   58758 }
   58759 
   58760 /*
   58761 ** Read data from the file.
   58762 */
   58763 static int jrnlRead(
   58764   sqlite3_file *pJfd,    /* The journal file from which to read */
   58765   void *zBuf,            /* Put the results here */
   58766   int iAmt,              /* Number of bytes to read */
   58767   sqlite_int64 iOfst     /* Begin reading at this offset */
   58768 ){
   58769   int rc = SQLITE_OK;
   58770   JournalFile *p = (JournalFile *)pJfd;
   58771   if( p->pReal ){
   58772     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
   58773   }else if( (iAmt+iOfst)>p->iSize ){
   58774     rc = SQLITE_IOERR_SHORT_READ;
   58775   }else{
   58776     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
   58777   }
   58778   return rc;
   58779 }
   58780 
   58781 /*
   58782 ** Write data to the file.
   58783 */
   58784 static int jrnlWrite(
   58785   sqlite3_file *pJfd,    /* The journal file into which to write */
   58786   const void *zBuf,      /* Take data to be written from here */
   58787   int iAmt,              /* Number of bytes to write */
   58788   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
   58789 ){
   58790   int rc = SQLITE_OK;
   58791   JournalFile *p = (JournalFile *)pJfd;
   58792   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
   58793     rc = createFile(p);
   58794   }
   58795   if( rc==SQLITE_OK ){
   58796     if( p->pReal ){
   58797       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
   58798     }else{
   58799       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
   58800       if( p->iSize<(iOfst+iAmt) ){
   58801         p->iSize = (iOfst+iAmt);
   58802       }
   58803     }
   58804   }
   58805   return rc;
   58806 }
   58807 
   58808 /*
   58809 ** Truncate the file.
   58810 */
   58811 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
   58812   int rc = SQLITE_OK;
   58813   JournalFile *p = (JournalFile *)pJfd;
   58814   if( p->pReal ){
   58815     rc = sqlite3OsTruncate(p->pReal, size);
   58816   }else if( size<p->iSize ){
   58817     p->iSize = size;
   58818   }
   58819   return rc;
   58820 }
   58821 
   58822 /*
   58823 ** Sync the file.
   58824 */
   58825 static int jrnlSync(sqlite3_file *pJfd, int flags){
   58826   int rc;
   58827   JournalFile *p = (JournalFile *)pJfd;
   58828   if( p->pReal ){
   58829     rc = sqlite3OsSync(p->pReal, flags);
   58830   }else{
   58831     rc = SQLITE_OK;
   58832   }
   58833   return rc;
   58834 }
   58835 
   58836 /*
   58837 ** Query the size of the file in bytes.
   58838 */
   58839 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
   58840   int rc = SQLITE_OK;
   58841   JournalFile *p = (JournalFile *)pJfd;
   58842   if( p->pReal ){
   58843     rc = sqlite3OsFileSize(p->pReal, pSize);
   58844   }else{
   58845     *pSize = (sqlite_int64) p->iSize;
   58846   }
   58847   return rc;
   58848 }
   58849 
   58850 /*
   58851 ** Table of methods for JournalFile sqlite3_file object.
   58852 */
   58853 static struct sqlite3_io_methods JournalFileMethods = {
   58854   1,             /* iVersion */
   58855   jrnlClose,     /* xClose */
   58856   jrnlRead,      /* xRead */
   58857   jrnlWrite,     /* xWrite */
   58858   jrnlTruncate,  /* xTruncate */
   58859   jrnlSync,      /* xSync */
   58860   jrnlFileSize,  /* xFileSize */
   58861   0,             /* xLock */
   58862   0,             /* xUnlock */
   58863   0,             /* xCheckReservedLock */
   58864   0,             /* xFileControl */
   58865   0,             /* xSectorSize */
   58866   0              /* xDeviceCharacteristics */
   58867 };
   58868 
   58869 /*
   58870 ** Open a journal file.
   58871 */
   58872 SQLITE_PRIVATE int sqlite3JournalOpen(
   58873   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
   58874   const char *zName,         /* Name of the journal file */
   58875   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
   58876   int flags,                 /* Opening flags */
   58877   int nBuf                   /* Bytes buffered before opening the file */
   58878 ){
   58879   JournalFile *p = (JournalFile *)pJfd;
   58880   memset(p, 0, sqlite3JournalSize(pVfs));
   58881   if( nBuf>0 ){
   58882     p->zBuf = sqlite3MallocZero(nBuf);
   58883     if( !p->zBuf ){
   58884       return SQLITE_NOMEM;
   58885     }
   58886   }else{
   58887     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
   58888   }
   58889   p->pMethod = &JournalFileMethods;
   58890   p->nBuf = nBuf;
   58891   p->flags = flags;
   58892   p->zJournal = zName;
   58893   p->pVfs = pVfs;
   58894   return SQLITE_OK;
   58895 }
   58896 
   58897 /*
   58898 ** If the argument p points to a JournalFile structure, and the underlying
   58899 ** file has not yet been created, create it now.
   58900 */
   58901 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
   58902   if( p->pMethods!=&JournalFileMethods ){
   58903     return SQLITE_OK;
   58904   }
   58905   return createFile((JournalFile *)p);
   58906 }
   58907 
   58908 /*
   58909 ** Return the number of bytes required to store a JournalFile that uses vfs
   58910 ** pVfs to create the underlying on-disk files.
   58911 */
   58912 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
   58913   return (pVfs->szOsFile+sizeof(JournalFile));
   58914 }
   58915 #endif
   58916 
   58917 /************** End of journal.c *********************************************/
   58918 /************** Begin file memjournal.c **************************************/
   58919 /*
   58920 ** 2008 October 7
   58921 **
   58922 ** The author disclaims copyright to this source code.  In place of
   58923 ** a legal notice, here is a blessing:
   58924 **
   58925 **    May you do good and not evil.
   58926 **    May you find forgiveness for yourself and forgive others.
   58927 **    May you share freely, never taking more than you give.
   58928 **
   58929 *************************************************************************
   58930 **
   58931 ** This file contains code use to implement an in-memory rollback journal.
   58932 ** The in-memory rollback journal is used to journal transactions for
   58933 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
   58934 */
   58935 
   58936 /* Forward references to internal structures */
   58937 typedef struct MemJournal MemJournal;
   58938 typedef struct FilePoint FilePoint;
   58939 typedef struct FileChunk FileChunk;
   58940 
   58941 /* Space to hold the rollback journal is allocated in increments of
   58942 ** this many bytes.
   58943 **
   58944 ** The size chosen is a little less than a power of two.  That way,
   58945 ** the FileChunk object will have a size that almost exactly fills
   58946 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
   58947 ** memory allocators.
   58948 */
   58949 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
   58950 
   58951 /* Macro to find the minimum of two numeric values.
   58952 */
   58953 #ifndef MIN
   58954 # define MIN(x,y) ((x)<(y)?(x):(y))
   58955 #endif
   58956 
   58957 /*
   58958 ** The rollback journal is composed of a linked list of these structures.
   58959 */
   58960 struct FileChunk {
   58961   FileChunk *pNext;               /* Next chunk in the journal */
   58962   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
   58963 };
   58964 
   58965 /*
   58966 ** An instance of this object serves as a cursor into the rollback journal.
   58967 ** The cursor can be either for reading or writing.
   58968 */
   58969 struct FilePoint {
   58970   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
   58971   FileChunk *pChunk;              /* Specific chunk into which cursor points */
   58972 };
   58973 
   58974 /*
   58975 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
   58976 ** is an instance of this class.
   58977 */
   58978 struct MemJournal {
   58979   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
   58980   FileChunk *pFirst;              /* Head of in-memory chunk-list */
   58981   FilePoint endpoint;             /* Pointer to the end of the file */
   58982   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
   58983 };
   58984 
   58985 /*
   58986 ** Read data from the in-memory journal file.  This is the implementation
   58987 ** of the sqlite3_vfs.xRead method.
   58988 */
   58989 static int memjrnlRead(
   58990   sqlite3_file *pJfd,    /* The journal file from which to read */
   58991   void *zBuf,            /* Put the results here */
   58992   int iAmt,              /* Number of bytes to read */
   58993   sqlite_int64 iOfst     /* Begin reading at this offset */
   58994 ){
   58995   MemJournal *p = (MemJournal *)pJfd;
   58996   u8 *zOut = zBuf;
   58997   int nRead = iAmt;
   58998   int iChunkOffset;
   58999   FileChunk *pChunk;
   59000 
   59001   /* SQLite never tries to read past the end of a rollback journal file */
   59002   assert( iOfst+iAmt<=p->endpoint.iOffset );
   59003 
   59004   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
   59005     sqlite3_int64 iOff = 0;
   59006     for(pChunk=p->pFirst;
   59007         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
   59008         pChunk=pChunk->pNext
   59009     ){
   59010       iOff += JOURNAL_CHUNKSIZE;
   59011     }
   59012   }else{
   59013     pChunk = p->readpoint.pChunk;
   59014   }
   59015 
   59016   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
   59017   do {
   59018     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
   59019     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
   59020     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
   59021     zOut += nCopy;
   59022     nRead -= iSpace;
   59023     iChunkOffset = 0;
   59024   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
   59025   p->readpoint.iOffset = iOfst+iAmt;
   59026   p->readpoint.pChunk = pChunk;
   59027 
   59028   return SQLITE_OK;
   59029 }
   59030 
   59031 /*
   59032 ** Write data to the file.
   59033 */
   59034 static int memjrnlWrite(
   59035   sqlite3_file *pJfd,    /* The journal file into which to write */
   59036   const void *zBuf,      /* Take data to be written from here */
   59037   int iAmt,              /* Number of bytes to write */
   59038   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
   59039 ){
   59040   MemJournal *p = (MemJournal *)pJfd;
   59041   int nWrite = iAmt;
   59042   u8 *zWrite = (u8 *)zBuf;
   59043 
   59044   /* An in-memory journal file should only ever be appended to. Random
   59045   ** access writes are not required by sqlite.
   59046   */
   59047   assert( iOfst==p->endpoint.iOffset );
   59048   UNUSED_PARAMETER(iOfst);
   59049 
   59050   while( nWrite>0 ){
   59051     FileChunk *pChunk = p->endpoint.pChunk;
   59052     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
   59053     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
   59054 
   59055     if( iChunkOffset==0 ){
   59056       /* New chunk is required to extend the file. */
   59057       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
   59058       if( !pNew ){
   59059         return SQLITE_IOERR_NOMEM;
   59060       }
   59061       pNew->pNext = 0;
   59062       if( pChunk ){
   59063         assert( p->pFirst );
   59064         pChunk->pNext = pNew;
   59065       }else{
   59066         assert( !p->pFirst );
   59067         p->pFirst = pNew;
   59068       }
   59069       p->endpoint.pChunk = pNew;
   59070     }
   59071 
   59072     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
   59073     zWrite += iSpace;
   59074     nWrite -= iSpace;
   59075     p->endpoint.iOffset += iSpace;
   59076   }
   59077 
   59078   return SQLITE_OK;
   59079 }
   59080 
   59081 /*
   59082 ** Truncate the file.
   59083 */
   59084 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
   59085   MemJournal *p = (MemJournal *)pJfd;
   59086   FileChunk *pChunk;
   59087   assert(size==0);
   59088   UNUSED_PARAMETER(size);
   59089   pChunk = p->pFirst;
   59090   while( pChunk ){
   59091     FileChunk *pTmp = pChunk;
   59092     pChunk = pChunk->pNext;
   59093     sqlite3_free(pTmp);
   59094   }
   59095   sqlite3MemJournalOpen(pJfd);
   59096   return SQLITE_OK;
   59097 }
   59098 
   59099 /*
   59100 ** Close the file.
   59101 */
   59102 static int memjrnlClose(sqlite3_file *pJfd){
   59103   memjrnlTruncate(pJfd, 0);
   59104   return SQLITE_OK;
   59105 }
   59106 
   59107 
   59108 /*
   59109 ** Sync the file.
   59110 **
   59111 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
   59112 ** is never called in a working implementation.  This implementation
   59113 ** exists purely as a contingency, in case some malfunction in some other
   59114 ** part of SQLite causes Sync to be called by mistake.
   59115 */
   59116 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){   /*NO_TEST*/
   59117   UNUSED_PARAMETER2(NotUsed, NotUsed2);                        /*NO_TEST*/
   59118   assert( 0 );                                                 /*NO_TEST*/
   59119   return SQLITE_OK;                                            /*NO_TEST*/
   59120 }                                                              /*NO_TEST*/
   59121 
   59122 /*
   59123 ** Query the size of the file in bytes.
   59124 */
   59125 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
   59126   MemJournal *p = (MemJournal *)pJfd;
   59127   *pSize = (sqlite_int64) p->endpoint.iOffset;
   59128   return SQLITE_OK;
   59129 }
   59130 
   59131 /*
   59132 ** Table of methods for MemJournal sqlite3_file object.
   59133 */
   59134 static struct sqlite3_io_methods MemJournalMethods = {
   59135   1,                /* iVersion */
   59136   memjrnlClose,     /* xClose */
   59137   memjrnlRead,      /* xRead */
   59138   memjrnlWrite,     /* xWrite */
   59139   memjrnlTruncate,  /* xTruncate */
   59140   memjrnlSync,      /* xSync */
   59141   memjrnlFileSize,  /* xFileSize */
   59142   0,                /* xLock */
   59143   0,                /* xUnlock */
   59144   0,                /* xCheckReservedLock */
   59145   0,                /* xFileControl */
   59146   0,                /* xSectorSize */
   59147   0                 /* xDeviceCharacteristics */
   59148 };
   59149 
   59150 /*
   59151 ** Open a journal file.
   59152 */
   59153 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
   59154   MemJournal *p = (MemJournal *)pJfd;
   59155   assert( EIGHT_BYTE_ALIGNMENT(p) );
   59156   memset(p, 0, sqlite3MemJournalSize());
   59157   p->pMethod = &MemJournalMethods;
   59158 }
   59159 
   59160 /*
   59161 ** Return true if the file-handle passed as an argument is
   59162 ** an in-memory journal
   59163 */
   59164 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
   59165   return pJfd->pMethods==&MemJournalMethods;
   59166 }
   59167 
   59168 /*
   59169 ** Return the number of bytes required to store a MemJournal that uses vfs
   59170 ** pVfs to create the underlying on-disk files.
   59171 */
   59172 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
   59173   return sizeof(MemJournal);
   59174 }
   59175 
   59176 /************** End of memjournal.c ******************************************/
   59177 /************** Begin file walker.c ******************************************/
   59178 /*
   59179 ** 2008 August 16
   59180 **
   59181 ** The author disclaims copyright to this source code.  In place of
   59182 ** a legal notice, here is a blessing:
   59183 **
   59184 **    May you do good and not evil.
   59185 **    May you find forgiveness for yourself and forgive others.
   59186 **    May you share freely, never taking more than you give.
   59187 **
   59188 *************************************************************************
   59189 ** This file contains routines used for walking the parser tree for
   59190 ** an SQL statement.
   59191 */
   59192 
   59193 
   59194 /*
   59195 ** Walk an expression tree.  Invoke the callback once for each node
   59196 ** of the expression, while decending.  (In other words, the callback
   59197 ** is invoked before visiting children.)
   59198 **
   59199 ** The return value from the callback should be one of the WRC_*
   59200 ** constants to specify how to proceed with the walk.
   59201 **
   59202 **    WRC_Continue      Continue descending down the tree.
   59203 **
   59204 **    WRC_Prune         Do not descend into child nodes.  But allow
   59205 **                      the walk to continue with sibling nodes.
   59206 **
   59207 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
   59208 **                      return the top-level walk call.
   59209 **
   59210 ** The return value from this routine is WRC_Abort to abandon the tree walk
   59211 ** and WRC_Continue to continue.
   59212 */
   59213 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
   59214   int rc;
   59215   if( pExpr==0 ) return WRC_Continue;
   59216   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
   59217   testcase( ExprHasProperty(pExpr, EP_Reduced) );
   59218   rc = pWalker->xExprCallback(pWalker, pExpr);
   59219   if( rc==WRC_Continue
   59220               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
   59221     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
   59222     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
   59223     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   59224       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
   59225     }else{
   59226       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
   59227     }
   59228   }
   59229   return rc & WRC_Abort;
   59230 }
   59231 
   59232 /*
   59233 ** Call sqlite3WalkExpr() for every expression in list p or until
   59234 ** an abort request is seen.
   59235 */
   59236 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
   59237   int i;
   59238   struct ExprList_item *pItem;
   59239   if( p ){
   59240     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
   59241       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
   59242     }
   59243   }
   59244   return WRC_Continue;
   59245 }
   59246 
   59247 /*
   59248 ** Walk all expressions associated with SELECT statement p.  Do
   59249 ** not invoke the SELECT callback on p, but do (of course) invoke
   59250 ** any expr callbacks and SELECT callbacks that come from subqueries.
   59251 ** Return WRC_Abort or WRC_Continue.
   59252 */
   59253 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
   59254   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
   59255   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
   59256   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
   59257   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
   59258   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
   59259   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
   59260   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
   59261   return WRC_Continue;
   59262 }
   59263 
   59264 /*
   59265 ** Walk the parse trees associated with all subqueries in the
   59266 ** FROM clause of SELECT statement p.  Do not invoke the select
   59267 ** callback on p, but do invoke it on each FROM clause subquery
   59268 ** and on any subqueries further down in the tree.  Return
   59269 ** WRC_Abort or WRC_Continue;
   59270 */
   59271 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
   59272   SrcList *pSrc;
   59273   int i;
   59274   struct SrcList_item *pItem;
   59275 
   59276   pSrc = p->pSrc;
   59277   if( ALWAYS(pSrc) ){
   59278     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
   59279       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
   59280         return WRC_Abort;
   59281       }
   59282     }
   59283   }
   59284   return WRC_Continue;
   59285 }
   59286 
   59287 /*
   59288 ** Call sqlite3WalkExpr() for every expression in Select statement p.
   59289 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
   59290 ** on the compound select chain, p->pPrior.
   59291 **
   59292 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
   59293 ** there is an abort request.
   59294 **
   59295 ** If the Walker does not have an xSelectCallback() then this routine
   59296 ** is a no-op returning WRC_Continue.
   59297 */
   59298 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
   59299   int rc;
   59300   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
   59301   rc = WRC_Continue;
   59302   while( p  ){
   59303     rc = pWalker->xSelectCallback(pWalker, p);
   59304     if( rc ) break;
   59305     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
   59306     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
   59307     p = p->pPrior;
   59308   }
   59309   return rc & WRC_Abort;
   59310 }
   59311 
   59312 /************** End of walker.c **********************************************/
   59313 /************** Begin file resolve.c *****************************************/
   59314 /*
   59315 ** 2008 August 18
   59316 **
   59317 ** The author disclaims copyright to this source code.  In place of
   59318 ** a legal notice, here is a blessing:
   59319 **
   59320 **    May you do good and not evil.
   59321 **    May you find forgiveness for yourself and forgive others.
   59322 **    May you share freely, never taking more than you give.
   59323 **
   59324 *************************************************************************
   59325 **
   59326 ** This file contains routines used for walking the parser tree and
   59327 ** resolve all identifiers by associating them with a particular
   59328 ** table and column.
   59329 */
   59330 
   59331 /*
   59332 ** Turn the pExpr expression into an alias for the iCol-th column of the
   59333 ** result set in pEList.
   59334 **
   59335 ** If the result set column is a simple column reference, then this routine
   59336 ** makes an exact copy.  But for any other kind of expression, this
   59337 ** routine make a copy of the result set column as the argument to the
   59338 ** TK_AS operator.  The TK_AS operator causes the expression to be
   59339 ** evaluated just once and then reused for each alias.
   59340 **
   59341 ** The reason for suppressing the TK_AS term when the expression is a simple
   59342 ** column reference is so that the column reference will be recognized as
   59343 ** usable by indices within the WHERE clause processing logic.
   59344 **
   59345 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
   59346 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
   59347 **
   59348 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
   59349 **
   59350 ** Is equivalent to:
   59351 **
   59352 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
   59353 **
   59354 ** The result of random()%5 in the GROUP BY clause is probably different
   59355 ** from the result in the result-set.  We might fix this someday.  Or
   59356 ** then again, we might not...
   59357 */
   59358 static void resolveAlias(
   59359   Parse *pParse,         /* Parsing context */
   59360   ExprList *pEList,      /* A result set */
   59361   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
   59362   Expr *pExpr,           /* Transform this into an alias to the result set */
   59363   const char *zType      /* "GROUP" or "ORDER" or "" */
   59364 ){
   59365   Expr *pOrig;           /* The iCol-th column of the result set */
   59366   Expr *pDup;            /* Copy of pOrig */
   59367   sqlite3 *db;           /* The database connection */
   59368 
   59369   assert( iCol>=0 && iCol<pEList->nExpr );
   59370   pOrig = pEList->a[iCol].pExpr;
   59371   assert( pOrig!=0 );
   59372   assert( pOrig->flags & EP_Resolved );
   59373   db = pParse->db;
   59374   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
   59375     pDup = sqlite3ExprDup(db, pOrig, 0);
   59376     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
   59377     if( pDup==0 ) return;
   59378     if( pEList->a[iCol].iAlias==0 ){
   59379       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
   59380     }
   59381     pDup->iTable = pEList->a[iCol].iAlias;
   59382   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
   59383     pDup = sqlite3ExprDup(db, pOrig, 0);
   59384     if( pDup==0 ) return;
   59385   }else{
   59386     char *zToken = pOrig->u.zToken;
   59387     assert( zToken!=0 );
   59388     pOrig->u.zToken = 0;
   59389     pDup = sqlite3ExprDup(db, pOrig, 0);
   59390     pOrig->u.zToken = zToken;
   59391     if( pDup==0 ) return;
   59392     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
   59393     pDup->flags2 |= EP2_MallocedToken;
   59394     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
   59395   }
   59396   if( pExpr->flags & EP_ExpCollate ){
   59397     pDup->pColl = pExpr->pColl;
   59398     pDup->flags |= EP_ExpCollate;
   59399   }
   59400 
   59401   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
   59402   ** prevents ExprDelete() from deleting the Expr structure itself,
   59403   ** allowing it to be repopulated by the memcpy() on the following line.
   59404   */
   59405   ExprSetProperty(pExpr, EP_Static);
   59406   sqlite3ExprDelete(db, pExpr);
   59407   memcpy(pExpr, pDup, sizeof(*pExpr));
   59408   sqlite3DbFree(db, pDup);
   59409 }
   59410 
   59411 /*
   59412 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
   59413 ** that name in the set of source tables in pSrcList and make the pExpr
   59414 ** expression node refer back to that source column.  The following changes
   59415 ** are made to pExpr:
   59416 **
   59417 **    pExpr->iDb           Set the index in db->aDb[] of the database X
   59418 **                         (even if X is implied).
   59419 **    pExpr->iTable        Set to the cursor number for the table obtained
   59420 **                         from pSrcList.
   59421 **    pExpr->pTab          Points to the Table structure of X.Y (even if
   59422 **                         X and/or Y are implied.)
   59423 **    pExpr->iColumn       Set to the column number within the table.
   59424 **    pExpr->op            Set to TK_COLUMN.
   59425 **    pExpr->pLeft         Any expression this points to is deleted
   59426 **    pExpr->pRight        Any expression this points to is deleted.
   59427 **
   59428 ** The zDb variable is the name of the database (the "X").  This value may be
   59429 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
   59430 ** can be used.  The zTable variable is the name of the table (the "Y").  This
   59431 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
   59432 ** means that the form of the name is Z and that columns from any table
   59433 ** can be used.
   59434 **
   59435 ** If the name cannot be resolved unambiguously, leave an error message
   59436 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
   59437 */
   59438 static int lookupName(
   59439   Parse *pParse,       /* The parsing context */
   59440   const char *zDb,     /* Name of the database containing table, or NULL */
   59441   const char *zTab,    /* Name of table containing column, or NULL */
   59442   const char *zCol,    /* Name of the column. */
   59443   NameContext *pNC,    /* The name context used to resolve the name */
   59444   Expr *pExpr          /* Make this EXPR node point to the selected column */
   59445 ){
   59446   int i, j;            /* Loop counters */
   59447   int cnt = 0;                      /* Number of matching column names */
   59448   int cntTab = 0;                   /* Number of matching table names */
   59449   sqlite3 *db = pParse->db;         /* The database connection */
   59450   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
   59451   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
   59452   NameContext *pTopNC = pNC;        /* First namecontext in the list */
   59453   Schema *pSchema = 0;              /* Schema of the expression */
   59454   int isTrigger = 0;
   59455 
   59456   assert( pNC );     /* the name context cannot be NULL. */
   59457   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
   59458   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   59459 
   59460   /* Initialize the node to no-match */
   59461   pExpr->iTable = -1;
   59462   pExpr->pTab = 0;
   59463   ExprSetIrreducible(pExpr);
   59464 
   59465   /* Start at the inner-most context and move outward until a match is found */
   59466   while( pNC && cnt==0 ){
   59467     ExprList *pEList;
   59468     SrcList *pSrcList = pNC->pSrcList;
   59469 
   59470     if( pSrcList ){
   59471       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
   59472         Table *pTab;
   59473         int iDb;
   59474         Column *pCol;
   59475 
   59476         pTab = pItem->pTab;
   59477         assert( pTab!=0 && pTab->zName!=0 );
   59478         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   59479         assert( pTab->nCol>0 );
   59480         if( zTab ){
   59481           if( pItem->zAlias ){
   59482             char *zTabName = pItem->zAlias;
   59483             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
   59484           }else{
   59485             char *zTabName = pTab->zName;
   59486             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
   59487               continue;
   59488             }
   59489             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
   59490               continue;
   59491             }
   59492           }
   59493         }
   59494         if( 0==(cntTab++) ){
   59495           pExpr->iTable = pItem->iCursor;
   59496           pExpr->pTab = pTab;
   59497           pSchema = pTab->pSchema;
   59498           pMatch = pItem;
   59499         }
   59500         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
   59501           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   59502             IdList *pUsing;
   59503             cnt++;
   59504             pExpr->iTable = pItem->iCursor;
   59505             pExpr->pTab = pTab;
   59506             pMatch = pItem;
   59507             pSchema = pTab->pSchema;
   59508             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
   59509             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
   59510             if( i<pSrcList->nSrc-1 ){
   59511               if( pItem[1].jointype & JT_NATURAL ){
   59512                 /* If this match occurred in the left table of a natural join,
   59513                 ** then skip the right table to avoid a duplicate match */
   59514                 pItem++;
   59515                 i++;
   59516               }else if( (pUsing = pItem[1].pUsing)!=0 ){
   59517                 /* If this match occurs on a column that is in the USING clause
   59518                 ** of a join, skip the search of the right table of the join
   59519                 ** to avoid a duplicate match there. */
   59520                 int k;
   59521                 for(k=0; k<pUsing->nId; k++){
   59522                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
   59523                     pItem++;
   59524                     i++;
   59525                     break;
   59526                   }
   59527                 }
   59528               }
   59529             }
   59530             break;
   59531           }
   59532         }
   59533       }
   59534     }
   59535 
   59536 #ifndef SQLITE_OMIT_TRIGGER
   59537     /* If we have not already resolved the name, then maybe
   59538     ** it is a new.* or old.* trigger argument reference
   59539     */
   59540     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
   59541       int op = pParse->eTriggerOp;
   59542       Table *pTab = 0;
   59543       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
   59544       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
   59545         pExpr->iTable = 1;
   59546         pTab = pParse->pTriggerTab;
   59547       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
   59548         pExpr->iTable = 0;
   59549         pTab = pParse->pTriggerTab;
   59550       }
   59551 
   59552       if( pTab ){
   59553         int iCol;
   59554         pSchema = pTab->pSchema;
   59555         cntTab++;
   59556         for(iCol=0; iCol<pTab->nCol; iCol++){
   59557           Column *pCol = &pTab->aCol[iCol];
   59558           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   59559             if( iCol==pTab->iPKey ){
   59560               iCol = -1;
   59561             }
   59562             break;
   59563           }
   59564         }
   59565         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
   59566           iCol = -1;        /* IMP: R-44911-55124 */
   59567         }
   59568         if( iCol<pTab->nCol ){
   59569           cnt++;
   59570           if( iCol<0 ){
   59571             pExpr->affinity = SQLITE_AFF_INTEGER;
   59572           }else if( pExpr->iTable==0 ){
   59573             testcase( iCol==31 );
   59574             testcase( iCol==32 );
   59575             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
   59576           }else{
   59577             testcase( iCol==31 );
   59578             testcase( iCol==32 );
   59579             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
   59580           }
   59581           pExpr->iColumn = (i16)iCol;
   59582           pExpr->pTab = pTab;
   59583           isTrigger = 1;
   59584         }
   59585       }
   59586     }
   59587 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   59588 
   59589     /*
   59590     ** Perhaps the name is a reference to the ROWID
   59591     */
   59592     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
   59593       cnt = 1;
   59594       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
   59595       pExpr->affinity = SQLITE_AFF_INTEGER;
   59596     }
   59597 
   59598     /*
   59599     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
   59600     ** might refer to an result-set alias.  This happens, for example, when
   59601     ** we are resolving names in the WHERE clause of the following command:
   59602     **
   59603     **     SELECT a+b AS x FROM table WHERE x<10;
   59604     **
   59605     ** In cases like this, replace pExpr with a copy of the expression that
   59606     ** forms the result set entry ("a+b" in the example) and return immediately.
   59607     ** Note that the expression in the result set should have already been
   59608     ** resolved by the time the WHERE clause is resolved.
   59609     */
   59610     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
   59611       for(j=0; j<pEList->nExpr; j++){
   59612         char *zAs = pEList->a[j].zName;
   59613         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
   59614           Expr *pOrig;
   59615           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
   59616           assert( pExpr->x.pList==0 );
   59617           assert( pExpr->x.pSelect==0 );
   59618           pOrig = pEList->a[j].pExpr;
   59619           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
   59620             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
   59621             return WRC_Abort;
   59622           }
   59623           resolveAlias(pParse, pEList, j, pExpr, "");
   59624           cnt = 1;
   59625           pMatch = 0;
   59626           assert( zTab==0 && zDb==0 );
   59627           goto lookupname_end;
   59628         }
   59629       }
   59630     }
   59631 
   59632     /* Advance to the next name context.  The loop will exit when either
   59633     ** we have a match (cnt>0) or when we run out of name contexts.
   59634     */
   59635     if( cnt==0 ){
   59636       pNC = pNC->pNext;
   59637     }
   59638   }
   59639 
   59640   /*
   59641   ** If X and Y are NULL (in other words if only the column name Z is
   59642   ** supplied) and the value of Z is enclosed in double-quotes, then
   59643   ** Z is a string literal if it doesn't match any column names.  In that
   59644   ** case, we need to return right away and not make any changes to
   59645   ** pExpr.
   59646   **
   59647   ** Because no reference was made to outer contexts, the pNC->nRef
   59648   ** fields are not changed in any context.
   59649   */
   59650   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
   59651     pExpr->op = TK_STRING;
   59652     pExpr->pTab = 0;
   59653     return WRC_Prune;
   59654   }
   59655 
   59656   /*
   59657   ** cnt==0 means there was not match.  cnt>1 means there were two or
   59658   ** more matches.  Either way, we have an error.
   59659   */
   59660   if( cnt!=1 ){
   59661     const char *zErr;
   59662     zErr = cnt==0 ? "no such column" : "ambiguous column name";
   59663     if( zDb ){
   59664       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
   59665     }else if( zTab ){
   59666       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
   59667     }else{
   59668       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
   59669     }
   59670     pTopNC->nErr++;
   59671   }
   59672 
   59673   /* If a column from a table in pSrcList is referenced, then record
   59674   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
   59675   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
   59676   ** column number is greater than the number of bits in the bitmask
   59677   ** then set the high-order bit of the bitmask.
   59678   */
   59679   if( pExpr->iColumn>=0 && pMatch!=0 ){
   59680     int n = pExpr->iColumn;
   59681     testcase( n==BMS-1 );
   59682     if( n>=BMS ){
   59683       n = BMS-1;
   59684     }
   59685     assert( pMatch->iCursor==pExpr->iTable );
   59686     pMatch->colUsed |= ((Bitmask)1)<<n;
   59687   }
   59688 
   59689   /* Clean up and return
   59690   */
   59691   sqlite3ExprDelete(db, pExpr->pLeft);
   59692   pExpr->pLeft = 0;
   59693   sqlite3ExprDelete(db, pExpr->pRight);
   59694   pExpr->pRight = 0;
   59695   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
   59696 lookupname_end:
   59697   if( cnt==1 ){
   59698     assert( pNC!=0 );
   59699     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
   59700     /* Increment the nRef value on all name contexts from TopNC up to
   59701     ** the point where the name matched. */
   59702     for(;;){
   59703       assert( pTopNC!=0 );
   59704       pTopNC->nRef++;
   59705       if( pTopNC==pNC ) break;
   59706       pTopNC = pTopNC->pNext;
   59707     }
   59708     return WRC_Prune;
   59709   } else {
   59710     return WRC_Abort;
   59711   }
   59712 }
   59713 
   59714 /*
   59715 ** Allocate and return a pointer to an expression to load the column iCol
   59716 ** from datasource iSrc datasource in SrcList pSrc.
   59717 */
   59718 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
   59719   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
   59720   if( p ){
   59721     struct SrcList_item *pItem = &pSrc->a[iSrc];
   59722     p->pTab = pItem->pTab;
   59723     p->iTable = pItem->iCursor;
   59724     if( p->pTab->iPKey==iCol ){
   59725       p->iColumn = -1;
   59726     }else{
   59727       p->iColumn = (ynVar)iCol;
   59728       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
   59729     }
   59730     ExprSetProperty(p, EP_Resolved);
   59731   }
   59732   return p;
   59733 }
   59734 
   59735 /*
   59736 ** This routine is callback for sqlite3WalkExpr().
   59737 **
   59738 ** Resolve symbolic names into TK_COLUMN operators for the current
   59739 ** node in the expression tree.  Return 0 to continue the search down
   59740 ** the tree or 2 to abort the tree walk.
   59741 **
   59742 ** This routine also does error checking and name resolution for
   59743 ** function names.  The operator for aggregate functions is changed
   59744 ** to TK_AGG_FUNCTION.
   59745 */
   59746 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
   59747   NameContext *pNC;
   59748   Parse *pParse;
   59749 
   59750   pNC = pWalker->u.pNC;
   59751   assert( pNC!=0 );
   59752   pParse = pNC->pParse;
   59753   assert( pParse==pWalker->pParse );
   59754 
   59755   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
   59756   ExprSetProperty(pExpr, EP_Resolved);
   59757 #ifndef NDEBUG
   59758   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
   59759     SrcList *pSrcList = pNC->pSrcList;
   59760     int i;
   59761     for(i=0; i<pNC->pSrcList->nSrc; i++){
   59762       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
   59763     }
   59764   }
   59765 #endif
   59766   switch( pExpr->op ){
   59767 
   59768 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   59769     /* The special operator TK_ROW means use the rowid for the first
   59770     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
   59771     ** clause processing on UPDATE and DELETE statements.
   59772     */
   59773     case TK_ROW: {
   59774       SrcList *pSrcList = pNC->pSrcList;
   59775       struct SrcList_item *pItem;
   59776       assert( pSrcList && pSrcList->nSrc==1 );
   59777       pItem = pSrcList->a;
   59778       pExpr->op = TK_COLUMN;
   59779       pExpr->pTab = pItem->pTab;
   59780       pExpr->iTable = pItem->iCursor;
   59781       pExpr->iColumn = -1;
   59782       pExpr->affinity = SQLITE_AFF_INTEGER;
   59783       break;
   59784     }
   59785 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
   59786 
   59787     /* A lone identifier is the name of a column.
   59788     */
   59789     case TK_ID: {
   59790       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
   59791     }
   59792 
   59793     /* A table name and column name:     ID.ID
   59794     ** Or a database, table and column:  ID.ID.ID
   59795     */
   59796     case TK_DOT: {
   59797       const char *zColumn;
   59798       const char *zTable;
   59799       const char *zDb;
   59800       Expr *pRight;
   59801 
   59802       /* if( pSrcList==0 ) break; */
   59803       pRight = pExpr->pRight;
   59804       if( pRight->op==TK_ID ){
   59805         zDb = 0;
   59806         zTable = pExpr->pLeft->u.zToken;
   59807         zColumn = pRight->u.zToken;
   59808       }else{
   59809         assert( pRight->op==TK_DOT );
   59810         zDb = pExpr->pLeft->u.zToken;
   59811         zTable = pRight->pLeft->u.zToken;
   59812         zColumn = pRight->pRight->u.zToken;
   59813       }
   59814       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
   59815     }
   59816 
   59817     /* Resolve function names
   59818     */
   59819     case TK_CONST_FUNC:
   59820     case TK_FUNCTION: {
   59821       ExprList *pList = pExpr->x.pList;    /* The argument list */
   59822       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
   59823       int no_such_func = 0;       /* True if no such function exists */
   59824       int wrong_num_args = 0;     /* True if wrong number of arguments */
   59825       int is_agg = 0;             /* True if is an aggregate function */
   59826       int auth;                   /* Authorization to use the function */
   59827       int nId;                    /* Number of characters in function name */
   59828       const char *zId;            /* The function name. */
   59829       FuncDef *pDef;              /* Information about the function */
   59830       u8 enc = ENC(pParse->db);   /* The database encoding */
   59831 
   59832       testcase( pExpr->op==TK_CONST_FUNC );
   59833       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   59834       zId = pExpr->u.zToken;
   59835       nId = sqlite3Strlen30(zId);
   59836       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
   59837       if( pDef==0 ){
   59838         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
   59839         if( pDef==0 ){
   59840           no_such_func = 1;
   59841         }else{
   59842           wrong_num_args = 1;
   59843         }
   59844       }else{
   59845         is_agg = pDef->xFunc==0;
   59846       }
   59847 #ifndef SQLITE_OMIT_AUTHORIZATION
   59848       if( pDef ){
   59849         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
   59850         if( auth!=SQLITE_OK ){
   59851           if( auth==SQLITE_DENY ){
   59852             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
   59853                                     pDef->zName);
   59854             pNC->nErr++;
   59855           }
   59856           pExpr->op = TK_NULL;
   59857           return WRC_Prune;
   59858         }
   59859       }
   59860 #endif
   59861       if( is_agg && !pNC->allowAgg ){
   59862         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
   59863         pNC->nErr++;
   59864         is_agg = 0;
   59865       }else if( no_such_func ){
   59866         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
   59867         pNC->nErr++;
   59868       }else if( wrong_num_args ){
   59869         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
   59870              nId, zId);
   59871         pNC->nErr++;
   59872       }
   59873       if( is_agg ){
   59874         pExpr->op = TK_AGG_FUNCTION;
   59875         pNC->hasAgg = 1;
   59876       }
   59877       if( is_agg ) pNC->allowAgg = 0;
   59878       sqlite3WalkExprList(pWalker, pList);
   59879       if( is_agg ) pNC->allowAgg = 1;
   59880       /* FIX ME:  Compute pExpr->affinity based on the expected return
   59881       ** type of the function
   59882       */
   59883       return WRC_Prune;
   59884     }
   59885 #ifndef SQLITE_OMIT_SUBQUERY
   59886     case TK_SELECT:
   59887     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
   59888 #endif
   59889     case TK_IN: {
   59890       testcase( pExpr->op==TK_IN );
   59891       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   59892         int nRef = pNC->nRef;
   59893 #ifndef SQLITE_OMIT_CHECK
   59894         if( pNC->isCheck ){
   59895           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
   59896         }
   59897 #endif
   59898         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
   59899         assert( pNC->nRef>=nRef );
   59900         if( nRef!=pNC->nRef ){
   59901           ExprSetProperty(pExpr, EP_VarSelect);
   59902         }
   59903       }
   59904       break;
   59905     }
   59906 #ifndef SQLITE_OMIT_CHECK
   59907     case TK_VARIABLE: {
   59908       if( pNC->isCheck ){
   59909         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
   59910       }
   59911       break;
   59912     }
   59913 #endif
   59914   }
   59915   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
   59916 }
   59917 
   59918 /*
   59919 ** pEList is a list of expressions which are really the result set of the
   59920 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
   59921 ** This routine checks to see if pE is a simple identifier which corresponds
   59922 ** to the AS-name of one of the terms of the expression list.  If it is,
   59923 ** this routine return an integer between 1 and N where N is the number of
   59924 ** elements in pEList, corresponding to the matching entry.  If there is
   59925 ** no match, or if pE is not a simple identifier, then this routine
   59926 ** return 0.
   59927 **
   59928 ** pEList has been resolved.  pE has not.
   59929 */
   59930 static int resolveAsName(
   59931   Parse *pParse,     /* Parsing context for error messages */
   59932   ExprList *pEList,  /* List of expressions to scan */
   59933   Expr *pE           /* Expression we are trying to match */
   59934 ){
   59935   int i;             /* Loop counter */
   59936 
   59937   UNUSED_PARAMETER(pParse);
   59938 
   59939   if( pE->op==TK_ID ){
   59940     char *zCol = pE->u.zToken;
   59941     for(i=0; i<pEList->nExpr; i++){
   59942       char *zAs = pEList->a[i].zName;
   59943       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
   59944         return i+1;
   59945       }
   59946     }
   59947   }
   59948   return 0;
   59949 }
   59950 
   59951 /*
   59952 ** pE is a pointer to an expression which is a single term in the
   59953 ** ORDER BY of a compound SELECT.  The expression has not been
   59954 ** name resolved.
   59955 **
   59956 ** At the point this routine is called, we already know that the
   59957 ** ORDER BY term is not an integer index into the result set.  That
   59958 ** case is handled by the calling routine.
   59959 **
   59960 ** Attempt to match pE against result set columns in the left-most
   59961 ** SELECT statement.  Return the index i of the matching column,
   59962 ** as an indication to the caller that it should sort by the i-th column.
   59963 ** The left-most column is 1.  In other words, the value returned is the
   59964 ** same integer value that would be used in the SQL statement to indicate
   59965 ** the column.
   59966 **
   59967 ** If there is no match, return 0.  Return -1 if an error occurs.
   59968 */
   59969 static int resolveOrderByTermToExprList(
   59970   Parse *pParse,     /* Parsing context for error messages */
   59971   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
   59972   Expr *pE           /* The specific ORDER BY term */
   59973 ){
   59974   int i;             /* Loop counter */
   59975   ExprList *pEList;  /* The columns of the result set */
   59976   NameContext nc;    /* Name context for resolving pE */
   59977   sqlite3 *db;       /* Database connection */
   59978   int rc;            /* Return code from subprocedures */
   59979   u8 savedSuppErr;   /* Saved value of db->suppressErr */
   59980 
   59981   assert( sqlite3ExprIsInteger(pE, &i)==0 );
   59982   pEList = pSelect->pEList;
   59983 
   59984   /* Resolve all names in the ORDER BY term expression
   59985   */
   59986   memset(&nc, 0, sizeof(nc));
   59987   nc.pParse = pParse;
   59988   nc.pSrcList = pSelect->pSrc;
   59989   nc.pEList = pEList;
   59990   nc.allowAgg = 1;
   59991   nc.nErr = 0;
   59992   db = pParse->db;
   59993   savedSuppErr = db->suppressErr;
   59994   db->suppressErr = 1;
   59995   rc = sqlite3ResolveExprNames(&nc, pE);
   59996   db->suppressErr = savedSuppErr;
   59997   if( rc ) return 0;
   59998 
   59999   /* Try to match the ORDER BY expression against an expression
   60000   ** in the result set.  Return an 1-based index of the matching
   60001   ** result-set entry.
   60002   */
   60003   for(i=0; i<pEList->nExpr; i++){
   60004     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
   60005       return i+1;
   60006     }
   60007   }
   60008 
   60009   /* If no match, return 0. */
   60010   return 0;
   60011 }
   60012 
   60013 /*
   60014 ** Generate an ORDER BY or GROUP BY term out-of-range error.
   60015 */
   60016 static void resolveOutOfRangeError(
   60017   Parse *pParse,         /* The error context into which to write the error */
   60018   const char *zType,     /* "ORDER" or "GROUP" */
   60019   int i,                 /* The index (1-based) of the term out of range */
   60020   int mx                 /* Largest permissible value of i */
   60021 ){
   60022   sqlite3ErrorMsg(pParse,
   60023     "%r %s BY term out of range - should be "
   60024     "between 1 and %d", i, zType, mx);
   60025 }
   60026 
   60027 /*
   60028 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
   60029 ** each term of the ORDER BY clause is a constant integer between 1
   60030 ** and N where N is the number of columns in the compound SELECT.
   60031 **
   60032 ** ORDER BY terms that are already an integer between 1 and N are
   60033 ** unmodified.  ORDER BY terms that are integers outside the range of
   60034 ** 1 through N generate an error.  ORDER BY terms that are expressions
   60035 ** are matched against result set expressions of compound SELECT
   60036 ** beginning with the left-most SELECT and working toward the right.
   60037 ** At the first match, the ORDER BY expression is transformed into
   60038 ** the integer column number.
   60039 **
   60040 ** Return the number of errors seen.
   60041 */
   60042 static int resolveCompoundOrderBy(
   60043   Parse *pParse,        /* Parsing context.  Leave error messages here */
   60044   Select *pSelect       /* The SELECT statement containing the ORDER BY */
   60045 ){
   60046   int i;
   60047   ExprList *pOrderBy;
   60048   ExprList *pEList;
   60049   sqlite3 *db;
   60050   int moreToDo = 1;
   60051 
   60052   pOrderBy = pSelect->pOrderBy;
   60053   if( pOrderBy==0 ) return 0;
   60054   db = pParse->db;
   60055 #if SQLITE_MAX_COLUMN
   60056   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   60057     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
   60058     return 1;
   60059   }
   60060 #endif
   60061   for(i=0; i<pOrderBy->nExpr; i++){
   60062     pOrderBy->a[i].done = 0;
   60063   }
   60064   pSelect->pNext = 0;
   60065   while( pSelect->pPrior ){
   60066     pSelect->pPrior->pNext = pSelect;
   60067     pSelect = pSelect->pPrior;
   60068   }
   60069   while( pSelect && moreToDo ){
   60070     struct ExprList_item *pItem;
   60071     moreToDo = 0;
   60072     pEList = pSelect->pEList;
   60073     assert( pEList!=0 );
   60074     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   60075       int iCol = -1;
   60076       Expr *pE, *pDup;
   60077       if( pItem->done ) continue;
   60078       pE = pItem->pExpr;
   60079       if( sqlite3ExprIsInteger(pE, &iCol) ){
   60080         if( iCol<=0 || iCol>pEList->nExpr ){
   60081           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
   60082           return 1;
   60083         }
   60084       }else{
   60085         iCol = resolveAsName(pParse, pEList, pE);
   60086         if( iCol==0 ){
   60087           pDup = sqlite3ExprDup(db, pE, 0);
   60088           if( !db->mallocFailed ){
   60089             assert(pDup);
   60090             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
   60091           }
   60092           sqlite3ExprDelete(db, pDup);
   60093         }
   60094       }
   60095       if( iCol>0 ){
   60096         CollSeq *pColl = pE->pColl;
   60097         int flags = pE->flags & EP_ExpCollate;
   60098         sqlite3ExprDelete(db, pE);
   60099         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
   60100         if( pE==0 ) return 1;
   60101         pE->pColl = pColl;
   60102         pE->flags |= EP_IntValue | flags;
   60103         pE->u.iValue = iCol;
   60104         pItem->iCol = (u16)iCol;
   60105         pItem->done = 1;
   60106       }else{
   60107         moreToDo = 1;
   60108       }
   60109     }
   60110     pSelect = pSelect->pNext;
   60111   }
   60112   for(i=0; i<pOrderBy->nExpr; i++){
   60113     if( pOrderBy->a[i].done==0 ){
   60114       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
   60115             "column in the result set", i+1);
   60116       return 1;
   60117     }
   60118   }
   60119   return 0;
   60120 }
   60121 
   60122 /*
   60123 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
   60124 ** the SELECT statement pSelect.  If any term is reference to a
   60125 ** result set expression (as determined by the ExprList.a.iCol field)
   60126 ** then convert that term into a copy of the corresponding result set
   60127 ** column.
   60128 **
   60129 ** If any errors are detected, add an error message to pParse and
   60130 ** return non-zero.  Return zero if no errors are seen.
   60131 */
   60132 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
   60133   Parse *pParse,        /* Parsing context.  Leave error messages here */
   60134   Select *pSelect,      /* The SELECT statement containing the clause */
   60135   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
   60136   const char *zType     /* "ORDER" or "GROUP" */
   60137 ){
   60138   int i;
   60139   sqlite3 *db = pParse->db;
   60140   ExprList *pEList;
   60141   struct ExprList_item *pItem;
   60142 
   60143   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
   60144 #if SQLITE_MAX_COLUMN
   60145   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   60146     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
   60147     return 1;
   60148   }
   60149 #endif
   60150   pEList = pSelect->pEList;
   60151   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
   60152   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   60153     if( pItem->iCol ){
   60154       if( pItem->iCol>pEList->nExpr ){
   60155         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
   60156         return 1;
   60157       }
   60158       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
   60159     }
   60160   }
   60161   return 0;
   60162 }
   60163 
   60164 /*
   60165 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
   60166 ** The Name context of the SELECT statement is pNC.  zType is either
   60167 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
   60168 **
   60169 ** This routine resolves each term of the clause into an expression.
   60170 ** If the order-by term is an integer I between 1 and N (where N is the
   60171 ** number of columns in the result set of the SELECT) then the expression
   60172 ** in the resolution is a copy of the I-th result-set expression.  If
   60173 ** the order-by term is an identify that corresponds to the AS-name of
   60174 ** a result-set expression, then the term resolves to a copy of the
   60175 ** result-set expression.  Otherwise, the expression is resolved in
   60176 ** the usual way - using sqlite3ResolveExprNames().
   60177 **
   60178 ** This routine returns the number of errors.  If errors occur, then
   60179 ** an appropriate error message might be left in pParse.  (OOM errors
   60180 ** excepted.)
   60181 */
   60182 static int resolveOrderGroupBy(
   60183   NameContext *pNC,     /* The name context of the SELECT statement */
   60184   Select *pSelect,      /* The SELECT statement holding pOrderBy */
   60185   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
   60186   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
   60187 ){
   60188   int i;                         /* Loop counter */
   60189   int iCol;                      /* Column number */
   60190   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
   60191   Parse *pParse;                 /* Parsing context */
   60192   int nResult;                   /* Number of terms in the result set */
   60193 
   60194   if( pOrderBy==0 ) return 0;
   60195   nResult = pSelect->pEList->nExpr;
   60196   pParse = pNC->pParse;
   60197   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   60198     Expr *pE = pItem->pExpr;
   60199     iCol = resolveAsName(pParse, pSelect->pEList, pE);
   60200     if( iCol>0 ){
   60201       /* If an AS-name match is found, mark this ORDER BY column as being
   60202       ** a copy of the iCol-th result-set column.  The subsequent call to
   60203       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
   60204       ** copy of the iCol-th result-set expression. */
   60205       pItem->iCol = (u16)iCol;
   60206       continue;
   60207     }
   60208     if( sqlite3ExprIsInteger(pE, &iCol) ){
   60209       /* The ORDER BY term is an integer constant.  Again, set the column
   60210       ** number so that sqlite3ResolveOrderGroupBy() will convert the
   60211       ** order-by term to a copy of the result-set expression */
   60212       if( iCol<1 ){
   60213         resolveOutOfRangeError(pParse, zType, i+1, nResult);
   60214         return 1;
   60215       }
   60216       pItem->iCol = (u16)iCol;
   60217       continue;
   60218     }
   60219 
   60220     /* Otherwise, treat the ORDER BY term as an ordinary expression */
   60221     pItem->iCol = 0;
   60222     if( sqlite3ResolveExprNames(pNC, pE) ){
   60223       return 1;
   60224     }
   60225   }
   60226   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
   60227 }
   60228 
   60229 /*
   60230 ** Resolve names in the SELECT statement p and all of its descendents.
   60231 */
   60232 static int resolveSelectStep(Walker *pWalker, Select *p){
   60233   NameContext *pOuterNC;  /* Context that contains this SELECT */
   60234   NameContext sNC;        /* Name context of this SELECT */
   60235   int isCompound;         /* True if p is a compound select */
   60236   int nCompound;          /* Number of compound terms processed so far */
   60237   Parse *pParse;          /* Parsing context */
   60238   ExprList *pEList;       /* Result set expression list */
   60239   int i;                  /* Loop counter */
   60240   ExprList *pGroupBy;     /* The GROUP BY clause */
   60241   Select *pLeftmost;      /* Left-most of SELECT of a compound */
   60242   sqlite3 *db;            /* Database connection */
   60243 
   60244 
   60245   assert( p!=0 );
   60246   if( p->selFlags & SF_Resolved ){
   60247     return WRC_Prune;
   60248   }
   60249   pOuterNC = pWalker->u.pNC;
   60250   pParse = pWalker->pParse;
   60251   db = pParse->db;
   60252 
   60253   /* Normally sqlite3SelectExpand() will be called first and will have
   60254   ** already expanded this SELECT.  However, if this is a subquery within
   60255   ** an expression, sqlite3ResolveExprNames() will be called without a
   60256   ** prior call to sqlite3SelectExpand().  When that happens, let
   60257   ** sqlite3SelectPrep() do all of the processing for this SELECT.
   60258   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
   60259   ** this routine in the correct order.
   60260   */
   60261   if( (p->selFlags & SF_Expanded)==0 ){
   60262     sqlite3SelectPrep(pParse, p, pOuterNC);
   60263     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
   60264   }
   60265 
   60266   isCompound = p->pPrior!=0;
   60267   nCompound = 0;
   60268   pLeftmost = p;
   60269   while( p ){
   60270     assert( (p->selFlags & SF_Expanded)!=0 );
   60271     assert( (p->selFlags & SF_Resolved)==0 );
   60272     p->selFlags |= SF_Resolved;
   60273 
   60274     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
   60275     ** are not allowed to refer to any names, so pass an empty NameContext.
   60276     */
   60277     memset(&sNC, 0, sizeof(sNC));
   60278     sNC.pParse = pParse;
   60279     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
   60280         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
   60281       return WRC_Abort;
   60282     }
   60283 
   60284     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
   60285     ** resolve the result-set expression list.
   60286     */
   60287     sNC.allowAgg = 1;
   60288     sNC.pSrcList = p->pSrc;
   60289     sNC.pNext = pOuterNC;
   60290 
   60291     /* Resolve names in the result set. */
   60292     pEList = p->pEList;
   60293     assert( pEList!=0 );
   60294     for(i=0; i<pEList->nExpr; i++){
   60295       Expr *pX = pEList->a[i].pExpr;
   60296       if( sqlite3ResolveExprNames(&sNC, pX) ){
   60297         return WRC_Abort;
   60298       }
   60299     }
   60300 
   60301     /* Recursively resolve names in all subqueries
   60302     */
   60303     for(i=0; i<p->pSrc->nSrc; i++){
   60304       struct SrcList_item *pItem = &p->pSrc->a[i];
   60305       if( pItem->pSelect ){
   60306         const char *zSavedContext = pParse->zAuthContext;
   60307         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
   60308         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
   60309         pParse->zAuthContext = zSavedContext;
   60310         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
   60311       }
   60312     }
   60313 
   60314     /* If there are no aggregate functions in the result-set, and no GROUP BY
   60315     ** expression, do not allow aggregates in any of the other expressions.
   60316     */
   60317     assert( (p->selFlags & SF_Aggregate)==0 );
   60318     pGroupBy = p->pGroupBy;
   60319     if( pGroupBy || sNC.hasAgg ){
   60320       p->selFlags |= SF_Aggregate;
   60321     }else{
   60322       sNC.allowAgg = 0;
   60323     }
   60324 
   60325     /* If a HAVING clause is present, then there must be a GROUP BY clause.
   60326     */
   60327     if( p->pHaving && !pGroupBy ){
   60328       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
   60329       return WRC_Abort;
   60330     }
   60331 
   60332     /* Add the expression list to the name-context before parsing the
   60333     ** other expressions in the SELECT statement. This is so that
   60334     ** expressions in the WHERE clause (etc.) can refer to expressions by
   60335     ** aliases in the result set.
   60336     **
   60337     ** Minor point: If this is the case, then the expression will be
   60338     ** re-evaluated for each reference to it.
   60339     */
   60340     sNC.pEList = p->pEList;
   60341     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
   60342        sqlite3ResolveExprNames(&sNC, p->pHaving)
   60343     ){
   60344       return WRC_Abort;
   60345     }
   60346 
   60347     /* The ORDER BY and GROUP BY clauses may not refer to terms in
   60348     ** outer queries
   60349     */
   60350     sNC.pNext = 0;
   60351     sNC.allowAgg = 1;
   60352 
   60353     /* Process the ORDER BY clause for singleton SELECT statements.
   60354     ** The ORDER BY clause for compounds SELECT statements is handled
   60355     ** below, after all of the result-sets for all of the elements of
   60356     ** the compound have been resolved.
   60357     */
   60358     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
   60359       return WRC_Abort;
   60360     }
   60361     if( db->mallocFailed ){
   60362       return WRC_Abort;
   60363     }
   60364 
   60365     /* Resolve the GROUP BY clause.  At the same time, make sure
   60366     ** the GROUP BY clause does not contain aggregate functions.
   60367     */
   60368     if( pGroupBy ){
   60369       struct ExprList_item *pItem;
   60370 
   60371       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
   60372         return WRC_Abort;
   60373       }
   60374       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
   60375         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
   60376           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
   60377               "the GROUP BY clause");
   60378           return WRC_Abort;
   60379         }
   60380       }
   60381     }
   60382 
   60383     /* Advance to the next term of the compound
   60384     */
   60385     p = p->pPrior;
   60386     nCompound++;
   60387   }
   60388 
   60389   /* Resolve the ORDER BY on a compound SELECT after all terms of
   60390   ** the compound have been resolved.
   60391   */
   60392   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
   60393     return WRC_Abort;
   60394   }
   60395 
   60396   return WRC_Prune;
   60397 }
   60398 
   60399 /*
   60400 ** This routine walks an expression tree and resolves references to
   60401 ** table columns and result-set columns.  At the same time, do error
   60402 ** checking on function usage and set a flag if any aggregate functions
   60403 ** are seen.
   60404 **
   60405 ** To resolve table columns references we look for nodes (or subtrees) of the
   60406 ** form X.Y.Z or Y.Z or just Z where
   60407 **
   60408 **      X:   The name of a database.  Ex:  "main" or "temp" or
   60409 **           the symbolic name assigned to an ATTACH-ed database.
   60410 **
   60411 **      Y:   The name of a table in a FROM clause.  Or in a trigger
   60412 **           one of the special names "old" or "new".
   60413 **
   60414 **      Z:   The name of a column in table Y.
   60415 **
   60416 ** The node at the root of the subtree is modified as follows:
   60417 **
   60418 **    Expr.op        Changed to TK_COLUMN
   60419 **    Expr.pTab      Points to the Table object for X.Y
   60420 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
   60421 **    Expr.iTable    The VDBE cursor number for X.Y
   60422 **
   60423 **
   60424 ** To resolve result-set references, look for expression nodes of the
   60425 ** form Z (with no X and Y prefix) where the Z matches the right-hand
   60426 ** size of an AS clause in the result-set of a SELECT.  The Z expression
   60427 ** is replaced by a copy of the left-hand side of the result-set expression.
   60428 ** Table-name and function resolution occurs on the substituted expression
   60429 ** tree.  For example, in:
   60430 **
   60431 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
   60432 **
   60433 ** The "x" term of the order by is replaced by "a+b" to render:
   60434 **
   60435 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
   60436 **
   60437 ** Function calls are checked to make sure that the function is
   60438 ** defined and that the correct number of arguments are specified.
   60439 ** If the function is an aggregate function, then the pNC->hasAgg is
   60440 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
   60441 ** If an expression contains aggregate functions then the EP_Agg
   60442 ** property on the expression is set.
   60443 **
   60444 ** An error message is left in pParse if anything is amiss.  The number
   60445 ** if errors is returned.
   60446 */
   60447 SQLITE_PRIVATE int sqlite3ResolveExprNames(
   60448   NameContext *pNC,       /* Namespace to resolve expressions in. */
   60449   Expr *pExpr             /* The expression to be analyzed. */
   60450 ){
   60451   int savedHasAgg;
   60452   Walker w;
   60453 
   60454   if( pExpr==0 ) return 0;
   60455 #if SQLITE_MAX_EXPR_DEPTH>0
   60456   {
   60457     Parse *pParse = pNC->pParse;
   60458     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
   60459       return 1;
   60460     }
   60461     pParse->nHeight += pExpr->nHeight;
   60462   }
   60463 #endif
   60464   savedHasAgg = pNC->hasAgg;
   60465   pNC->hasAgg = 0;
   60466   w.xExprCallback = resolveExprStep;
   60467   w.xSelectCallback = resolveSelectStep;
   60468   w.pParse = pNC->pParse;
   60469   w.u.pNC = pNC;
   60470   sqlite3WalkExpr(&w, pExpr);
   60471 #if SQLITE_MAX_EXPR_DEPTH>0
   60472   pNC->pParse->nHeight -= pExpr->nHeight;
   60473 #endif
   60474   if( pNC->nErr>0 || w.pParse->nErr>0 ){
   60475     ExprSetProperty(pExpr, EP_Error);
   60476   }
   60477   if( pNC->hasAgg ){
   60478     ExprSetProperty(pExpr, EP_Agg);
   60479   }else if( savedHasAgg ){
   60480     pNC->hasAgg = 1;
   60481   }
   60482   return ExprHasProperty(pExpr, EP_Error);
   60483 }
   60484 
   60485 
   60486 /*
   60487 ** Resolve all names in all expressions of a SELECT and in all
   60488 ** decendents of the SELECT, including compounds off of p->pPrior,
   60489 ** subqueries in expressions, and subqueries used as FROM clause
   60490 ** terms.
   60491 **
   60492 ** See sqlite3ResolveExprNames() for a description of the kinds of
   60493 ** transformations that occur.
   60494 **
   60495 ** All SELECT statements should have been expanded using
   60496 ** sqlite3SelectExpand() prior to invoking this routine.
   60497 */
   60498 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
   60499   Parse *pParse,         /* The parser context */
   60500   Select *p,             /* The SELECT statement being coded. */
   60501   NameContext *pOuterNC  /* Name context for parent SELECT statement */
   60502 ){
   60503   Walker w;
   60504 
   60505   assert( p!=0 );
   60506   w.xExprCallback = resolveExprStep;
   60507   w.xSelectCallback = resolveSelectStep;
   60508   w.pParse = pParse;
   60509   w.u.pNC = pOuterNC;
   60510   sqlite3WalkSelect(&w, p);
   60511 }
   60512 
   60513 /************** End of resolve.c *********************************************/
   60514 /************** Begin file expr.c ********************************************/
   60515 /*
   60516 ** 2001 September 15
   60517 **
   60518 ** The author disclaims copyright to this source code.  In place of
   60519 ** a legal notice, here is a blessing:
   60520 **
   60521 **    May you do good and not evil.
   60522 **    May you find forgiveness for yourself and forgive others.
   60523 **    May you share freely, never taking more than you give.
   60524 **
   60525 *************************************************************************
   60526 ** This file contains routines used for analyzing expressions and
   60527 ** for generating VDBE code that evaluates expressions in SQLite.
   60528 */
   60529 
   60530 /*
   60531 ** Return the 'affinity' of the expression pExpr if any.
   60532 **
   60533 ** If pExpr is a column, a reference to a column via an 'AS' alias,
   60534 ** or a sub-select with a column as the return value, then the
   60535 ** affinity of that column is returned. Otherwise, 0x00 is returned,
   60536 ** indicating no affinity for the expression.
   60537 **
   60538 ** i.e. the WHERE clause expresssions in the following statements all
   60539 ** have an affinity:
   60540 **
   60541 ** CREATE TABLE t1(a);
   60542 ** SELECT * FROM t1 WHERE a;
   60543 ** SELECT a AS b FROM t1 WHERE b;
   60544 ** SELECT * FROM t1 WHERE (select a from t1);
   60545 */
   60546 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
   60547   int op = pExpr->op;
   60548   if( op==TK_SELECT ){
   60549     assert( pExpr->flags&EP_xIsSelect );
   60550     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
   60551   }
   60552 #ifndef SQLITE_OMIT_CAST
   60553   if( op==TK_CAST ){
   60554     assert( !ExprHasProperty(pExpr, EP_IntValue) );
   60555     return sqlite3AffinityType(pExpr->u.zToken);
   60556   }
   60557 #endif
   60558   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
   60559    && pExpr->pTab!=0
   60560   ){
   60561     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
   60562     ** a TK_COLUMN but was previously evaluated and cached in a register */
   60563     int j = pExpr->iColumn;
   60564     if( j<0 ) return SQLITE_AFF_INTEGER;
   60565     assert( pExpr->pTab && j<pExpr->pTab->nCol );
   60566     return pExpr->pTab->aCol[j].affinity;
   60567   }
   60568   return pExpr->affinity;
   60569 }
   60570 
   60571 /*
   60572 ** Set the collating sequence for expression pExpr to be the collating
   60573 ** sequence named by pToken.   Return a pointer to the revised expression.
   60574 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
   60575 ** flag.  An explicit collating sequence will override implicit
   60576 ** collating sequences.
   60577 */
   60578 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
   60579   char *zColl = 0;            /* Dequoted name of collation sequence */
   60580   CollSeq *pColl;
   60581   sqlite3 *db = pParse->db;
   60582   zColl = sqlite3NameFromToken(db, pCollName);
   60583   if( pExpr && zColl ){
   60584     pColl = sqlite3LocateCollSeq(pParse, zColl);
   60585     if( pColl ){
   60586       pExpr->pColl = pColl;
   60587       pExpr->flags |= EP_ExpCollate;
   60588     }
   60589   }
   60590   sqlite3DbFree(db, zColl);
   60591   return pExpr;
   60592 }
   60593 
   60594 /*
   60595 ** Return the default collation sequence for the expression pExpr. If
   60596 ** there is no default collation type, return 0.
   60597 */
   60598 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
   60599   CollSeq *pColl = 0;
   60600   Expr *p = pExpr;
   60601   while( ALWAYS(p) ){
   60602     int op;
   60603     pColl = p->pColl;
   60604     if( pColl ) break;
   60605     op = p->op;
   60606     if( p->pTab!=0 && (
   60607         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
   60608     )){
   60609       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
   60610       ** a TK_COLUMN but was previously evaluated and cached in a register */
   60611       const char *zColl;
   60612       int j = p->iColumn;
   60613       if( j>=0 ){
   60614         sqlite3 *db = pParse->db;
   60615         zColl = p->pTab->aCol[j].zColl;
   60616         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
   60617         pExpr->pColl = pColl;
   60618       }
   60619       break;
   60620     }
   60621     if( op!=TK_CAST && op!=TK_UPLUS ){
   60622       break;
   60623     }
   60624     p = p->pLeft;
   60625   }
   60626   if( sqlite3CheckCollSeq(pParse, pColl) ){
   60627     pColl = 0;
   60628   }
   60629   return pColl;
   60630 }
   60631 
   60632 /*
   60633 ** pExpr is an operand of a comparison operator.  aff2 is the
   60634 ** type affinity of the other operand.  This routine returns the
   60635 ** type affinity that should be used for the comparison operator.
   60636 */
   60637 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
   60638   char aff1 = sqlite3ExprAffinity(pExpr);
   60639   if( aff1 && aff2 ){
   60640     /* Both sides of the comparison are columns. If one has numeric
   60641     ** affinity, use that. Otherwise use no affinity.
   60642     */
   60643     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
   60644       return SQLITE_AFF_NUMERIC;
   60645     }else{
   60646       return SQLITE_AFF_NONE;
   60647     }
   60648   }else if( !aff1 && !aff2 ){
   60649     /* Neither side of the comparison is a column.  Compare the
   60650     ** results directly.
   60651     */
   60652     return SQLITE_AFF_NONE;
   60653   }else{
   60654     /* One side is a column, the other is not. Use the columns affinity. */
   60655     assert( aff1==0 || aff2==0 );
   60656     return (aff1 + aff2);
   60657   }
   60658 }
   60659 
   60660 /*
   60661 ** pExpr is a comparison operator.  Return the type affinity that should
   60662 ** be applied to both operands prior to doing the comparison.
   60663 */
   60664 static char comparisonAffinity(Expr *pExpr){
   60665   char aff;
   60666   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
   60667           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
   60668           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
   60669   assert( pExpr->pLeft );
   60670   aff = sqlite3ExprAffinity(pExpr->pLeft);
   60671   if( pExpr->pRight ){
   60672     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
   60673   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   60674     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
   60675   }else if( !aff ){
   60676     aff = SQLITE_AFF_NONE;
   60677   }
   60678   return aff;
   60679 }
   60680 
   60681 /*
   60682 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
   60683 ** idx_affinity is the affinity of an indexed column. Return true
   60684 ** if the index with affinity idx_affinity may be used to implement
   60685 ** the comparison in pExpr.
   60686 */
   60687 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
   60688   char aff = comparisonAffinity(pExpr);
   60689   switch( aff ){
   60690     case SQLITE_AFF_NONE:
   60691       return 1;
   60692     case SQLITE_AFF_TEXT:
   60693       return idx_affinity==SQLITE_AFF_TEXT;
   60694     default:
   60695       return sqlite3IsNumericAffinity(idx_affinity);
   60696   }
   60697 }
   60698 
   60699 /*
   60700 ** Return the P5 value that should be used for a binary comparison
   60701 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
   60702 */
   60703 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
   60704   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
   60705   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
   60706   return aff;
   60707 }
   60708 
   60709 /*
   60710 ** Return a pointer to the collation sequence that should be used by
   60711 ** a binary comparison operator comparing pLeft and pRight.
   60712 **
   60713 ** If the left hand expression has a collating sequence type, then it is
   60714 ** used. Otherwise the collation sequence for the right hand expression
   60715 ** is used, or the default (BINARY) if neither expression has a collating
   60716 ** type.
   60717 **
   60718 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
   60719 ** it is not considered.
   60720 */
   60721 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
   60722   Parse *pParse,
   60723   Expr *pLeft,
   60724   Expr *pRight
   60725 ){
   60726   CollSeq *pColl;
   60727   assert( pLeft );
   60728   if( pLeft->flags & EP_ExpCollate ){
   60729     assert( pLeft->pColl );
   60730     pColl = pLeft->pColl;
   60731   }else if( pRight && pRight->flags & EP_ExpCollate ){
   60732     assert( pRight->pColl );
   60733     pColl = pRight->pColl;
   60734   }else{
   60735     pColl = sqlite3ExprCollSeq(pParse, pLeft);
   60736     if( !pColl ){
   60737       pColl = sqlite3ExprCollSeq(pParse, pRight);
   60738     }
   60739   }
   60740   return pColl;
   60741 }
   60742 
   60743 /*
   60744 ** Generate code for a comparison operator.
   60745 */
   60746 static int codeCompare(
   60747   Parse *pParse,    /* The parsing (and code generating) context */
   60748   Expr *pLeft,      /* The left operand */
   60749   Expr *pRight,     /* The right operand */
   60750   int opcode,       /* The comparison opcode */
   60751   int in1, int in2, /* Register holding operands */
   60752   int dest,         /* Jump here if true.  */
   60753   int jumpIfNull    /* If true, jump if either operand is NULL */
   60754 ){
   60755   int p5;
   60756   int addr;
   60757   CollSeq *p4;
   60758 
   60759   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
   60760   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
   60761   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
   60762                            (void*)p4, P4_COLLSEQ);
   60763   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
   60764   if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
   60765     sqlite3ExprCacheAffinityChange(pParse, in1, 1);
   60766     sqlite3ExprCacheAffinityChange(pParse, in2, 1);
   60767   }
   60768   return addr;
   60769 }
   60770 
   60771 #if SQLITE_MAX_EXPR_DEPTH>0
   60772 /*
   60773 ** Check that argument nHeight is less than or equal to the maximum
   60774 ** expression depth allowed. If it is not, leave an error message in
   60775 ** pParse.
   60776 */
   60777 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
   60778   int rc = SQLITE_OK;
   60779   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
   60780   if( nHeight>mxHeight ){
   60781     sqlite3ErrorMsg(pParse,
   60782        "Expression tree is too large (maximum depth %d)", mxHeight
   60783     );
   60784     rc = SQLITE_ERROR;
   60785   }
   60786   return rc;
   60787 }
   60788 
   60789 /* The following three functions, heightOfExpr(), heightOfExprList()
   60790 ** and heightOfSelect(), are used to determine the maximum height
   60791 ** of any expression tree referenced by the structure passed as the
   60792 ** first argument.
   60793 **
   60794 ** If this maximum height is greater than the current value pointed
   60795 ** to by pnHeight, the second parameter, then set *pnHeight to that
   60796 ** value.
   60797 */
   60798 static void heightOfExpr(Expr *p, int *pnHeight){
   60799   if( p ){
   60800     if( p->nHeight>*pnHeight ){
   60801       *pnHeight = p->nHeight;
   60802     }
   60803   }
   60804 }
   60805 static void heightOfExprList(ExprList *p, int *pnHeight){
   60806   if( p ){
   60807     int i;
   60808     for(i=0; i<p->nExpr; i++){
   60809       heightOfExpr(p->a[i].pExpr, pnHeight);
   60810     }
   60811   }
   60812 }
   60813 static void heightOfSelect(Select *p, int *pnHeight){
   60814   if( p ){
   60815     heightOfExpr(p->pWhere, pnHeight);
   60816     heightOfExpr(p->pHaving, pnHeight);
   60817     heightOfExpr(p->pLimit, pnHeight);
   60818     heightOfExpr(p->pOffset, pnHeight);
   60819     heightOfExprList(p->pEList, pnHeight);
   60820     heightOfExprList(p->pGroupBy, pnHeight);
   60821     heightOfExprList(p->pOrderBy, pnHeight);
   60822     heightOfSelect(p->pPrior, pnHeight);
   60823   }
   60824 }
   60825 
   60826 /*
   60827 ** Set the Expr.nHeight variable in the structure passed as an
   60828 ** argument. An expression with no children, Expr.pList or
   60829 ** Expr.pSelect member has a height of 1. Any other expression
   60830 ** has a height equal to the maximum height of any other
   60831 ** referenced Expr plus one.
   60832 */
   60833 static void exprSetHeight(Expr *p){
   60834   int nHeight = 0;
   60835   heightOfExpr(p->pLeft, &nHeight);
   60836   heightOfExpr(p->pRight, &nHeight);
   60837   if( ExprHasProperty(p, EP_xIsSelect) ){
   60838     heightOfSelect(p->x.pSelect, &nHeight);
   60839   }else{
   60840     heightOfExprList(p->x.pList, &nHeight);
   60841   }
   60842   p->nHeight = nHeight + 1;
   60843 }
   60844 
   60845 /*
   60846 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
   60847 ** the height is greater than the maximum allowed expression depth,
   60848 ** leave an error in pParse.
   60849 */
   60850 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
   60851   exprSetHeight(p);
   60852   sqlite3ExprCheckHeight(pParse, p->nHeight);
   60853 }
   60854 
   60855 /*
   60856 ** Return the maximum height of any expression tree referenced
   60857 ** by the select statement passed as an argument.
   60858 */
   60859 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
   60860   int nHeight = 0;
   60861   heightOfSelect(p, &nHeight);
   60862   return nHeight;
   60863 }
   60864 #else
   60865   #define exprSetHeight(y)
   60866 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
   60867 
   60868 /*
   60869 ** This routine is the core allocator for Expr nodes.
   60870 **
   60871 ** Construct a new expression node and return a pointer to it.  Memory
   60872 ** for this node and for the pToken argument is a single allocation
   60873 ** obtained from sqlite3DbMalloc().  The calling function
   60874 ** is responsible for making sure the node eventually gets freed.
   60875 **
   60876 ** If dequote is true, then the token (if it exists) is dequoted.
   60877 ** If dequote is false, no dequoting is performance.  The deQuote
   60878 ** parameter is ignored if pToken is NULL or if the token does not
   60879 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
   60880 ** then the EP_DblQuoted flag is set on the expression node.
   60881 **
   60882 ** Special case:  If op==TK_INTEGER and pToken points to a string that
   60883 ** can be translated into a 32-bit integer, then the token is not
   60884 ** stored in u.zToken.  Instead, the integer values is written
   60885 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
   60886 ** is allocated to hold the integer text and the dequote flag is ignored.
   60887 */
   60888 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
   60889   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
   60890   int op,                 /* Expression opcode */
   60891   const Token *pToken,    /* Token argument.  Might be NULL */
   60892   int dequote             /* True to dequote */
   60893 ){
   60894   Expr *pNew;
   60895   int nExtra = 0;
   60896   int iValue = 0;
   60897 
   60898   if( pToken ){
   60899     if( op!=TK_INTEGER || pToken->z==0
   60900           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
   60901       nExtra = pToken->n+1;
   60902     }
   60903   }
   60904   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
   60905   if( pNew ){
   60906     pNew->op = (u8)op;
   60907     pNew->iAgg = -1;
   60908     if( pToken ){
   60909       if( nExtra==0 ){
   60910         pNew->flags |= EP_IntValue;
   60911         pNew->u.iValue = iValue;
   60912       }else{
   60913         int c;
   60914         pNew->u.zToken = (char*)&pNew[1];
   60915         memcpy(pNew->u.zToken, pToken->z, pToken->n);
   60916         pNew->u.zToken[pToken->n] = 0;
   60917         if( dequote && nExtra>=3
   60918              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
   60919           sqlite3Dequote(pNew->u.zToken);
   60920           if( c=='"' ) pNew->flags |= EP_DblQuoted;
   60921         }
   60922       }
   60923     }
   60924 #if SQLITE_MAX_EXPR_DEPTH>0
   60925     pNew->nHeight = 1;
   60926 #endif
   60927   }
   60928   return pNew;
   60929 }
   60930 
   60931 /*
   60932 ** Allocate a new expression node from a zero-terminated token that has
   60933 ** already been dequoted.
   60934 */
   60935 SQLITE_PRIVATE Expr *sqlite3Expr(
   60936   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
   60937   int op,                 /* Expression opcode */
   60938   const char *zToken      /* Token argument.  Might be NULL */
   60939 ){
   60940   Token x;
   60941   x.z = zToken;
   60942   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
   60943   return sqlite3ExprAlloc(db, op, &x, 0);
   60944 }
   60945 
   60946 /*
   60947 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
   60948 **
   60949 ** If pRoot==NULL that means that a memory allocation error has occurred.
   60950 ** In that case, delete the subtrees pLeft and pRight.
   60951 */
   60952 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
   60953   sqlite3 *db,
   60954   Expr *pRoot,
   60955   Expr *pLeft,
   60956   Expr *pRight
   60957 ){
   60958   if( pRoot==0 ){
   60959     assert( db->mallocFailed );
   60960     sqlite3ExprDelete(db, pLeft);
   60961     sqlite3ExprDelete(db, pRight);
   60962   }else{
   60963     if( pRight ){
   60964       pRoot->pRight = pRight;
   60965       if( pRight->flags & EP_ExpCollate ){
   60966         pRoot->flags |= EP_ExpCollate;
   60967         pRoot->pColl = pRight->pColl;
   60968       }
   60969     }
   60970     if( pLeft ){
   60971       pRoot->pLeft = pLeft;
   60972       if( pLeft->flags & EP_ExpCollate ){
   60973         pRoot->flags |= EP_ExpCollate;
   60974         pRoot->pColl = pLeft->pColl;
   60975       }
   60976     }
   60977     exprSetHeight(pRoot);
   60978   }
   60979 }
   60980 
   60981 /*
   60982 ** Allocate a Expr node which joins as many as two subtrees.
   60983 **
   60984 ** One or both of the subtrees can be NULL.  Return a pointer to the new
   60985 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
   60986 ** free the subtrees and return NULL.
   60987 */
   60988 SQLITE_PRIVATE Expr *sqlite3PExpr(
   60989   Parse *pParse,          /* Parsing context */
   60990   int op,                 /* Expression opcode */
   60991   Expr *pLeft,            /* Left operand */
   60992   Expr *pRight,           /* Right operand */
   60993   const Token *pToken     /* Argument token */
   60994 ){
   60995   Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
   60996   sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
   60997   return p;
   60998 }
   60999 
   61000 /*
   61001 ** Join two expressions using an AND operator.  If either expression is
   61002 ** NULL, then just return the other expression.
   61003 */
   61004 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
   61005   if( pLeft==0 ){
   61006     return pRight;
   61007   }else if( pRight==0 ){
   61008     return pLeft;
   61009   }else{
   61010     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
   61011     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
   61012     return pNew;
   61013   }
   61014 }
   61015 
   61016 /*
   61017 ** Construct a new expression node for a function with multiple
   61018 ** arguments.
   61019 */
   61020 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
   61021   Expr *pNew;
   61022   sqlite3 *db = pParse->db;
   61023   assert( pToken );
   61024   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
   61025   if( pNew==0 ){
   61026     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
   61027     return 0;
   61028   }
   61029   pNew->x.pList = pList;
   61030   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
   61031   sqlite3ExprSetHeight(pParse, pNew);
   61032   return pNew;
   61033 }
   61034 
   61035 /*
   61036 ** Assign a variable number to an expression that encodes a wildcard
   61037 ** in the original SQL statement.
   61038 **
   61039 ** Wildcards consisting of a single "?" are assigned the next sequential
   61040 ** variable number.
   61041 **
   61042 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
   61043 ** sure "nnn" is not too be to avoid a denial of service attack when
   61044 ** the SQL statement comes from an external source.
   61045 **
   61046 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
   61047 ** as the previous instance of the same wildcard.  Or if this is the first
   61048 ** instance of the wildcard, the next sequenial variable number is
   61049 ** assigned.
   61050 */
   61051 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
   61052   sqlite3 *db = pParse->db;
   61053   const char *z;
   61054 
   61055   if( pExpr==0 ) return;
   61056   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
   61057   z = pExpr->u.zToken;
   61058   assert( z!=0 );
   61059   assert( z[0]!=0 );
   61060   if( z[1]==0 ){
   61061     /* Wildcard of the form "?".  Assign the next variable number */
   61062     assert( z[0]=='?' );
   61063     pExpr->iColumn = (ynVar)(++pParse->nVar);
   61064   }else if( z[0]=='?' ){
   61065     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
   61066     ** use it as the variable number */
   61067     int i = atoi((char*)&z[1]);
   61068     pExpr->iColumn = (ynVar)i;
   61069     testcase( i==0 );
   61070     testcase( i==1 );
   61071     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
   61072     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
   61073     if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
   61074       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
   61075           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
   61076     }
   61077     if( i>pParse->nVar ){
   61078       pParse->nVar = i;
   61079     }
   61080   }else{
   61081     /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
   61082     ** number as the prior appearance of the same name, or if the name
   61083     ** has never appeared before, reuse the same variable number
   61084     */
   61085     int i;
   61086     u32 n;
   61087     n = sqlite3Strlen30(z);
   61088     for(i=0; i<pParse->nVarExpr; i++){
   61089       Expr *pE = pParse->apVarExpr[i];
   61090       assert( pE!=0 );
   61091       if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
   61092         pExpr->iColumn = pE->iColumn;
   61093         break;
   61094       }
   61095     }
   61096     if( i>=pParse->nVarExpr ){
   61097       pExpr->iColumn = (ynVar)(++pParse->nVar);
   61098       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
   61099         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
   61100         pParse->apVarExpr =
   61101             sqlite3DbReallocOrFree(
   61102               db,
   61103               pParse->apVarExpr,
   61104               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
   61105             );
   61106       }
   61107       if( !db->mallocFailed ){
   61108         assert( pParse->apVarExpr!=0 );
   61109         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
   61110       }
   61111     }
   61112   }
   61113   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
   61114     sqlite3ErrorMsg(pParse, "too many SQL variables");
   61115   }
   61116 }
   61117 
   61118 /*
   61119 ** Recursively delete an expression tree.
   61120 */
   61121 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
   61122   if( p==0 ) return;
   61123   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
   61124     sqlite3ExprDelete(db, p->pLeft);
   61125     sqlite3ExprDelete(db, p->pRight);
   61126     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
   61127       sqlite3DbFree(db, p->u.zToken);
   61128     }
   61129     if( ExprHasProperty(p, EP_xIsSelect) ){
   61130       sqlite3SelectDelete(db, p->x.pSelect);
   61131     }else{
   61132       sqlite3ExprListDelete(db, p->x.pList);
   61133     }
   61134   }
   61135   if( !ExprHasProperty(p, EP_Static) ){
   61136     sqlite3DbFree(db, p);
   61137   }
   61138 }
   61139 
   61140 /*
   61141 ** Return the number of bytes allocated for the expression structure
   61142 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
   61143 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
   61144 */
   61145 static int exprStructSize(Expr *p){
   61146   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
   61147   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
   61148   return EXPR_FULLSIZE;
   61149 }
   61150 
   61151 /*
   61152 ** The dupedExpr*Size() routines each return the number of bytes required
   61153 ** to store a copy of an expression or expression tree.  They differ in
   61154 ** how much of the tree is measured.
   61155 **
   61156 **     dupedExprStructSize()     Size of only the Expr structure
   61157 **     dupedExprNodeSize()       Size of Expr + space for token
   61158 **     dupedExprSize()           Expr + token + subtree components
   61159 **
   61160 ***************************************************************************
   61161 **
   61162 ** The dupedExprStructSize() function returns two values OR-ed together:
   61163 ** (1) the space required for a copy of the Expr structure only and
   61164 ** (2) the EP_xxx flags that indicate what the structure size should be.
   61165 ** The return values is always one of:
   61166 **
   61167 **      EXPR_FULLSIZE
   61168 **      EXPR_REDUCEDSIZE   | EP_Reduced
   61169 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
   61170 **
   61171 ** The size of the structure can be found by masking the return value
   61172 ** of this routine with 0xfff.  The flags can be found by masking the
   61173 ** return value with EP_Reduced|EP_TokenOnly.
   61174 **
   61175 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
   61176 ** (unreduced) Expr objects as they or originally constructed by the parser.
   61177 ** During expression analysis, extra information is computed and moved into
   61178 ** later parts of teh Expr object and that extra information might get chopped
   61179 ** off if the expression is reduced.  Note also that it does not work to
   61180 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
   61181 ** to reduce a pristine expression tree from the parser.  The implementation
   61182 ** of dupedExprStructSize() contain multiple assert() statements that attempt
   61183 ** to enforce this constraint.
   61184 */
   61185 static int dupedExprStructSize(Expr *p, int flags){
   61186   int nSize;
   61187   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
   61188   if( 0==(flags&EXPRDUP_REDUCE) ){
   61189     nSize = EXPR_FULLSIZE;
   61190   }else{
   61191     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
   61192     assert( !ExprHasProperty(p, EP_FromJoin) );
   61193     assert( (p->flags2 & EP2_MallocedToken)==0 );
   61194     assert( (p->flags2 & EP2_Irreducible)==0 );
   61195     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
   61196       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
   61197     }else{
   61198       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
   61199     }
   61200   }
   61201   return nSize;
   61202 }
   61203 
   61204 /*
   61205 ** This function returns the space in bytes required to store the copy
   61206 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
   61207 ** string is defined.)
   61208 */
   61209 static int dupedExprNodeSize(Expr *p, int flags){
   61210   int nByte = dupedExprStructSize(p, flags) & 0xfff;
   61211   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
   61212     nByte += sqlite3Strlen30(p->u.zToken)+1;
   61213   }
   61214   return ROUND8(nByte);
   61215 }
   61216 
   61217 /*
   61218 ** Return the number of bytes required to create a duplicate of the
   61219 ** expression passed as the first argument. The second argument is a
   61220 ** mask containing EXPRDUP_XXX flags.
   61221 **
   61222 ** The value returned includes space to create a copy of the Expr struct
   61223 ** itself and the buffer referred to by Expr.u.zToken, if any.
   61224 **
   61225 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
   61226 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
   61227 ** and Expr.pRight variables (but not for any structures pointed to or
   61228 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
   61229 */
   61230 static int dupedExprSize(Expr *p, int flags){
   61231   int nByte = 0;
   61232   if( p ){
   61233     nByte = dupedExprNodeSize(p, flags);
   61234     if( flags&EXPRDUP_REDUCE ){
   61235       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
   61236     }
   61237   }
   61238   return nByte;
   61239 }
   61240 
   61241 /*
   61242 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
   61243 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
   61244 ** to store the copy of expression p, the copies of p->u.zToken
   61245 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
   61246 ** if any. Before returning, *pzBuffer is set to the first byte passed the
   61247 ** portion of the buffer copied into by this function.
   61248 */
   61249 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
   61250   Expr *pNew = 0;                      /* Value to return */
   61251   if( p ){
   61252     const int isReduced = (flags&EXPRDUP_REDUCE);
   61253     u8 *zAlloc;
   61254     u32 staticFlag = 0;
   61255 
   61256     assert( pzBuffer==0 || isReduced );
   61257 
   61258     /* Figure out where to write the new Expr structure. */
   61259     if( pzBuffer ){
   61260       zAlloc = *pzBuffer;
   61261       staticFlag = EP_Static;
   61262     }else{
   61263       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
   61264     }
   61265     pNew = (Expr *)zAlloc;
   61266 
   61267     if( pNew ){
   61268       /* Set nNewSize to the size allocated for the structure pointed to
   61269       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
   61270       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
   61271       ** by the copy of the p->u.zToken string (if any).
   61272       */
   61273       const unsigned nStructSize = dupedExprStructSize(p, flags);
   61274       const int nNewSize = nStructSize & 0xfff;
   61275       int nToken;
   61276       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
   61277         nToken = sqlite3Strlen30(p->u.zToken) + 1;
   61278       }else{
   61279         nToken = 0;
   61280       }
   61281       if( isReduced ){
   61282         assert( ExprHasProperty(p, EP_Reduced)==0 );
   61283         memcpy(zAlloc, p, nNewSize);
   61284       }else{
   61285         int nSize = exprStructSize(p);
   61286         memcpy(zAlloc, p, nSize);
   61287         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
   61288       }
   61289 
   61290       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
   61291       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
   61292       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
   61293       pNew->flags |= staticFlag;
   61294 
   61295       /* Copy the p->u.zToken string, if any. */
   61296       if( nToken ){
   61297         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
   61298         memcpy(zToken, p->u.zToken, nToken);
   61299       }
   61300 
   61301       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
   61302         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
   61303         if( ExprHasProperty(p, EP_xIsSelect) ){
   61304           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
   61305         }else{
   61306           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
   61307         }
   61308       }
   61309 
   61310       /* Fill in pNew->pLeft and pNew->pRight. */
   61311       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
   61312         zAlloc += dupedExprNodeSize(p, flags);
   61313         if( ExprHasProperty(pNew, EP_Reduced) ){
   61314           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
   61315           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
   61316         }
   61317         if( pzBuffer ){
   61318           *pzBuffer = zAlloc;
   61319         }
   61320       }else{
   61321         pNew->flags2 = 0;
   61322         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
   61323           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
   61324           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
   61325         }
   61326       }
   61327 
   61328     }
   61329   }
   61330   return pNew;
   61331 }
   61332 
   61333 /*
   61334 ** The following group of routines make deep copies of expressions,
   61335 ** expression lists, ID lists, and select statements.  The copies can
   61336 ** be deleted (by being passed to their respective ...Delete() routines)
   61337 ** without effecting the originals.
   61338 **
   61339 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
   61340 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
   61341 ** by subsequent calls to sqlite*ListAppend() routines.
   61342 **
   61343 ** Any tables that the SrcList might point to are not duplicated.
   61344 **
   61345 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
   61346 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
   61347 ** truncated version of the usual Expr structure that will be stored as
   61348 ** part of the in-memory representation of the database schema.
   61349 */
   61350 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
   61351   return exprDup(db, p, flags, 0);
   61352 }
   61353 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
   61354   ExprList *pNew;
   61355   struct ExprList_item *pItem, *pOldItem;
   61356   int i;
   61357   if( p==0 ) return 0;
   61358   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
   61359   if( pNew==0 ) return 0;
   61360   pNew->iECursor = 0;
   61361   pNew->nExpr = pNew->nAlloc = p->nExpr;
   61362   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
   61363   if( pItem==0 ){
   61364     sqlite3DbFree(db, pNew);
   61365     return 0;
   61366   }
   61367   pOldItem = p->a;
   61368   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
   61369     Expr *pOldExpr = pOldItem->pExpr;
   61370     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
   61371     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   61372     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
   61373     pItem->sortOrder = pOldItem->sortOrder;
   61374     pItem->done = 0;
   61375     pItem->iCol = pOldItem->iCol;
   61376     pItem->iAlias = pOldItem->iAlias;
   61377   }
   61378   return pNew;
   61379 }
   61380 
   61381 /*
   61382 ** If cursors, triggers, views and subqueries are all omitted from
   61383 ** the build, then none of the following routines, except for
   61384 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
   61385 ** called with a NULL argument.
   61386 */
   61387 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
   61388  || !defined(SQLITE_OMIT_SUBQUERY)
   61389 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
   61390   SrcList *pNew;
   61391   int i;
   61392   int nByte;
   61393   if( p==0 ) return 0;
   61394   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
   61395   pNew = sqlite3DbMallocRaw(db, nByte );
   61396   if( pNew==0 ) return 0;
   61397   pNew->nSrc = pNew->nAlloc = p->nSrc;
   61398   for(i=0; i<p->nSrc; i++){
   61399     struct SrcList_item *pNewItem = &pNew->a[i];
   61400     struct SrcList_item *pOldItem = &p->a[i];
   61401     Table *pTab;
   61402     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
   61403     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   61404     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
   61405     pNewItem->jointype = pOldItem->jointype;
   61406     pNewItem->iCursor = pOldItem->iCursor;
   61407     pNewItem->isPopulated = pOldItem->isPopulated;
   61408     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
   61409     pNewItem->notIndexed = pOldItem->notIndexed;
   61410     pNewItem->pIndex = pOldItem->pIndex;
   61411     pTab = pNewItem->pTab = pOldItem->pTab;
   61412     if( pTab ){
   61413       pTab->nRef++;
   61414     }
   61415     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
   61416     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
   61417     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
   61418     pNewItem->colUsed = pOldItem->colUsed;
   61419   }
   61420   return pNew;
   61421 }
   61422 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
   61423   IdList *pNew;
   61424   int i;
   61425   if( p==0 ) return 0;
   61426   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
   61427   if( pNew==0 ) return 0;
   61428   pNew->nId = pNew->nAlloc = p->nId;
   61429   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
   61430   if( pNew->a==0 ){
   61431     sqlite3DbFree(db, pNew);
   61432     return 0;
   61433   }
   61434   for(i=0; i<p->nId; i++){
   61435     struct IdList_item *pNewItem = &pNew->a[i];
   61436     struct IdList_item *pOldItem = &p->a[i];
   61437     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   61438     pNewItem->idx = pOldItem->idx;
   61439   }
   61440   return pNew;
   61441 }
   61442 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
   61443   Select *pNew;
   61444   if( p==0 ) return 0;
   61445   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
   61446   if( pNew==0 ) return 0;
   61447   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
   61448   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
   61449   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
   61450   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
   61451   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
   61452   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
   61453   pNew->op = p->op;
   61454   pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
   61455   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
   61456   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
   61457   pNew->iLimit = 0;
   61458   pNew->iOffset = 0;
   61459   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
   61460   pNew->pRightmost = 0;
   61461   pNew->addrOpenEphm[0] = -1;
   61462   pNew->addrOpenEphm[1] = -1;
   61463   pNew->addrOpenEphm[2] = -1;
   61464   return pNew;
   61465 }
   61466 #else
   61467 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
   61468   assert( p==0 );
   61469   return 0;
   61470 }
   61471 #endif
   61472 
   61473 
   61474 /*
   61475 ** Add a new element to the end of an expression list.  If pList is
   61476 ** initially NULL, then create a new expression list.
   61477 **
   61478 ** If a memory allocation error occurs, the entire list is freed and
   61479 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
   61480 ** that the new entry was successfully appended.
   61481 */
   61482 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
   61483   Parse *pParse,          /* Parsing context */
   61484   ExprList *pList,        /* List to which to append. Might be NULL */
   61485   Expr *pExpr             /* Expression to be appended. Might be NULL */
   61486 ){
   61487   sqlite3 *db = pParse->db;
   61488   if( pList==0 ){
   61489     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
   61490     if( pList==0 ){
   61491       goto no_mem;
   61492     }
   61493     assert( pList->nAlloc==0 );
   61494   }
   61495   if( pList->nAlloc<=pList->nExpr ){
   61496     struct ExprList_item *a;
   61497     int n = pList->nAlloc*2 + 4;
   61498     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
   61499     if( a==0 ){
   61500       goto no_mem;
   61501     }
   61502     pList->a = a;
   61503     pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
   61504   }
   61505   assert( pList->a!=0 );
   61506   if( 1 ){
   61507     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
   61508     memset(pItem, 0, sizeof(*pItem));
   61509     pItem->pExpr = pExpr;
   61510   }
   61511   return pList;
   61512 
   61513 no_mem:
   61514   /* Avoid leaking memory if malloc has failed. */
   61515   sqlite3ExprDelete(db, pExpr);
   61516   sqlite3ExprListDelete(db, pList);
   61517   return 0;
   61518 }
   61519 
   61520 /*
   61521 ** Set the ExprList.a[].zName element of the most recently added item
   61522 ** on the expression list.
   61523 **
   61524 ** pList might be NULL following an OOM error.  But pName should never be
   61525 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
   61526 ** is set.
   61527 */
   61528 SQLITE_PRIVATE void sqlite3ExprListSetName(
   61529   Parse *pParse,          /* Parsing context */
   61530   ExprList *pList,        /* List to which to add the span. */
   61531   Token *pName,           /* Name to be added */
   61532   int dequote             /* True to cause the name to be dequoted */
   61533 ){
   61534   assert( pList!=0 || pParse->db->mallocFailed!=0 );
   61535   if( pList ){
   61536     struct ExprList_item *pItem;
   61537     assert( pList->nExpr>0 );
   61538     pItem = &pList->a[pList->nExpr-1];
   61539     assert( pItem->zName==0 );
   61540     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
   61541     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
   61542   }
   61543 }
   61544 
   61545 /*
   61546 ** Set the ExprList.a[].zSpan element of the most recently added item
   61547 ** on the expression list.
   61548 **
   61549 ** pList might be NULL following an OOM error.  But pSpan should never be
   61550 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
   61551 ** is set.
   61552 */
   61553 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
   61554   Parse *pParse,          /* Parsing context */
   61555   ExprList *pList,        /* List to which to add the span. */
   61556   ExprSpan *pSpan         /* The span to be added */
   61557 ){
   61558   sqlite3 *db = pParse->db;
   61559   assert( pList!=0 || db->mallocFailed!=0 );
   61560   if( pList ){
   61561     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
   61562     assert( pList->nExpr>0 );
   61563     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
   61564     sqlite3DbFree(db, pItem->zSpan);
   61565     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
   61566                                     (int)(pSpan->zEnd - pSpan->zStart));
   61567   }
   61568 }
   61569 
   61570 /*
   61571 ** If the expression list pEList contains more than iLimit elements,
   61572 ** leave an error message in pParse.
   61573 */
   61574 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
   61575   Parse *pParse,
   61576   ExprList *pEList,
   61577   const char *zObject
   61578 ){
   61579   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
   61580   testcase( pEList && pEList->nExpr==mx );
   61581   testcase( pEList && pEList->nExpr==mx+1 );
   61582   if( pEList && pEList->nExpr>mx ){
   61583     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
   61584   }
   61585 }
   61586 
   61587 /*
   61588 ** Delete an entire expression list.
   61589 */
   61590 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
   61591   int i;
   61592   struct ExprList_item *pItem;
   61593   if( pList==0 ) return;
   61594   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
   61595   assert( pList->nExpr<=pList->nAlloc );
   61596   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
   61597     sqlite3ExprDelete(db, pItem->pExpr);
   61598     sqlite3DbFree(db, pItem->zName);
   61599     sqlite3DbFree(db, pItem->zSpan);
   61600   }
   61601   sqlite3DbFree(db, pList->a);
   61602   sqlite3DbFree(db, pList);
   61603 }
   61604 
   61605 /*
   61606 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
   61607 ** to an integer.  These routines are checking an expression to see
   61608 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
   61609 ** not constant.
   61610 **
   61611 ** These callback routines are used to implement the following:
   61612 **
   61613 **     sqlite3ExprIsConstant()
   61614 **     sqlite3ExprIsConstantNotJoin()
   61615 **     sqlite3ExprIsConstantOrFunction()
   61616 **
   61617 */
   61618 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
   61619 
   61620   /* If pWalker->u.i is 3 then any term of the expression that comes from
   61621   ** the ON or USING clauses of a join disqualifies the expression
   61622   ** from being considered constant. */
   61623   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
   61624     pWalker->u.i = 0;
   61625     return WRC_Abort;
   61626   }
   61627 
   61628   switch( pExpr->op ){
   61629     /* Consider functions to be constant if all their arguments are constant
   61630     ** and pWalker->u.i==2 */
   61631     case TK_FUNCTION:
   61632       if( pWalker->u.i==2 ) return 0;
   61633       /* Fall through */
   61634     case TK_ID:
   61635     case TK_COLUMN:
   61636     case TK_AGG_FUNCTION:
   61637     case TK_AGG_COLUMN:
   61638       testcase( pExpr->op==TK_ID );
   61639       testcase( pExpr->op==TK_COLUMN );
   61640       testcase( pExpr->op==TK_AGG_FUNCTION );
   61641       testcase( pExpr->op==TK_AGG_COLUMN );
   61642       pWalker->u.i = 0;
   61643       return WRC_Abort;
   61644     default:
   61645       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
   61646       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
   61647       return WRC_Continue;
   61648   }
   61649 }
   61650 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
   61651   UNUSED_PARAMETER(NotUsed);
   61652   pWalker->u.i = 0;
   61653   return WRC_Abort;
   61654 }
   61655 static int exprIsConst(Expr *p, int initFlag){
   61656   Walker w;
   61657   w.u.i = initFlag;
   61658   w.xExprCallback = exprNodeIsConstant;
   61659   w.xSelectCallback = selectNodeIsConstant;
   61660   sqlite3WalkExpr(&w, p);
   61661   return w.u.i;
   61662 }
   61663 
   61664 /*
   61665 ** Walk an expression tree.  Return 1 if the expression is constant
   61666 ** and 0 if it involves variables or function calls.
   61667 **
   61668 ** For the purposes of this function, a double-quoted string (ex: "abc")
   61669 ** is considered a variable but a single-quoted string (ex: 'abc') is
   61670 ** a constant.
   61671 */
   61672 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
   61673   return exprIsConst(p, 1);
   61674 }
   61675 
   61676 /*
   61677 ** Walk an expression tree.  Return 1 if the expression is constant
   61678 ** that does no originate from the ON or USING clauses of a join.
   61679 ** Return 0 if it involves variables or function calls or terms from
   61680 ** an ON or USING clause.
   61681 */
   61682 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
   61683   return exprIsConst(p, 3);
   61684 }
   61685 
   61686 /*
   61687 ** Walk an expression tree.  Return 1 if the expression is constant
   61688 ** or a function call with constant arguments.  Return and 0 if there
   61689 ** are any variables.
   61690 **
   61691 ** For the purposes of this function, a double-quoted string (ex: "abc")
   61692 ** is considered a variable but a single-quoted string (ex: 'abc') is
   61693 ** a constant.
   61694 */
   61695 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
   61696   return exprIsConst(p, 2);
   61697 }
   61698 
   61699 /*
   61700 ** If the expression p codes a constant integer that is small enough
   61701 ** to fit in a 32-bit integer, return 1 and put the value of the integer
   61702 ** in *pValue.  If the expression is not an integer or if it is too big
   61703 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
   61704 */
   61705 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
   61706   int rc = 0;
   61707   if( p->flags & EP_IntValue ){
   61708     *pValue = p->u.iValue;
   61709     return 1;
   61710   }
   61711   switch( p->op ){
   61712     case TK_INTEGER: {
   61713       rc = sqlite3GetInt32(p->u.zToken, pValue);
   61714       assert( rc==0 );
   61715       break;
   61716     }
   61717     case TK_UPLUS: {
   61718       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
   61719       break;
   61720     }
   61721     case TK_UMINUS: {
   61722       int v;
   61723       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
   61724         *pValue = -v;
   61725         rc = 1;
   61726       }
   61727       break;
   61728     }
   61729     default: break;
   61730   }
   61731   if( rc ){
   61732     assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
   61733                || (p->flags2 & EP2_MallocedToken)==0 );
   61734     p->op = TK_INTEGER;
   61735     p->flags |= EP_IntValue;
   61736     p->u.iValue = *pValue;
   61737   }
   61738   return rc;
   61739 }
   61740 
   61741 /*
   61742 ** Return FALSE if there is no chance that the expression can be NULL.
   61743 **
   61744 ** If the expression might be NULL or if the expression is too complex
   61745 ** to tell return TRUE.
   61746 **
   61747 ** This routine is used as an optimization, to skip OP_IsNull opcodes
   61748 ** when we know that a value cannot be NULL.  Hence, a false positive
   61749 ** (returning TRUE when in fact the expression can never be NULL) might
   61750 ** be a small performance hit but is otherwise harmless.  On the other
   61751 ** hand, a false negative (returning FALSE when the result could be NULL)
   61752 ** will likely result in an incorrect answer.  So when in doubt, return
   61753 ** TRUE.
   61754 */
   61755 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
   61756   u8 op;
   61757   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
   61758   op = p->op;
   61759   if( op==TK_REGISTER ) op = p->op2;
   61760   switch( op ){
   61761     case TK_INTEGER:
   61762     case TK_STRING:
   61763     case TK_FLOAT:
   61764     case TK_BLOB:
   61765       return 0;
   61766     default:
   61767       return 1;
   61768   }
   61769 }
   61770 
   61771 /*
   61772 ** Generate an OP_IsNull instruction that tests register iReg and jumps
   61773 ** to location iDest if the value in iReg is NULL.  The value in iReg
   61774 ** was computed by pExpr.  If we can look at pExpr at compile-time and
   61775 ** determine that it can never generate a NULL, then the OP_IsNull operation
   61776 ** can be omitted.
   61777 */
   61778 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
   61779   Vdbe *v,            /* The VDBE under construction */
   61780   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
   61781   int iReg,           /* Test the value in this register for NULL */
   61782   int iDest           /* Jump here if the value is null */
   61783 ){
   61784   if( sqlite3ExprCanBeNull(pExpr) ){
   61785     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
   61786   }
   61787 }
   61788 
   61789 /*
   61790 ** Return TRUE if the given expression is a constant which would be
   61791 ** unchanged by OP_Affinity with the affinity given in the second
   61792 ** argument.
   61793 **
   61794 ** This routine is used to determine if the OP_Affinity operation
   61795 ** can be omitted.  When in doubt return FALSE.  A false negative
   61796 ** is harmless.  A false positive, however, can result in the wrong
   61797 ** answer.
   61798 */
   61799 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
   61800   u8 op;
   61801   if( aff==SQLITE_AFF_NONE ) return 1;
   61802   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
   61803   op = p->op;
   61804   if( op==TK_REGISTER ) op = p->op2;
   61805   switch( op ){
   61806     case TK_INTEGER: {
   61807       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
   61808     }
   61809     case TK_FLOAT: {
   61810       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
   61811     }
   61812     case TK_STRING: {
   61813       return aff==SQLITE_AFF_TEXT;
   61814     }
   61815     case TK_BLOB: {
   61816       return 1;
   61817     }
   61818     case TK_COLUMN: {
   61819       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
   61820       return p->iColumn<0
   61821           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
   61822     }
   61823     default: {
   61824       return 0;
   61825     }
   61826   }
   61827 }
   61828 
   61829 /*
   61830 ** Return TRUE if the given string is a row-id column name.
   61831 */
   61832 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
   61833   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
   61834   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
   61835   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
   61836   return 0;
   61837 }
   61838 
   61839 /*
   61840 ** Return true if we are able to the IN operator optimization on a
   61841 ** query of the form
   61842 **
   61843 **       x IN (SELECT ...)
   61844 **
   61845 ** Where the SELECT... clause is as specified by the parameter to this
   61846 ** routine.
   61847 **
   61848 ** The Select object passed in has already been preprocessed and no
   61849 ** errors have been found.
   61850 */
   61851 #ifndef SQLITE_OMIT_SUBQUERY
   61852 static int isCandidateForInOpt(Select *p){
   61853   SrcList *pSrc;
   61854   ExprList *pEList;
   61855   Table *pTab;
   61856   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
   61857   if( p->pPrior ) return 0;              /* Not a compound SELECT */
   61858   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
   61859     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
   61860     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
   61861     return 0; /* No DISTINCT keyword and no aggregate functions */
   61862   }
   61863   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
   61864   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
   61865   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
   61866   if( p->pWhere ) return 0;              /* Has no WHERE clause */
   61867   pSrc = p->pSrc;
   61868   assert( pSrc!=0 );
   61869   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
   61870   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
   61871   pTab = pSrc->a[0].pTab;
   61872   if( NEVER(pTab==0) ) return 0;
   61873   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
   61874   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
   61875   pEList = p->pEList;
   61876   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
   61877   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
   61878   return 1;
   61879 }
   61880 #endif /* SQLITE_OMIT_SUBQUERY */
   61881 
   61882 /*
   61883 ** This function is used by the implementation of the IN (...) operator.
   61884 ** It's job is to find or create a b-tree structure that may be used
   61885 ** either to test for membership of the (...) set or to iterate through
   61886 ** its members, skipping duplicates.
   61887 **
   61888 ** The index of the cursor opened on the b-tree (database table, database index
   61889 ** or ephermal table) is stored in pX->iTable before this function returns.
   61890 ** The returned value of this function indicates the b-tree type, as follows:
   61891 **
   61892 **   IN_INDEX_ROWID - The cursor was opened on a database table.
   61893 **   IN_INDEX_INDEX - The cursor was opened on a database index.
   61894 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
   61895 **                    populated epheremal table.
   61896 **
   61897 ** An existing b-tree may only be used if the SELECT is of the simple
   61898 ** form:
   61899 **
   61900 **     SELECT <column> FROM <table>
   61901 **
   61902 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
   61903 ** through the set members, skipping any duplicates. In this case an
   61904 ** epheremal table must be used unless the selected <column> is guaranteed
   61905 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
   61906 ** has a UNIQUE constraint or UNIQUE index.
   61907 **
   61908 ** If the prNotFound parameter is not 0, then the b-tree will be used
   61909 ** for fast set membership tests. In this case an epheremal table must
   61910 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
   61911 ** be found with <column> as its left-most column.
   61912 **
   61913 ** When the b-tree is being used for membership tests, the calling function
   61914 ** needs to know whether or not the structure contains an SQL NULL
   61915 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
   61916 ** If there is any chance that the (...) might contain a NULL value at
   61917 ** runtime, then a register is allocated and the register number written
   61918 ** to *prNotFound. If there is no chance that the (...) contains a
   61919 ** NULL value, then *prNotFound is left unchanged.
   61920 **
   61921 ** If a register is allocated and its location stored in *prNotFound, then
   61922 ** its initial value is NULL.  If the (...) does not remain constant
   61923 ** for the duration of the query (i.e. the SELECT within the (...)
   61924 ** is a correlated subquery) then the value of the allocated register is
   61925 ** reset to NULL each time the subquery is rerun. This allows the
   61926 ** caller to use vdbe code equivalent to the following:
   61927 **
   61928 **   if( register==NULL ){
   61929 **     has_null = <test if data structure contains null>
   61930 **     register = 1
   61931 **   }
   61932 **
   61933 ** in order to avoid running the <test if data structure contains null>
   61934 ** test more often than is necessary.
   61935 */
   61936 #ifndef SQLITE_OMIT_SUBQUERY
   61937 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
   61938   Select *p;                            /* SELECT to the right of IN operator */
   61939   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
   61940   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
   61941   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
   61942 
   61943   assert( pX->op==TK_IN );
   61944 
   61945   /* Check to see if an existing table or index can be used to
   61946   ** satisfy the query.  This is preferable to generating a new
   61947   ** ephemeral table.
   61948   */
   61949   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
   61950   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
   61951     sqlite3 *db = pParse->db;              /* Database connection */
   61952     Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
   61953     int iCol = pExpr->iColumn;             /* Index of column <column> */
   61954     Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
   61955     Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
   61956     int iDb;                               /* Database idx for pTab */
   61957 
   61958     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
   61959     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   61960     sqlite3CodeVerifySchema(pParse, iDb);
   61961     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   61962 
   61963     /* This function is only called from two places. In both cases the vdbe
   61964     ** has already been allocated. So assume sqlite3GetVdbe() is always
   61965     ** successful here.
   61966     */
   61967     assert(v);
   61968     if( iCol<0 ){
   61969       int iMem = ++pParse->nMem;
   61970       int iAddr;
   61971 
   61972       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
   61973       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
   61974 
   61975       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
   61976       eType = IN_INDEX_ROWID;
   61977 
   61978       sqlite3VdbeJumpHere(v, iAddr);
   61979     }else{
   61980       Index *pIdx;                         /* Iterator variable */
   61981 
   61982       /* The collation sequence used by the comparison. If an index is to
   61983       ** be used in place of a temp-table, it must be ordered according
   61984       ** to this collation sequence.  */
   61985       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
   61986 
   61987       /* Check that the affinity that will be used to perform the
   61988       ** comparison is the same as the affinity of the column. If
   61989       ** it is not, it is not possible to use any index.
   61990       */
   61991       char aff = comparisonAffinity(pX);
   61992       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
   61993 
   61994       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
   61995         if( (pIdx->aiColumn[0]==iCol)
   61996          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
   61997          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
   61998         ){
   61999           int iMem = ++pParse->nMem;
   62000           int iAddr;
   62001           char *pKey;
   62002 
   62003           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
   62004           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
   62005           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
   62006 
   62007           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
   62008                                pKey,P4_KEYINFO_HANDOFF);
   62009           VdbeComment((v, "%s", pIdx->zName));
   62010           eType = IN_INDEX_INDEX;
   62011 
   62012           sqlite3VdbeJumpHere(v, iAddr);
   62013           if( prNotFound && !pTab->aCol[iCol].notNull ){
   62014             *prNotFound = ++pParse->nMem;
   62015           }
   62016         }
   62017       }
   62018     }
   62019   }
   62020 
   62021   if( eType==0 ){
   62022     /* Could not found an existing table or index to use as the RHS b-tree.
   62023     ** We will have to generate an ephemeral table to do the job.
   62024     */
   62025     int rMayHaveNull = 0;
   62026     eType = IN_INDEX_EPH;
   62027     if( prNotFound ){
   62028       *prNotFound = rMayHaveNull = ++pParse->nMem;
   62029     }else if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
   62030       eType = IN_INDEX_ROWID;
   62031     }
   62032     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
   62033   }else{
   62034     pX->iTable = iTab;
   62035   }
   62036   return eType;
   62037 }
   62038 #endif
   62039 
   62040 /*
   62041 ** Generate code for scalar subqueries used as an expression
   62042 ** and IN operators.  Examples:
   62043 **
   62044 **     (SELECT a FROM b)          -- subquery
   62045 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
   62046 **     x IN (4,5,11)              -- IN operator with list on right-hand side
   62047 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
   62048 **
   62049 ** The pExpr parameter describes the expression that contains the IN
   62050 ** operator or subquery.
   62051 **
   62052 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
   62053 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
   62054 ** to some integer key column of a table B-Tree. In this case, use an
   62055 ** intkey B-Tree to store the set of IN(...) values instead of the usual
   62056 ** (slower) variable length keys B-Tree.
   62057 **
   62058 ** If rMayHaveNull is non-zero, that means that the operation is an IN
   62059 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
   62060 ** Furthermore, the IN is in a WHERE clause and that we really want
   62061 ** to iterate over the RHS of the IN operator in order to quickly locate
   62062 ** all corresponding LHS elements.  All this routine does is initialize
   62063 ** the register given by rMayHaveNull to NULL.  Calling routines will take
   62064 ** care of changing this register value to non-NULL if the RHS is NULL-free.
   62065 **
   62066 ** If rMayHaveNull is zero, that means that the subquery is being used
   62067 ** for membership testing only.  There is no need to initialize any
   62068 ** registers to indicate the presense or absence of NULLs on the RHS.
   62069 **
   62070 ** For a SELECT or EXISTS operator, return the register that holds the
   62071 ** result.  For IN operators or if an error occurs, the return value is 0.
   62072 */
   62073 #ifndef SQLITE_OMIT_SUBQUERY
   62074 SQLITE_PRIVATE int sqlite3CodeSubselect(
   62075   Parse *pParse,          /* Parsing context */
   62076   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
   62077   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
   62078   int isRowid             /* If true, LHS of IN operator is a rowid */
   62079 ){
   62080   int testAddr = 0;                       /* One-time test address */
   62081   int rReg = 0;                           /* Register storing resulting */
   62082   Vdbe *v = sqlite3GetVdbe(pParse);
   62083   if( NEVER(v==0) ) return 0;
   62084   sqlite3ExprCachePush(pParse);
   62085 
   62086   /* This code must be run in its entirety every time it is encountered
   62087   ** if any of the following is true:
   62088   **
   62089   **    *  The right-hand side is a correlated subquery
   62090   **    *  The right-hand side is an expression list containing variables
   62091   **    *  We are inside a trigger
   62092   **
   62093   ** If all of the above are false, then we can run this code just once
   62094   ** save the results, and reuse the same result on subsequent invocations.
   62095   */
   62096   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
   62097     int mem = ++pParse->nMem;
   62098     sqlite3VdbeAddOp1(v, OP_If, mem);
   62099     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
   62100     assert( testAddr>0 || pParse->db->mallocFailed );
   62101   }
   62102 
   62103   switch( pExpr->op ){
   62104     case TK_IN: {
   62105       char affinity;
   62106       KeyInfo keyInfo;
   62107       int addr;        /* Address of OP_OpenEphemeral instruction */
   62108       Expr *pLeft = pExpr->pLeft;
   62109 
   62110       if( rMayHaveNull ){
   62111         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
   62112       }
   62113 
   62114       affinity = sqlite3ExprAffinity(pLeft);
   62115 
   62116       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
   62117       ** expression it is handled the same way.  An ephemeral table is
   62118       ** filled with single-field index keys representing the results
   62119       ** from the SELECT or the <exprlist>.
   62120       **
   62121       ** If the 'x' expression is a column value, or the SELECT...
   62122       ** statement returns a column value, then the affinity of that
   62123       ** column is used to build the index keys. If both 'x' and the
   62124       ** SELECT... statement are columns, then numeric affinity is used
   62125       ** if either column has NUMERIC or INTEGER affinity. If neither
   62126       ** 'x' nor the SELECT... statement are columns, then numeric affinity
   62127       ** is used.
   62128       */
   62129       pExpr->iTable = pParse->nTab++;
   62130       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
   62131       memset(&keyInfo, 0, sizeof(keyInfo));
   62132       keyInfo.nField = 1;
   62133 
   62134       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   62135         /* Case 1:     expr IN (SELECT ...)
   62136         **
   62137         ** Generate code to write the results of the select into the temporary
   62138         ** table allocated and opened above.
   62139         */
   62140         SelectDest dest;
   62141         ExprList *pEList;
   62142 
   62143         assert( !isRowid );
   62144         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
   62145         dest.affinity = (u8)affinity;
   62146         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
   62147         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
   62148           return 0;
   62149         }
   62150         pEList = pExpr->x.pSelect->pEList;
   62151         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
   62152           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
   62153               pEList->a[0].pExpr);
   62154         }
   62155       }else if( pExpr->x.pList!=0 ){
   62156         /* Case 2:     expr IN (exprlist)
   62157         **
   62158         ** For each expression, build an index key from the evaluation and
   62159         ** store it in the temporary table. If <expr> is a column, then use
   62160         ** that columns affinity when building index keys. If <expr> is not
   62161         ** a column, use numeric affinity.
   62162         */
   62163         int i;
   62164         ExprList *pList = pExpr->x.pList;
   62165         struct ExprList_item *pItem;
   62166         int r1, r2, r3;
   62167 
   62168         if( !affinity ){
   62169           affinity = SQLITE_AFF_NONE;
   62170         }
   62171         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
   62172 
   62173         /* Loop through each expression in <exprlist>. */
   62174         r1 = sqlite3GetTempReg(pParse);
   62175         r2 = sqlite3GetTempReg(pParse);
   62176         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
   62177         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
   62178           Expr *pE2 = pItem->pExpr;
   62179           int iValToIns;
   62180 
   62181           /* If the expression is not constant then we will need to
   62182           ** disable the test that was generated above that makes sure
   62183           ** this code only executes once.  Because for a non-constant
   62184           ** expression we need to rerun this code each time.
   62185           */
   62186           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
   62187             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
   62188             testAddr = 0;
   62189           }
   62190 
   62191           /* Evaluate the expression and insert it into the temp table */
   62192           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
   62193             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
   62194           }else{
   62195             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
   62196             if( isRowid ){
   62197               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
   62198                                 sqlite3VdbeCurrentAddr(v)+2);
   62199               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
   62200             }else{
   62201               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
   62202               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
   62203               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
   62204             }
   62205           }
   62206         }
   62207         sqlite3ReleaseTempReg(pParse, r1);
   62208         sqlite3ReleaseTempReg(pParse, r2);
   62209       }
   62210       if( !isRowid ){
   62211         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
   62212       }
   62213       break;
   62214     }
   62215 
   62216     case TK_EXISTS:
   62217     case TK_SELECT:
   62218     default: {
   62219       /* If this has to be a scalar SELECT.  Generate code to put the
   62220       ** value of this select in a memory cell and record the number
   62221       ** of the memory cell in iColumn.  If this is an EXISTS, write
   62222       ** an integer 0 (not exists) or 1 (exists) into a memory cell
   62223       ** and record that memory cell in iColumn.
   62224       */
   62225       static const Token one = { "1", 1 };  /* Token for literal value 1 */
   62226       Select *pSel;                         /* SELECT statement to encode */
   62227       SelectDest dest;                      /* How to deal with SELECt result */
   62228 
   62229       testcase( pExpr->op==TK_EXISTS );
   62230       testcase( pExpr->op==TK_SELECT );
   62231       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
   62232 
   62233       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
   62234       pSel = pExpr->x.pSelect;
   62235       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
   62236       if( pExpr->op==TK_SELECT ){
   62237         dest.eDest = SRT_Mem;
   62238         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
   62239         VdbeComment((v, "Init subquery result"));
   62240       }else{
   62241         dest.eDest = SRT_Exists;
   62242         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
   62243         VdbeComment((v, "Init EXISTS result"));
   62244       }
   62245       sqlite3ExprDelete(pParse->db, pSel->pLimit);
   62246       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
   62247       if( sqlite3Select(pParse, pSel, &dest) ){
   62248         return 0;
   62249       }
   62250       rReg = dest.iParm;
   62251       ExprSetIrreducible(pExpr);
   62252       break;
   62253     }
   62254   }
   62255 
   62256   if( testAddr ){
   62257     sqlite3VdbeJumpHere(v, testAddr-1);
   62258   }
   62259   sqlite3ExprCachePop(pParse, 1);
   62260 
   62261   return rReg;
   62262 }
   62263 #endif /* SQLITE_OMIT_SUBQUERY */
   62264 
   62265 #ifndef SQLITE_OMIT_SUBQUERY
   62266 /*
   62267 ** Generate code for an IN expression.
   62268 **
   62269 **      x IN (SELECT ...)
   62270 **      x IN (value, value, ...)
   62271 **
   62272 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
   62273 ** is an array of zero or more values.  The expression is true if the LHS is
   62274 ** contained within the RHS.  The value of the expression is unknown (NULL)
   62275 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
   62276 ** RHS contains one or more NULL values.
   62277 **
   62278 ** This routine generates code will jump to destIfFalse if the LHS is not
   62279 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
   62280 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
   62281 ** within the RHS then fall through.
   62282 */
   62283 static void sqlite3ExprCodeIN(
   62284   Parse *pParse,        /* Parsing and code generating context */
   62285   Expr *pExpr,          /* The IN expression */
   62286   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
   62287   int destIfNull        /* Jump here if the results are unknown due to NULLs */
   62288 ){
   62289   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
   62290   char affinity;        /* Comparison affinity to use */
   62291   int eType;            /* Type of the RHS */
   62292   int r1;               /* Temporary use register */
   62293   Vdbe *v;              /* Statement under construction */
   62294 
   62295   /* Compute the RHS.   After this step, the table with cursor
   62296   ** pExpr->iTable will contains the values that make up the RHS.
   62297   */
   62298   v = pParse->pVdbe;
   62299   assert( v!=0 );       /* OOM detected prior to this routine */
   62300   VdbeNoopComment((v, "begin IN expr"));
   62301   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
   62302 
   62303   /* Figure out the affinity to use to create a key from the results
   62304   ** of the expression. affinityStr stores a static string suitable for
   62305   ** P4 of OP_MakeRecord.
   62306   */
   62307   affinity = comparisonAffinity(pExpr);
   62308 
   62309   /* Code the LHS, the <expr> from "<expr> IN (...)".
   62310   */
   62311   sqlite3ExprCachePush(pParse);
   62312   r1 = sqlite3GetTempReg(pParse);
   62313   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
   62314   sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
   62315 
   62316 
   62317   if( eType==IN_INDEX_ROWID ){
   62318     /* In this case, the RHS is the ROWID of table b-tree
   62319     */
   62320     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
   62321     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
   62322   }else{
   62323     /* In this case, the RHS is an index b-tree.
   62324     */
   62325     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
   62326 
   62327     /* If the set membership test fails, then the result of the
   62328     ** "x IN (...)" expression must be either 0 or NULL. If the set
   62329     ** contains no NULL values, then the result is 0. If the set
   62330     ** contains one or more NULL values, then the result of the
   62331     ** expression is also NULL.
   62332     */
   62333     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
   62334       /* This branch runs if it is known at compile time that the RHS
   62335       ** cannot contain NULL values. This happens as the result
   62336       ** of a "NOT NULL" constraint in the database schema.
   62337       **
   62338       ** Also run this branch if NULL is equivalent to FALSE
   62339       ** for this particular IN operator.
   62340       */
   62341       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
   62342 
   62343     }else{
   62344       /* In this branch, the RHS of the IN might contain a NULL and
   62345       ** the presence of a NULL on the RHS makes a difference in the
   62346       ** outcome.
   62347       */
   62348       int j1, j2, j3;
   62349 
   62350       /* First check to see if the LHS is contained in the RHS.  If so,
   62351       ** then the presence of NULLs in the RHS does not matter, so jump
   62352       ** over all of the code that follows.
   62353       */
   62354       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
   62355 
   62356       /* Here we begin generating code that runs if the LHS is not
   62357       ** contained within the RHS.  Generate additional code that
   62358       ** tests the RHS for NULLs.  If the RHS contains a NULL then
   62359       ** jump to destIfNull.  If there are no NULLs in the RHS then
   62360       ** jump to destIfFalse.
   62361       */
   62362       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
   62363       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
   62364       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
   62365       sqlite3VdbeJumpHere(v, j3);
   62366       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
   62367       sqlite3VdbeJumpHere(v, j2);
   62368 
   62369       /* Jump to the appropriate target depending on whether or not
   62370       ** the RHS contains a NULL
   62371       */
   62372       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
   62373       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
   62374 
   62375       /* The OP_Found at the top of this branch jumps here when true,
   62376       ** causing the overall IN expression evaluation to fall through.
   62377       */
   62378       sqlite3VdbeJumpHere(v, j1);
   62379     }
   62380   }
   62381   sqlite3ReleaseTempReg(pParse, r1);
   62382   sqlite3ExprCachePop(pParse, 1);
   62383   VdbeComment((v, "end IN expr"));
   62384 }
   62385 #endif /* SQLITE_OMIT_SUBQUERY */
   62386 
   62387 /*
   62388 ** Duplicate an 8-byte value
   62389 */
   62390 static char *dup8bytes(Vdbe *v, const char *in){
   62391   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
   62392   if( out ){
   62393     memcpy(out, in, 8);
   62394   }
   62395   return out;
   62396 }
   62397 
   62398 /*
   62399 ** Generate an instruction that will put the floating point
   62400 ** value described by z[0..n-1] into register iMem.
   62401 **
   62402 ** The z[] string will probably not be zero-terminated.  But the
   62403 ** z[n] character is guaranteed to be something that does not look
   62404 ** like the continuation of the number.
   62405 */
   62406 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
   62407   if( ALWAYS(z!=0) ){
   62408     double value;
   62409     char *zV;
   62410     sqlite3AtoF(z, &value);
   62411     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
   62412     if( negateFlag ) value = -value;
   62413     zV = dup8bytes(v, (char*)&value);
   62414     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
   62415   }
   62416 }
   62417 
   62418 
   62419 /*
   62420 ** Generate an instruction that will put the integer describe by
   62421 ** text z[0..n-1] into register iMem.
   62422 **
   62423 ** The z[] string will probably not be zero-terminated.  But the
   62424 ** z[n] character is guaranteed to be something that does not look
   62425 ** like the continuation of the number.
   62426 */
   62427 static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
   62428   if( pExpr->flags & EP_IntValue ){
   62429     int i = pExpr->u.iValue;
   62430     if( negFlag ) i = -i;
   62431     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
   62432   }else{
   62433     const char *z = pExpr->u.zToken;
   62434     assert( z!=0 );
   62435     if( sqlite3FitsIn64Bits(z, negFlag) ){
   62436       i64 value;
   62437       char *zV;
   62438       sqlite3Atoi64(z, &value);
   62439       if( negFlag ) value = -value;
   62440       zV = dup8bytes(v, (char*)&value);
   62441       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
   62442     }else{
   62443       codeReal(v, z, negFlag, iMem);
   62444     }
   62445   }
   62446 }
   62447 
   62448 /*
   62449 ** Clear a cache entry.
   62450 */
   62451 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
   62452   if( p->tempReg ){
   62453     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
   62454       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
   62455     }
   62456     p->tempReg = 0;
   62457   }
   62458 }
   62459 
   62460 
   62461 /*
   62462 ** Record in the column cache that a particular column from a
   62463 ** particular table is stored in a particular register.
   62464 */
   62465 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
   62466   int i;
   62467   int minLru;
   62468   int idxLru;
   62469   struct yColCache *p;
   62470 
   62471   assert( iReg>0 );  /* Register numbers are always positive */
   62472   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
   62473 
   62474   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
   62475   ** for testing only - to verify that SQLite always gets the same answer
   62476   ** with and without the column cache.
   62477   */
   62478   if( pParse->db->flags & SQLITE_ColumnCache ) return;
   62479 
   62480   /* First replace any existing entry.
   62481   **
   62482   ** Actually, the way the column cache is currently used, we are guaranteed
   62483   ** that the object will never already be in cache.  Verify this guarantee.
   62484   */
   62485 #ifndef NDEBUG
   62486   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   62487 #if 0 /* This code wold remove the entry from the cache if it existed */
   62488     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
   62489       cacheEntryClear(pParse, p);
   62490       p->iLevel = pParse->iCacheLevel;
   62491       p->iReg = iReg;
   62492       p->lru = pParse->iCacheCnt++;
   62493       return;
   62494     }
   62495 #endif
   62496     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
   62497   }
   62498 #endif
   62499 
   62500   /* Find an empty slot and replace it */
   62501   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   62502     if( p->iReg==0 ){
   62503       p->iLevel = pParse->iCacheLevel;
   62504       p->iTable = iTab;
   62505       p->iColumn = iCol;
   62506       p->iReg = iReg;
   62507       p->tempReg = 0;
   62508       p->lru = pParse->iCacheCnt++;
   62509       return;
   62510     }
   62511   }
   62512 
   62513   /* Replace the last recently used */
   62514   minLru = 0x7fffffff;
   62515   idxLru = -1;
   62516   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   62517     if( p->lru<minLru ){
   62518       idxLru = i;
   62519       minLru = p->lru;
   62520     }
   62521   }
   62522   if( ALWAYS(idxLru>=0) ){
   62523     p = &pParse->aColCache[idxLru];
   62524     p->iLevel = pParse->iCacheLevel;
   62525     p->iTable = iTab;
   62526     p->iColumn = iCol;
   62527     p->iReg = iReg;
   62528     p->tempReg = 0;
   62529     p->lru = pParse->iCacheCnt++;
   62530     return;
   62531   }
   62532 }
   62533 
   62534 /*
   62535 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
   62536 ** Purge the range of registers from the column cache.
   62537 */
   62538 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
   62539   int i;
   62540   int iLast = iReg + nReg - 1;
   62541   struct yColCache *p;
   62542   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   62543     int r = p->iReg;
   62544     if( r>=iReg && r<=iLast ){
   62545       cacheEntryClear(pParse, p);
   62546       p->iReg = 0;
   62547     }
   62548   }
   62549 }
   62550 
   62551 /*
   62552 ** Remember the current column cache context.  Any new entries added
   62553 ** added to the column cache after this call are removed when the
   62554 ** corresponding pop occurs.
   62555 */
   62556 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
   62557   pParse->iCacheLevel++;
   62558 }
   62559 
   62560 /*
   62561 ** Remove from the column cache any entries that were added since the
   62562 ** the previous N Push operations.  In other words, restore the cache
   62563 ** to the state it was in N Pushes ago.
   62564 */
   62565 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
   62566   int i;
   62567   struct yColCache *p;
   62568   assert( N>0 );
   62569   assert( pParse->iCacheLevel>=N );
   62570   pParse->iCacheLevel -= N;
   62571   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   62572     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
   62573       cacheEntryClear(pParse, p);
   62574       p->iReg = 0;
   62575     }
   62576   }
   62577 }
   62578 
   62579 /*
   62580 ** When a cached column is reused, make sure that its register is
   62581 ** no longer available as a temp register.  ticket #3879:  that same
   62582 ** register might be in the cache in multiple places, so be sure to
   62583 ** get them all.
   62584 */
   62585 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
   62586   int i;
   62587   struct yColCache *p;
   62588   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   62589     if( p->iReg==iReg ){
   62590       p->tempReg = 0;
   62591     }
   62592   }
   62593 }
   62594 
   62595 /*
   62596 ** Generate code that will extract the iColumn-th column from
   62597 ** table pTab and store the column value in a register.  An effort
   62598 ** is made to store the column value in register iReg, but this is
   62599 ** not guaranteed.  The location of the column value is returned.
   62600 **
   62601 ** There must be an open cursor to pTab in iTable when this routine
   62602 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
   62603 */
   62604 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
   62605   Parse *pParse,   /* Parsing and code generating context */
   62606   Table *pTab,     /* Description of the table we are reading from */
   62607   int iColumn,     /* Index of the table column */
   62608   int iTable,      /* The cursor pointing to the table */
   62609   int iReg         /* Store results here */
   62610 ){
   62611   Vdbe *v = pParse->pVdbe;
   62612   int i;
   62613   struct yColCache *p;
   62614 
   62615   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   62616     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
   62617       p->lru = pParse->iCacheCnt++;
   62618       sqlite3ExprCachePinRegister(pParse, p->iReg);
   62619       return p->iReg;
   62620     }
   62621   }
   62622   assert( v!=0 );
   62623   if( iColumn<0 ){
   62624     sqlite3VdbeAddOp2(v, OP_Rowid, iTable, iReg);
   62625   }else if( ALWAYS(pTab!=0) ){
   62626     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
   62627     sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
   62628     sqlite3ColumnDefault(v, pTab, iColumn, iReg);
   62629   }
   62630   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
   62631   return iReg;
   62632 }
   62633 
   62634 /*
   62635 ** Clear all column cache entries.
   62636 */
   62637 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
   62638   int i;
   62639   struct yColCache *p;
   62640 
   62641   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   62642     if( p->iReg ){
   62643       cacheEntryClear(pParse, p);
   62644       p->iReg = 0;
   62645     }
   62646   }
   62647 }
   62648 
   62649 /*
   62650 ** Record the fact that an affinity change has occurred on iCount
   62651 ** registers starting with iStart.
   62652 */
   62653 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
   62654   sqlite3ExprCacheRemove(pParse, iStart, iCount);
   62655 }
   62656 
   62657 /*
   62658 ** Generate code to move content from registers iFrom...iFrom+nReg-1
   62659 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
   62660 */
   62661 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
   62662   int i;
   62663   struct yColCache *p;
   62664   if( NEVER(iFrom==iTo) ) return;
   62665   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
   62666   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   62667     int x = p->iReg;
   62668     if( x>=iFrom && x<iFrom+nReg ){
   62669       p->iReg += iTo-iFrom;
   62670     }
   62671   }
   62672 }
   62673 
   62674 /*
   62675 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
   62676 ** over to iTo..iTo+nReg-1.
   62677 */
   62678 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
   62679   int i;
   62680   if( NEVER(iFrom==iTo) ) return;
   62681   for(i=0; i<nReg; i++){
   62682     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
   62683   }
   62684 }
   62685 
   62686 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   62687 /*
   62688 ** Return true if any register in the range iFrom..iTo (inclusive)
   62689 ** is used as part of the column cache.
   62690 **
   62691 ** This routine is used within assert() and testcase() macros only
   62692 ** and does not appear in a normal build.
   62693 */
   62694 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
   62695   int i;
   62696   struct yColCache *p;
   62697   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   62698     int r = p->iReg;
   62699     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
   62700   }
   62701   return 0;
   62702 }
   62703 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
   62704 
   62705 /*
   62706 ** If the last instruction coded is an ephemeral copy of any of
   62707 ** the registers in the nReg registers beginning with iReg, then
   62708 ** convert the last instruction from OP_SCopy to OP_Copy.
   62709 */
   62710 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
   62711   VdbeOp *pOp;
   62712   Vdbe *v;
   62713 
   62714   assert( pParse->db->mallocFailed==0 );
   62715   v = pParse->pVdbe;
   62716   assert( v!=0 );
   62717   pOp = sqlite3VdbeGetOp(v, -1);
   62718   assert( pOp!=0 );
   62719   if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
   62720     pOp->opcode = OP_Copy;
   62721   }
   62722 }
   62723 
   62724 /*
   62725 ** Generate code to store the value of the iAlias-th alias in register
   62726 ** target.  The first time this is called, pExpr is evaluated to compute
   62727 ** the value of the alias.  The value is stored in an auxiliary register
   62728 ** and the number of that register is returned.  On subsequent calls,
   62729 ** the register number is returned without generating any code.
   62730 **
   62731 ** Note that in order for this to work, code must be generated in the
   62732 ** same order that it is executed.
   62733 **
   62734 ** Aliases are numbered starting with 1.  So iAlias is in the range
   62735 ** of 1 to pParse->nAlias inclusive.
   62736 **
   62737 ** pParse->aAlias[iAlias-1] records the register number where the value
   62738 ** of the iAlias-th alias is stored.  If zero, that means that the
   62739 ** alias has not yet been computed.
   62740 */
   62741 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
   62742 #if 0
   62743   sqlite3 *db = pParse->db;
   62744   int iReg;
   62745   if( pParse->nAliasAlloc<pParse->nAlias ){
   62746     pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
   62747                                  sizeof(pParse->aAlias[0])*pParse->nAlias );
   62748     testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
   62749     if( db->mallocFailed ) return 0;
   62750     memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
   62751            (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
   62752     pParse->nAliasAlloc = pParse->nAlias;
   62753   }
   62754   assert( iAlias>0 && iAlias<=pParse->nAlias );
   62755   iReg = pParse->aAlias[iAlias-1];
   62756   if( iReg==0 ){
   62757     if( pParse->iCacheLevel>0 ){
   62758       iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
   62759     }else{
   62760       iReg = ++pParse->nMem;
   62761       sqlite3ExprCode(pParse, pExpr, iReg);
   62762       pParse->aAlias[iAlias-1] = iReg;
   62763     }
   62764   }
   62765   return iReg;
   62766 #else
   62767   UNUSED_PARAMETER(iAlias);
   62768   return sqlite3ExprCodeTarget(pParse, pExpr, target);
   62769 #endif
   62770 }
   62771 
   62772 /*
   62773 ** Generate code into the current Vdbe to evaluate the given
   62774 ** expression.  Attempt to store the results in register "target".
   62775 ** Return the register where results are stored.
   62776 **
   62777 ** With this routine, there is no guarantee that results will
   62778 ** be stored in target.  The result might be stored in some other
   62779 ** register if it is convenient to do so.  The calling function
   62780 ** must check the return code and move the results to the desired
   62781 ** register.
   62782 */
   62783 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
   62784   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
   62785   int op;                   /* The opcode being coded */
   62786   int inReg = target;       /* Results stored in register inReg */
   62787   int regFree1 = 0;         /* If non-zero free this temporary register */
   62788   int regFree2 = 0;         /* If non-zero free this temporary register */
   62789   int r1, r2, r3, r4;       /* Various register numbers */
   62790   sqlite3 *db = pParse->db; /* The database connection */
   62791 
   62792   assert( target>0 && target<=pParse->nMem );
   62793   if( v==0 ){
   62794     assert( pParse->db->mallocFailed );
   62795     return 0;
   62796   }
   62797 
   62798   if( pExpr==0 ){
   62799     op = TK_NULL;
   62800   }else{
   62801     op = pExpr->op;
   62802   }
   62803   switch( op ){
   62804     case TK_AGG_COLUMN: {
   62805       AggInfo *pAggInfo = pExpr->pAggInfo;
   62806       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
   62807       if( !pAggInfo->directMode ){
   62808         assert( pCol->iMem>0 );
   62809         inReg = pCol->iMem;
   62810         break;
   62811       }else if( pAggInfo->useSortingIdx ){
   62812         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
   62813                               pCol->iSorterColumn, target);
   62814         break;
   62815       }
   62816       /* Otherwise, fall thru into the TK_COLUMN case */
   62817     }
   62818     case TK_COLUMN: {
   62819       if( pExpr->iTable<0 ){
   62820         /* This only happens when coding check constraints */
   62821         assert( pParse->ckBase>0 );
   62822         inReg = pExpr->iColumn + pParse->ckBase;
   62823       }else{
   62824         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
   62825                                  pExpr->iColumn, pExpr->iTable, target);
   62826       }
   62827       break;
   62828     }
   62829     case TK_INTEGER: {
   62830       codeInteger(v, pExpr, 0, target);
   62831       break;
   62832     }
   62833     case TK_FLOAT: {
   62834       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   62835       codeReal(v, pExpr->u.zToken, 0, target);
   62836       break;
   62837     }
   62838     case TK_STRING: {
   62839       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   62840       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
   62841       break;
   62842     }
   62843     case TK_NULL: {
   62844       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   62845       break;
   62846     }
   62847 #ifndef SQLITE_OMIT_BLOB_LITERAL
   62848     case TK_BLOB: {
   62849       int n;
   62850       const char *z;
   62851       char *zBlob;
   62852       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   62853       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
   62854       assert( pExpr->u.zToken[1]=='\'' );
   62855       z = &pExpr->u.zToken[2];
   62856       n = sqlite3Strlen30(z) - 1;
   62857       assert( z[n]=='\'' );
   62858       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
   62859       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
   62860       break;
   62861     }
   62862 #endif
   62863     case TK_VARIABLE: {
   62864       VdbeOp *pOp;
   62865       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   62866       assert( pExpr->u.zToken!=0 );
   62867       assert( pExpr->u.zToken[0]!=0 );
   62868       if( pExpr->u.zToken[1]==0
   62869          && (pOp = sqlite3VdbeGetOp(v, -1))->opcode==OP_Variable
   62870          && pOp->p1+pOp->p3==pExpr->iColumn
   62871          && pOp->p2+pOp->p3==target
   62872          && pOp->p4.z==0
   62873       ){
   62874         /* If the previous instruction was a copy of the previous unnamed
   62875         ** parameter into the previous register, then simply increment the
   62876         ** repeat count on the prior instruction rather than making a new
   62877         ** instruction.
   62878         */
   62879         pOp->p3++;
   62880       }else{
   62881         sqlite3VdbeAddOp3(v, OP_Variable, pExpr->iColumn, target, 1);
   62882         if( pExpr->u.zToken[1]!=0 ){
   62883           sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
   62884         }
   62885       }
   62886       break;
   62887     }
   62888     case TK_REGISTER: {
   62889       inReg = pExpr->iTable;
   62890       break;
   62891     }
   62892     case TK_AS: {
   62893       inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
   62894       break;
   62895     }
   62896 #ifndef SQLITE_OMIT_CAST
   62897     case TK_CAST: {
   62898       /* Expressions of the form:   CAST(pLeft AS token) */
   62899       int aff, to_op;
   62900       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   62901       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   62902       aff = sqlite3AffinityType(pExpr->u.zToken);
   62903       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
   62904       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
   62905       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
   62906       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
   62907       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
   62908       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
   62909       testcase( to_op==OP_ToText );
   62910       testcase( to_op==OP_ToBlob );
   62911       testcase( to_op==OP_ToNumeric );
   62912       testcase( to_op==OP_ToInt );
   62913       testcase( to_op==OP_ToReal );
   62914       if( inReg!=target ){
   62915         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
   62916         inReg = target;
   62917       }
   62918       sqlite3VdbeAddOp1(v, to_op, inReg);
   62919       testcase( usedAsColumnCache(pParse, inReg, inReg) );
   62920       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
   62921       break;
   62922     }
   62923 #endif /* SQLITE_OMIT_CAST */
   62924     case TK_LT:
   62925     case TK_LE:
   62926     case TK_GT:
   62927     case TK_GE:
   62928     case TK_NE:
   62929     case TK_EQ: {
   62930       assert( TK_LT==OP_Lt );
   62931       assert( TK_LE==OP_Le );
   62932       assert( TK_GT==OP_Gt );
   62933       assert( TK_GE==OP_Ge );
   62934       assert( TK_EQ==OP_Eq );
   62935       assert( TK_NE==OP_Ne );
   62936       testcase( op==TK_LT );
   62937       testcase( op==TK_LE );
   62938       testcase( op==TK_GT );
   62939       testcase( op==TK_GE );
   62940       testcase( op==TK_EQ );
   62941       testcase( op==TK_NE );
   62942       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   62943       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   62944       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   62945                   r1, r2, inReg, SQLITE_STOREP2);
   62946       testcase( regFree1==0 );
   62947       testcase( regFree2==0 );
   62948       break;
   62949     }
   62950     case TK_IS:
   62951     case TK_ISNOT: {
   62952       testcase( op==TK_IS );
   62953       testcase( op==TK_ISNOT );
   62954       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   62955       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   62956       op = (op==TK_IS) ? TK_EQ : TK_NE;
   62957       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   62958                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
   62959       testcase( regFree1==0 );
   62960       testcase( regFree2==0 );
   62961       break;
   62962     }
   62963     case TK_AND:
   62964     case TK_OR:
   62965     case TK_PLUS:
   62966     case TK_STAR:
   62967     case TK_MINUS:
   62968     case TK_REM:
   62969     case TK_BITAND:
   62970     case TK_BITOR:
   62971     case TK_SLASH:
   62972     case TK_LSHIFT:
   62973     case TK_RSHIFT:
   62974     case TK_CONCAT: {
   62975       assert( TK_AND==OP_And );
   62976       assert( TK_OR==OP_Or );
   62977       assert( TK_PLUS==OP_Add );
   62978       assert( TK_MINUS==OP_Subtract );
   62979       assert( TK_REM==OP_Remainder );
   62980       assert( TK_BITAND==OP_BitAnd );
   62981       assert( TK_BITOR==OP_BitOr );
   62982       assert( TK_SLASH==OP_Divide );
   62983       assert( TK_LSHIFT==OP_ShiftLeft );
   62984       assert( TK_RSHIFT==OP_ShiftRight );
   62985       assert( TK_CONCAT==OP_Concat );
   62986       testcase( op==TK_AND );
   62987       testcase( op==TK_OR );
   62988       testcase( op==TK_PLUS );
   62989       testcase( op==TK_MINUS );
   62990       testcase( op==TK_REM );
   62991       testcase( op==TK_BITAND );
   62992       testcase( op==TK_BITOR );
   62993       testcase( op==TK_SLASH );
   62994       testcase( op==TK_LSHIFT );
   62995       testcase( op==TK_RSHIFT );
   62996       testcase( op==TK_CONCAT );
   62997       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   62998       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   62999       sqlite3VdbeAddOp3(v, op, r2, r1, target);
   63000       testcase( regFree1==0 );
   63001       testcase( regFree2==0 );
   63002       break;
   63003     }
   63004     case TK_UMINUS: {
   63005       Expr *pLeft = pExpr->pLeft;
   63006       assert( pLeft );
   63007       if( pLeft->op==TK_FLOAT ){
   63008         assert( !ExprHasProperty(pExpr, EP_IntValue) );
   63009         codeReal(v, pLeft->u.zToken, 1, target);
   63010       }else if( pLeft->op==TK_INTEGER ){
   63011         codeInteger(v, pLeft, 1, target);
   63012       }else{
   63013         regFree1 = r1 = sqlite3GetTempReg(pParse);
   63014         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
   63015         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
   63016         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
   63017         testcase( regFree2==0 );
   63018       }
   63019       inReg = target;
   63020       break;
   63021     }
   63022     case TK_BITNOT:
   63023     case TK_NOT: {
   63024       assert( TK_BITNOT==OP_BitNot );
   63025       assert( TK_NOT==OP_Not );
   63026       testcase( op==TK_BITNOT );
   63027       testcase( op==TK_NOT );
   63028       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   63029       testcase( regFree1==0 );
   63030       inReg = target;
   63031       sqlite3VdbeAddOp2(v, op, r1, inReg);
   63032       break;
   63033     }
   63034     case TK_ISNULL:
   63035     case TK_NOTNULL: {
   63036       int addr;
   63037       assert( TK_ISNULL==OP_IsNull );
   63038       assert( TK_NOTNULL==OP_NotNull );
   63039       testcase( op==TK_ISNULL );
   63040       testcase( op==TK_NOTNULL );
   63041       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
   63042       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   63043       testcase( regFree1==0 );
   63044       addr = sqlite3VdbeAddOp1(v, op, r1);
   63045       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
   63046       sqlite3VdbeJumpHere(v, addr);
   63047       break;
   63048     }
   63049     case TK_AGG_FUNCTION: {
   63050       AggInfo *pInfo = pExpr->pAggInfo;
   63051       if( pInfo==0 ){
   63052         assert( !ExprHasProperty(pExpr, EP_IntValue) );
   63053         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
   63054       }else{
   63055         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
   63056       }
   63057       break;
   63058     }
   63059     case TK_CONST_FUNC:
   63060     case TK_FUNCTION: {
   63061       ExprList *pFarg;       /* List of function arguments */
   63062       int nFarg;             /* Number of function arguments */
   63063       FuncDef *pDef;         /* The function definition object */
   63064       int nId;               /* Length of the function name in bytes */
   63065       const char *zId;       /* The function name */
   63066       int constMask = 0;     /* Mask of function arguments that are constant */
   63067       int i;                 /* Loop counter */
   63068       u8 enc = ENC(db);      /* The text encoding used by this database */
   63069       CollSeq *pColl = 0;    /* A collating sequence */
   63070 
   63071       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   63072       testcase( op==TK_CONST_FUNC );
   63073       testcase( op==TK_FUNCTION );
   63074       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
   63075         pFarg = 0;
   63076       }else{
   63077         pFarg = pExpr->x.pList;
   63078       }
   63079       nFarg = pFarg ? pFarg->nExpr : 0;
   63080       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   63081       zId = pExpr->u.zToken;
   63082       nId = sqlite3Strlen30(zId);
   63083       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
   63084       if( pDef==0 ){
   63085         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
   63086         break;
   63087       }
   63088 
   63089       /* Attempt a direct implementation of the built-in COALESCE() and
   63090       ** IFNULL() functions.  This avoids unnecessary evalation of
   63091       ** arguments past the first non-NULL argument.
   63092       */
   63093       if( pDef->flags & SQLITE_FUNC_COALESCE ){
   63094         int endCoalesce = sqlite3VdbeMakeLabel(v);
   63095         assert( nFarg>=2 );
   63096         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
   63097         for(i=1; i<nFarg; i++){
   63098           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
   63099           sqlite3ExprCacheRemove(pParse, target, 1);
   63100           sqlite3ExprCachePush(pParse);
   63101           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
   63102           sqlite3ExprCachePop(pParse, 1);
   63103         }
   63104         sqlite3VdbeResolveLabel(v, endCoalesce);
   63105         break;
   63106       }
   63107 
   63108 
   63109       if( pFarg ){
   63110         r1 = sqlite3GetTempRange(pParse, nFarg);
   63111         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
   63112         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
   63113         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
   63114       }else{
   63115         r1 = 0;
   63116       }
   63117 #ifndef SQLITE_OMIT_VIRTUALTABLE
   63118       /* Possibly overload the function if the first argument is
   63119       ** a virtual table column.
   63120       **
   63121       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
   63122       ** second argument, not the first, as the argument to test to
   63123       ** see if it is a column in a virtual table.  This is done because
   63124       ** the left operand of infix functions (the operand we want to
   63125       ** control overloading) ends up as the second argument to the
   63126       ** function.  The expression "A glob B" is equivalent to
   63127       ** "glob(B,A).  We want to use the A in "A glob B" to test
   63128       ** for function overloading.  But we use the B term in "glob(B,A)".
   63129       */
   63130       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
   63131         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
   63132       }else if( nFarg>0 ){
   63133         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
   63134       }
   63135 #endif
   63136       for(i=0; i<nFarg; i++){
   63137         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
   63138           constMask |= (1<<i);
   63139         }
   63140         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
   63141           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
   63142         }
   63143       }
   63144       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
   63145         if( !pColl ) pColl = db->pDfltColl;
   63146         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
   63147       }
   63148       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
   63149                         (char*)pDef, P4_FUNCDEF);
   63150       sqlite3VdbeChangeP5(v, (u8)nFarg);
   63151       if( nFarg ){
   63152         sqlite3ReleaseTempRange(pParse, r1, nFarg);
   63153       }
   63154       break;
   63155     }
   63156 #ifndef SQLITE_OMIT_SUBQUERY
   63157     case TK_EXISTS:
   63158     case TK_SELECT: {
   63159       testcase( op==TK_EXISTS );
   63160       testcase( op==TK_SELECT );
   63161       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
   63162       break;
   63163     }
   63164     case TK_IN: {
   63165       int destIfFalse = sqlite3VdbeMakeLabel(v);
   63166       int destIfNull = sqlite3VdbeMakeLabel(v);
   63167       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   63168       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
   63169       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
   63170       sqlite3VdbeResolveLabel(v, destIfFalse);
   63171       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
   63172       sqlite3VdbeResolveLabel(v, destIfNull);
   63173       break;
   63174     }
   63175 #endif /* SQLITE_OMIT_SUBQUERY */
   63176 
   63177 
   63178     /*
   63179     **    x BETWEEN y AND z
   63180     **
   63181     ** This is equivalent to
   63182     **
   63183     **    x>=y AND x<=z
   63184     **
   63185     ** X is stored in pExpr->pLeft.
   63186     ** Y is stored in pExpr->pList->a[0].pExpr.
   63187     ** Z is stored in pExpr->pList->a[1].pExpr.
   63188     */
   63189     case TK_BETWEEN: {
   63190       Expr *pLeft = pExpr->pLeft;
   63191       struct ExprList_item *pLItem = pExpr->x.pList->a;
   63192       Expr *pRight = pLItem->pExpr;
   63193 
   63194       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
   63195       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
   63196       testcase( regFree1==0 );
   63197       testcase( regFree2==0 );
   63198       r3 = sqlite3GetTempReg(pParse);
   63199       r4 = sqlite3GetTempReg(pParse);
   63200       codeCompare(pParse, pLeft, pRight, OP_Ge,
   63201                   r1, r2, r3, SQLITE_STOREP2);
   63202       pLItem++;
   63203       pRight = pLItem->pExpr;
   63204       sqlite3ReleaseTempReg(pParse, regFree2);
   63205       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
   63206       testcase( regFree2==0 );
   63207       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
   63208       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
   63209       sqlite3ReleaseTempReg(pParse, r3);
   63210       sqlite3ReleaseTempReg(pParse, r4);
   63211       break;
   63212     }
   63213     case TK_UPLUS: {
   63214       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   63215       break;
   63216     }
   63217 
   63218     case TK_TRIGGER: {
   63219       /* If the opcode is TK_TRIGGER, then the expression is a reference
   63220       ** to a column in the new.* or old.* pseudo-tables available to
   63221       ** trigger programs. In this case Expr.iTable is set to 1 for the
   63222       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
   63223       ** is set to the column of the pseudo-table to read, or to -1 to
   63224       ** read the rowid field.
   63225       **
   63226       ** The expression is implemented using an OP_Param opcode. The p1
   63227       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
   63228       ** to reference another column of the old.* pseudo-table, where
   63229       ** i is the index of the column. For a new.rowid reference, p1 is
   63230       ** set to (n+1), where n is the number of columns in each pseudo-table.
   63231       ** For a reference to any other column in the new.* pseudo-table, p1
   63232       ** is set to (n+2+i), where n and i are as defined previously. For
   63233       ** example, if the table on which triggers are being fired is
   63234       ** declared as:
   63235       **
   63236       **   CREATE TABLE t1(a, b);
   63237       **
   63238       ** Then p1 is interpreted as follows:
   63239       **
   63240       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
   63241       **   p1==1   ->    old.a         p1==4   ->    new.a
   63242       **   p1==2   ->    old.b         p1==5   ->    new.b
   63243       */
   63244       Table *pTab = pExpr->pTab;
   63245       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
   63246 
   63247       assert( pExpr->iTable==0 || pExpr->iTable==1 );
   63248       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
   63249       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
   63250       assert( p1>=0 && p1<(pTab->nCol*2+2) );
   63251 
   63252       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
   63253       VdbeComment((v, "%s.%s -> $%d",
   63254         (pExpr->iTable ? "new" : "old"),
   63255         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
   63256         target
   63257       ));
   63258 
   63259       /* If the column has REAL affinity, it may currently be stored as an
   63260       ** integer. Use OP_RealAffinity to make sure it is really real.  */
   63261       if( pExpr->iColumn>=0
   63262        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
   63263       ){
   63264         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
   63265       }
   63266       break;
   63267     }
   63268 
   63269 
   63270     /*
   63271     ** Form A:
   63272     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
   63273     **
   63274     ** Form B:
   63275     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
   63276     **
   63277     ** Form A is can be transformed into the equivalent form B as follows:
   63278     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
   63279     **        WHEN x=eN THEN rN ELSE y END
   63280     **
   63281     ** X (if it exists) is in pExpr->pLeft.
   63282     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
   63283     ** ELSE clause and no other term matches, then the result of the
   63284     ** exprssion is NULL.
   63285     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
   63286     **
   63287     ** The result of the expression is the Ri for the first matching Ei,
   63288     ** or if there is no matching Ei, the ELSE term Y, or if there is
   63289     ** no ELSE term, NULL.
   63290     */
   63291     default: assert( op==TK_CASE ); {
   63292       int endLabel;                     /* GOTO label for end of CASE stmt */
   63293       int nextCase;                     /* GOTO label for next WHEN clause */
   63294       int nExpr;                        /* 2x number of WHEN terms */
   63295       int i;                            /* Loop counter */
   63296       ExprList *pEList;                 /* List of WHEN terms */
   63297       struct ExprList_item *aListelem;  /* Array of WHEN terms */
   63298       Expr opCompare;                   /* The X==Ei expression */
   63299       Expr cacheX;                      /* Cached expression X */
   63300       Expr *pX;                         /* The X expression */
   63301       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
   63302       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
   63303 
   63304       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
   63305       assert((pExpr->x.pList->nExpr % 2) == 0);
   63306       assert(pExpr->x.pList->nExpr > 0);
   63307       pEList = pExpr->x.pList;
   63308       aListelem = pEList->a;
   63309       nExpr = pEList->nExpr;
   63310       endLabel = sqlite3VdbeMakeLabel(v);
   63311       if( (pX = pExpr->pLeft)!=0 ){
   63312         cacheX = *pX;
   63313         testcase( pX->op==TK_COLUMN );
   63314         testcase( pX->op==TK_REGISTER );
   63315         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
   63316         testcase( regFree1==0 );
   63317         cacheX.op = TK_REGISTER;
   63318         opCompare.op = TK_EQ;
   63319         opCompare.pLeft = &cacheX;
   63320         pTest = &opCompare;
   63321       }
   63322       for(i=0; i<nExpr; i=i+2){
   63323         sqlite3ExprCachePush(pParse);
   63324         if( pX ){
   63325           assert( pTest!=0 );
   63326           opCompare.pRight = aListelem[i].pExpr;
   63327         }else{
   63328           pTest = aListelem[i].pExpr;
   63329         }
   63330         nextCase = sqlite3VdbeMakeLabel(v);
   63331         testcase( pTest->op==TK_COLUMN );
   63332         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
   63333         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
   63334         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
   63335         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
   63336         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
   63337         sqlite3ExprCachePop(pParse, 1);
   63338         sqlite3VdbeResolveLabel(v, nextCase);
   63339       }
   63340       if( pExpr->pRight ){
   63341         sqlite3ExprCachePush(pParse);
   63342         sqlite3ExprCode(pParse, pExpr->pRight, target);
   63343         sqlite3ExprCachePop(pParse, 1);
   63344       }else{
   63345         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   63346       }
   63347       assert( db->mallocFailed || pParse->nErr>0
   63348            || pParse->iCacheLevel==iCacheLevel );
   63349       sqlite3VdbeResolveLabel(v, endLabel);
   63350       break;
   63351     }
   63352 #ifndef SQLITE_OMIT_TRIGGER
   63353     case TK_RAISE: {
   63354       assert( pExpr->affinity==OE_Rollback
   63355            || pExpr->affinity==OE_Abort
   63356            || pExpr->affinity==OE_Fail
   63357            || pExpr->affinity==OE_Ignore
   63358       );
   63359       if( !pParse->pTriggerTab ){
   63360         sqlite3ErrorMsg(pParse,
   63361                        "RAISE() may only be used within a trigger-program");
   63362         return 0;
   63363       }
   63364       if( pExpr->affinity==OE_Abort ){
   63365         sqlite3MayAbort(pParse);
   63366       }
   63367       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   63368       if( pExpr->affinity==OE_Ignore ){
   63369         sqlite3VdbeAddOp4(
   63370             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
   63371       }else{
   63372         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
   63373       }
   63374 
   63375       break;
   63376     }
   63377 #endif
   63378   }
   63379   sqlite3ReleaseTempReg(pParse, regFree1);
   63380   sqlite3ReleaseTempReg(pParse, regFree2);
   63381   return inReg;
   63382 }
   63383 
   63384 /*
   63385 ** Generate code to evaluate an expression and store the results
   63386 ** into a register.  Return the register number where the results
   63387 ** are stored.
   63388 **
   63389 ** If the register is a temporary register that can be deallocated,
   63390 ** then write its number into *pReg.  If the result register is not
   63391 ** a temporary, then set *pReg to zero.
   63392 */
   63393 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
   63394   int r1 = sqlite3GetTempReg(pParse);
   63395   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
   63396   if( r2==r1 ){
   63397     *pReg = r1;
   63398   }else{
   63399     sqlite3ReleaseTempReg(pParse, r1);
   63400     *pReg = 0;
   63401   }
   63402   return r2;
   63403 }
   63404 
   63405 /*
   63406 ** Generate code that will evaluate expression pExpr and store the
   63407 ** results in register target.  The results are guaranteed to appear
   63408 ** in register target.
   63409 */
   63410 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
   63411   int inReg;
   63412 
   63413   assert( target>0 && target<=pParse->nMem );
   63414   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
   63415   assert( pParse->pVdbe || pParse->db->mallocFailed );
   63416   if( inReg!=target && pParse->pVdbe ){
   63417     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
   63418   }
   63419   return target;
   63420 }
   63421 
   63422 /*
   63423 ** Generate code that evalutes the given expression and puts the result
   63424 ** in register target.
   63425 **
   63426 ** Also make a copy of the expression results into another "cache" register
   63427 ** and modify the expression so that the next time it is evaluated,
   63428 ** the result is a copy of the cache register.
   63429 **
   63430 ** This routine is used for expressions that are used multiple
   63431 ** times.  They are evaluated once and the results of the expression
   63432 ** are reused.
   63433 */
   63434 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
   63435   Vdbe *v = pParse->pVdbe;
   63436   int inReg;
   63437   inReg = sqlite3ExprCode(pParse, pExpr, target);
   63438   assert( target>0 );
   63439   /* This routine is called for terms to INSERT or UPDATE.  And the only
   63440   ** other place where expressions can be converted into TK_REGISTER is
   63441   ** in WHERE clause processing.  So as currently implemented, there is
   63442   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
   63443   ** keep the ALWAYS() in case the conditions above change with future
   63444   ** modifications or enhancements. */
   63445   if( ALWAYS(pExpr->op!=TK_REGISTER) ){
   63446     int iMem;
   63447     iMem = ++pParse->nMem;
   63448     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
   63449     pExpr->iTable = iMem;
   63450     pExpr->op2 = pExpr->op;
   63451     pExpr->op = TK_REGISTER;
   63452   }
   63453   return inReg;
   63454 }
   63455 
   63456 /*
   63457 ** Return TRUE if pExpr is an constant expression that is appropriate
   63458 ** for factoring out of a loop.  Appropriate expressions are:
   63459 **
   63460 **    *  Any expression that evaluates to two or more opcodes.
   63461 **
   63462 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
   63463 **       or OP_Variable that does not need to be placed in a
   63464 **       specific register.
   63465 **
   63466 ** There is no point in factoring out single-instruction constant
   63467 ** expressions that need to be placed in a particular register.
   63468 ** We could factor them out, but then we would end up adding an
   63469 ** OP_SCopy instruction to move the value into the correct register
   63470 ** later.  We might as well just use the original instruction and
   63471 ** avoid the OP_SCopy.
   63472 */
   63473 static int isAppropriateForFactoring(Expr *p){
   63474   if( !sqlite3ExprIsConstantNotJoin(p) ){
   63475     return 0;  /* Only constant expressions are appropriate for factoring */
   63476   }
   63477   if( (p->flags & EP_FixedDest)==0 ){
   63478     return 1;  /* Any constant without a fixed destination is appropriate */
   63479   }
   63480   while( p->op==TK_UPLUS ) p = p->pLeft;
   63481   switch( p->op ){
   63482 #ifndef SQLITE_OMIT_BLOB_LITERAL
   63483     case TK_BLOB:
   63484 #endif
   63485     case TK_VARIABLE:
   63486     case TK_INTEGER:
   63487     case TK_FLOAT:
   63488     case TK_NULL:
   63489     case TK_STRING: {
   63490       testcase( p->op==TK_BLOB );
   63491       testcase( p->op==TK_VARIABLE );
   63492       testcase( p->op==TK_INTEGER );
   63493       testcase( p->op==TK_FLOAT );
   63494       testcase( p->op==TK_NULL );
   63495       testcase( p->op==TK_STRING );
   63496       /* Single-instruction constants with a fixed destination are
   63497       ** better done in-line.  If we factor them, they will just end
   63498       ** up generating an OP_SCopy to move the value to the destination
   63499       ** register. */
   63500       return 0;
   63501     }
   63502     case TK_UMINUS: {
   63503       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
   63504         return 0;
   63505       }
   63506       break;
   63507     }
   63508     default: {
   63509       break;
   63510     }
   63511   }
   63512   return 1;
   63513 }
   63514 
   63515 /*
   63516 ** If pExpr is a constant expression that is appropriate for
   63517 ** factoring out of a loop, then evaluate the expression
   63518 ** into a register and convert the expression into a TK_REGISTER
   63519 ** expression.
   63520 */
   63521 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
   63522   Parse *pParse = pWalker->pParse;
   63523   switch( pExpr->op ){
   63524     case TK_IN:
   63525     case TK_REGISTER: {
   63526       return WRC_Prune;
   63527     }
   63528     case TK_FUNCTION:
   63529     case TK_AGG_FUNCTION:
   63530     case TK_CONST_FUNC: {
   63531       /* The arguments to a function have a fixed destination.
   63532       ** Mark them this way to avoid generated unneeded OP_SCopy
   63533       ** instructions.
   63534       */
   63535       ExprList *pList = pExpr->x.pList;
   63536       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   63537       if( pList ){
   63538         int i = pList->nExpr;
   63539         struct ExprList_item *pItem = pList->a;
   63540         for(; i>0; i--, pItem++){
   63541           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
   63542         }
   63543       }
   63544       break;
   63545     }
   63546   }
   63547   if( isAppropriateForFactoring(pExpr) ){
   63548     int r1 = ++pParse->nMem;
   63549     int r2;
   63550     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
   63551     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
   63552     pExpr->op2 = pExpr->op;
   63553     pExpr->op = TK_REGISTER;
   63554     pExpr->iTable = r2;
   63555     return WRC_Prune;
   63556   }
   63557   return WRC_Continue;
   63558 }
   63559 
   63560 /*
   63561 ** Preevaluate constant subexpressions within pExpr and store the
   63562 ** results in registers.  Modify pExpr so that the constant subexpresions
   63563 ** are TK_REGISTER opcodes that refer to the precomputed values.
   63564 */
   63565 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
   63566   Walker w;
   63567   w.xExprCallback = evalConstExpr;
   63568   w.xSelectCallback = 0;
   63569   w.pParse = pParse;
   63570   sqlite3WalkExpr(&w, pExpr);
   63571 }
   63572 
   63573 
   63574 /*
   63575 ** Generate code that pushes the value of every element of the given
   63576 ** expression list into a sequence of registers beginning at target.
   63577 **
   63578 ** Return the number of elements evaluated.
   63579 */
   63580 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
   63581   Parse *pParse,     /* Parsing context */
   63582   ExprList *pList,   /* The expression list to be coded */
   63583   int target,        /* Where to write results */
   63584   int doHardCopy     /* Make a hard copy of every element */
   63585 ){
   63586   struct ExprList_item *pItem;
   63587   int i, n;
   63588   assert( pList!=0 );
   63589   assert( target>0 );
   63590   n = pList->nExpr;
   63591   for(pItem=pList->a, i=0; i<n; i++, pItem++){
   63592     if( pItem->iAlias ){
   63593       int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
   63594       Vdbe *v = sqlite3GetVdbe(pParse);
   63595       if( iReg!=target+i ){
   63596         sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
   63597       }
   63598     }else{
   63599       sqlite3ExprCode(pParse, pItem->pExpr, target+i);
   63600     }
   63601     if( doHardCopy && !pParse->db->mallocFailed ){
   63602       sqlite3ExprHardCopy(pParse, target, n);
   63603     }
   63604   }
   63605   return n;
   63606 }
   63607 
   63608 /*
   63609 ** Generate code for a BETWEEN operator.
   63610 **
   63611 **    x BETWEEN y AND z
   63612 **
   63613 ** The above is equivalent to
   63614 **
   63615 **    x>=y AND x<=z
   63616 **
   63617 ** Code it as such, taking care to do the common subexpression
   63618 ** elementation of x.
   63619 */
   63620 static void exprCodeBetween(
   63621   Parse *pParse,    /* Parsing and code generating context */
   63622   Expr *pExpr,      /* The BETWEEN expression */
   63623   int dest,         /* Jump here if the jump is taken */
   63624   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
   63625   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
   63626 ){
   63627   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
   63628   Expr compLeft;    /* The  x>=y  term */
   63629   Expr compRight;   /* The  x<=z  term */
   63630   Expr exprX;       /* The  x  subexpression */
   63631   int regFree1 = 0; /* Temporary use register */
   63632 
   63633   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   63634   exprX = *pExpr->pLeft;
   63635   exprAnd.op = TK_AND;
   63636   exprAnd.pLeft = &compLeft;
   63637   exprAnd.pRight = &compRight;
   63638   compLeft.op = TK_GE;
   63639   compLeft.pLeft = &exprX;
   63640   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
   63641   compRight.op = TK_LE;
   63642   compRight.pLeft = &exprX;
   63643   compRight.pRight = pExpr->x.pList->a[1].pExpr;
   63644   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
   63645   exprX.op = TK_REGISTER;
   63646   if( jumpIfTrue ){
   63647     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
   63648   }else{
   63649     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
   63650   }
   63651   sqlite3ReleaseTempReg(pParse, regFree1);
   63652 
   63653   /* Ensure adequate test coverage */
   63654   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
   63655   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
   63656   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
   63657   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
   63658   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
   63659   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
   63660   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
   63661   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
   63662 }
   63663 
   63664 /*
   63665 ** Generate code for a boolean expression such that a jump is made
   63666 ** to the label "dest" if the expression is true but execution
   63667 ** continues straight thru if the expression is false.
   63668 **
   63669 ** If the expression evaluates to NULL (neither true nor false), then
   63670 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
   63671 **
   63672 ** This code depends on the fact that certain token values (ex: TK_EQ)
   63673 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
   63674 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
   63675 ** the make process cause these values to align.  Assert()s in the code
   63676 ** below verify that the numbers are aligned correctly.
   63677 */
   63678 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
   63679   Vdbe *v = pParse->pVdbe;
   63680   int op = 0;
   63681   int regFree1 = 0;
   63682   int regFree2 = 0;
   63683   int r1, r2;
   63684 
   63685   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
   63686   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
   63687   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
   63688   op = pExpr->op;
   63689   switch( op ){
   63690     case TK_AND: {
   63691       int d2 = sqlite3VdbeMakeLabel(v);
   63692       testcase( jumpIfNull==0 );
   63693       sqlite3ExprCachePush(pParse);
   63694       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
   63695       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
   63696       sqlite3VdbeResolveLabel(v, d2);
   63697       sqlite3ExprCachePop(pParse, 1);
   63698       break;
   63699     }
   63700     case TK_OR: {
   63701       testcase( jumpIfNull==0 );
   63702       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
   63703       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
   63704       break;
   63705     }
   63706     case TK_NOT: {
   63707       testcase( jumpIfNull==0 );
   63708       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
   63709       break;
   63710     }
   63711     case TK_LT:
   63712     case TK_LE:
   63713     case TK_GT:
   63714     case TK_GE:
   63715     case TK_NE:
   63716     case TK_EQ: {
   63717       assert( TK_LT==OP_Lt );
   63718       assert( TK_LE==OP_Le );
   63719       assert( TK_GT==OP_Gt );
   63720       assert( TK_GE==OP_Ge );
   63721       assert( TK_EQ==OP_Eq );
   63722       assert( TK_NE==OP_Ne );
   63723       testcase( op==TK_LT );
   63724       testcase( op==TK_LE );
   63725       testcase( op==TK_GT );
   63726       testcase( op==TK_GE );
   63727       testcase( op==TK_EQ );
   63728       testcase( op==TK_NE );
   63729       testcase( jumpIfNull==0 );
   63730       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   63731       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   63732       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   63733                   r1, r2, dest, jumpIfNull);
   63734       testcase( regFree1==0 );
   63735       testcase( regFree2==0 );
   63736       break;
   63737     }
   63738     case TK_IS:
   63739     case TK_ISNOT: {
   63740       testcase( op==TK_IS );
   63741       testcase( op==TK_ISNOT );
   63742       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   63743       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   63744       op = (op==TK_IS) ? TK_EQ : TK_NE;
   63745       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   63746                   r1, r2, dest, SQLITE_NULLEQ);
   63747       testcase( regFree1==0 );
   63748       testcase( regFree2==0 );
   63749       break;
   63750     }
   63751     case TK_ISNULL:
   63752     case TK_NOTNULL: {
   63753       assert( TK_ISNULL==OP_IsNull );
   63754       assert( TK_NOTNULL==OP_NotNull );
   63755       testcase( op==TK_ISNULL );
   63756       testcase( op==TK_NOTNULL );
   63757       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   63758       sqlite3VdbeAddOp2(v, op, r1, dest);
   63759       testcase( regFree1==0 );
   63760       break;
   63761     }
   63762     case TK_BETWEEN: {
   63763       testcase( jumpIfNull==0 );
   63764       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
   63765       break;
   63766     }
   63767     case TK_IN: {
   63768       int destIfFalse = sqlite3VdbeMakeLabel(v);
   63769       int destIfNull = jumpIfNull ? dest : destIfFalse;
   63770       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
   63771       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
   63772       sqlite3VdbeResolveLabel(v, destIfFalse);
   63773       break;
   63774     }
   63775     default: {
   63776       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
   63777       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
   63778       testcase( regFree1==0 );
   63779       testcase( jumpIfNull==0 );
   63780       break;
   63781     }
   63782   }
   63783   sqlite3ReleaseTempReg(pParse, regFree1);
   63784   sqlite3ReleaseTempReg(pParse, regFree2);
   63785 }
   63786 
   63787 /*
   63788 ** Generate code for a boolean expression such that a jump is made
   63789 ** to the label "dest" if the expression is false but execution
   63790 ** continues straight thru if the expression is true.
   63791 **
   63792 ** If the expression evaluates to NULL (neither true nor false) then
   63793 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
   63794 ** is 0.
   63795 */
   63796 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
   63797   Vdbe *v = pParse->pVdbe;
   63798   int op = 0;
   63799   int regFree1 = 0;
   63800   int regFree2 = 0;
   63801   int r1, r2;
   63802 
   63803   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
   63804   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
   63805   if( pExpr==0 )    return;
   63806 
   63807   /* The value of pExpr->op and op are related as follows:
   63808   **
   63809   **       pExpr->op            op
   63810   **       ---------          ----------
   63811   **       TK_ISNULL          OP_NotNull
   63812   **       TK_NOTNULL         OP_IsNull
   63813   **       TK_NE              OP_Eq
   63814   **       TK_EQ              OP_Ne
   63815   **       TK_GT              OP_Le
   63816   **       TK_LE              OP_Gt
   63817   **       TK_GE              OP_Lt
   63818   **       TK_LT              OP_Ge
   63819   **
   63820   ** For other values of pExpr->op, op is undefined and unused.
   63821   ** The value of TK_ and OP_ constants are arranged such that we
   63822   ** can compute the mapping above using the following expression.
   63823   ** Assert()s verify that the computation is correct.
   63824   */
   63825   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
   63826 
   63827   /* Verify correct alignment of TK_ and OP_ constants
   63828   */
   63829   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
   63830   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
   63831   assert( pExpr->op!=TK_NE || op==OP_Eq );
   63832   assert( pExpr->op!=TK_EQ || op==OP_Ne );
   63833   assert( pExpr->op!=TK_LT || op==OP_Ge );
   63834   assert( pExpr->op!=TK_LE || op==OP_Gt );
   63835   assert( pExpr->op!=TK_GT || op==OP_Le );
   63836   assert( pExpr->op!=TK_GE || op==OP_Lt );
   63837 
   63838   switch( pExpr->op ){
   63839     case TK_AND: {
   63840       testcase( jumpIfNull==0 );
   63841       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
   63842       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
   63843       break;
   63844     }
   63845     case TK_OR: {
   63846       int d2 = sqlite3VdbeMakeLabel(v);
   63847       testcase( jumpIfNull==0 );
   63848       sqlite3ExprCachePush(pParse);
   63849       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
   63850       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
   63851       sqlite3VdbeResolveLabel(v, d2);
   63852       sqlite3ExprCachePop(pParse, 1);
   63853       break;
   63854     }
   63855     case TK_NOT: {
   63856       testcase( jumpIfNull==0 );
   63857       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
   63858       break;
   63859     }
   63860     case TK_LT:
   63861     case TK_LE:
   63862     case TK_GT:
   63863     case TK_GE:
   63864     case TK_NE:
   63865     case TK_EQ: {
   63866       testcase( op==TK_LT );
   63867       testcase( op==TK_LE );
   63868       testcase( op==TK_GT );
   63869       testcase( op==TK_GE );
   63870       testcase( op==TK_EQ );
   63871       testcase( op==TK_NE );
   63872       testcase( jumpIfNull==0 );
   63873       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   63874       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   63875       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   63876                   r1, r2, dest, jumpIfNull);
   63877       testcase( regFree1==0 );
   63878       testcase( regFree2==0 );
   63879       break;
   63880     }
   63881     case TK_IS:
   63882     case TK_ISNOT: {
   63883       testcase( pExpr->op==TK_IS );
   63884       testcase( pExpr->op==TK_ISNOT );
   63885       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   63886       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   63887       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
   63888       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   63889                   r1, r2, dest, SQLITE_NULLEQ);
   63890       testcase( regFree1==0 );
   63891       testcase( regFree2==0 );
   63892       break;
   63893     }
   63894     case TK_ISNULL:
   63895     case TK_NOTNULL: {
   63896       testcase( op==TK_ISNULL );
   63897       testcase( op==TK_NOTNULL );
   63898       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   63899       sqlite3VdbeAddOp2(v, op, r1, dest);
   63900       testcase( regFree1==0 );
   63901       break;
   63902     }
   63903     case TK_BETWEEN: {
   63904       testcase( jumpIfNull==0 );
   63905       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
   63906       break;
   63907     }
   63908     case TK_IN: {
   63909       if( jumpIfNull ){
   63910         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
   63911       }else{
   63912         int destIfNull = sqlite3VdbeMakeLabel(v);
   63913         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
   63914         sqlite3VdbeResolveLabel(v, destIfNull);
   63915       }
   63916       break;
   63917     }
   63918     default: {
   63919       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
   63920       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
   63921       testcase( regFree1==0 );
   63922       testcase( jumpIfNull==0 );
   63923       break;
   63924     }
   63925   }
   63926   sqlite3ReleaseTempReg(pParse, regFree1);
   63927   sqlite3ReleaseTempReg(pParse, regFree2);
   63928 }
   63929 
   63930 /*
   63931 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
   63932 ** if they are identical and return FALSE if they differ in any way.
   63933 **
   63934 ** Sometimes this routine will return FALSE even if the two expressions
   63935 ** really are equivalent.  If we cannot prove that the expressions are
   63936 ** identical, we return FALSE just to be safe.  So if this routine
   63937 ** returns false, then you do not really know for certain if the two
   63938 ** expressions are the same.  But if you get a TRUE return, then you
   63939 ** can be sure the expressions are the same.  In the places where
   63940 ** this routine is used, it does not hurt to get an extra FALSE - that
   63941 ** just might result in some slightly slower code.  But returning
   63942 ** an incorrect TRUE could lead to a malfunction.
   63943 */
   63944 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
   63945   int i;
   63946   if( pA==0||pB==0 ){
   63947     return pB==pA;
   63948   }
   63949   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
   63950   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
   63951   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
   63952     return 0;
   63953   }
   63954   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
   63955   if( pA->op!=pB->op ) return 0;
   63956   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
   63957   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
   63958 
   63959   if( pA->x.pList && pB->x.pList ){
   63960     if( pA->x.pList->nExpr!=pB->x.pList->nExpr ) return 0;
   63961     for(i=0; i<pA->x.pList->nExpr; i++){
   63962       Expr *pExprA = pA->x.pList->a[i].pExpr;
   63963       Expr *pExprB = pB->x.pList->a[i].pExpr;
   63964       if( !sqlite3ExprCompare(pExprA, pExprB) ) return 0;
   63965     }
   63966   }else if( pA->x.pList || pB->x.pList ){
   63967     return 0;
   63968   }
   63969 
   63970   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
   63971   if( ExprHasProperty(pA, EP_IntValue) ){
   63972     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
   63973       return 0;
   63974     }
   63975   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
   63976     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 0;
   63977     if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
   63978       return 0;
   63979     }
   63980   }
   63981   return 1;
   63982 }
   63983 
   63984 
   63985 /*
   63986 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
   63987 ** the new element.  Return a negative number if malloc fails.
   63988 */
   63989 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
   63990   int i;
   63991   pInfo->aCol = sqlite3ArrayAllocate(
   63992        db,
   63993        pInfo->aCol,
   63994        sizeof(pInfo->aCol[0]),
   63995        3,
   63996        &pInfo->nColumn,
   63997        &pInfo->nColumnAlloc,
   63998        &i
   63999   );
   64000   return i;
   64001 }
   64002 
   64003 /*
   64004 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
   64005 ** the new element.  Return a negative number if malloc fails.
   64006 */
   64007 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
   64008   int i;
   64009   pInfo->aFunc = sqlite3ArrayAllocate(
   64010        db,
   64011        pInfo->aFunc,
   64012        sizeof(pInfo->aFunc[0]),
   64013        3,
   64014        &pInfo->nFunc,
   64015        &pInfo->nFuncAlloc,
   64016        &i
   64017   );
   64018   return i;
   64019 }
   64020 
   64021 /*
   64022 ** This is the xExprCallback for a tree walker.  It is used to
   64023 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
   64024 ** for additional information.
   64025 */
   64026 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
   64027   int i;
   64028   NameContext *pNC = pWalker->u.pNC;
   64029   Parse *pParse = pNC->pParse;
   64030   SrcList *pSrcList = pNC->pSrcList;
   64031   AggInfo *pAggInfo = pNC->pAggInfo;
   64032 
   64033   switch( pExpr->op ){
   64034     case TK_AGG_COLUMN:
   64035     case TK_COLUMN: {
   64036       testcase( pExpr->op==TK_AGG_COLUMN );
   64037       testcase( pExpr->op==TK_COLUMN );
   64038       /* Check to see if the column is in one of the tables in the FROM
   64039       ** clause of the aggregate query */
   64040       if( ALWAYS(pSrcList!=0) ){
   64041         struct SrcList_item *pItem = pSrcList->a;
   64042         for(i=0; i<pSrcList->nSrc; i++, pItem++){
   64043           struct AggInfo_col *pCol;
   64044           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   64045           if( pExpr->iTable==pItem->iCursor ){
   64046             /* If we reach this point, it means that pExpr refers to a table
   64047             ** that is in the FROM clause of the aggregate query.
   64048             **
   64049             ** Make an entry for the column in pAggInfo->aCol[] if there
   64050             ** is not an entry there already.
   64051             */
   64052             int k;
   64053             pCol = pAggInfo->aCol;
   64054             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
   64055               if( pCol->iTable==pExpr->iTable &&
   64056                   pCol->iColumn==pExpr->iColumn ){
   64057                 break;
   64058               }
   64059             }
   64060             if( (k>=pAggInfo->nColumn)
   64061              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
   64062             ){
   64063               pCol = &pAggInfo->aCol[k];
   64064               pCol->pTab = pExpr->pTab;
   64065               pCol->iTable = pExpr->iTable;
   64066               pCol->iColumn = pExpr->iColumn;
   64067               pCol->iMem = ++pParse->nMem;
   64068               pCol->iSorterColumn = -1;
   64069               pCol->pExpr = pExpr;
   64070               if( pAggInfo->pGroupBy ){
   64071                 int j, n;
   64072                 ExprList *pGB = pAggInfo->pGroupBy;
   64073                 struct ExprList_item *pTerm = pGB->a;
   64074                 n = pGB->nExpr;
   64075                 for(j=0; j<n; j++, pTerm++){
   64076                   Expr *pE = pTerm->pExpr;
   64077                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
   64078                       pE->iColumn==pExpr->iColumn ){
   64079                     pCol->iSorterColumn = j;
   64080                     break;
   64081                   }
   64082                 }
   64083               }
   64084               if( pCol->iSorterColumn<0 ){
   64085                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
   64086               }
   64087             }
   64088             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
   64089             ** because it was there before or because we just created it).
   64090             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
   64091             ** pAggInfo->aCol[] entry.
   64092             */
   64093             ExprSetIrreducible(pExpr);
   64094             pExpr->pAggInfo = pAggInfo;
   64095             pExpr->op = TK_AGG_COLUMN;
   64096             pExpr->iAgg = (i16)k;
   64097             break;
   64098           } /* endif pExpr->iTable==pItem->iCursor */
   64099         } /* end loop over pSrcList */
   64100       }
   64101       return WRC_Prune;
   64102     }
   64103     case TK_AGG_FUNCTION: {
   64104       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
   64105       ** to be ignored */
   64106       if( pNC->nDepth==0 ){
   64107         /* Check to see if pExpr is a duplicate of another aggregate
   64108         ** function that is already in the pAggInfo structure
   64109         */
   64110         struct AggInfo_func *pItem = pAggInfo->aFunc;
   64111         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
   64112           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
   64113             break;
   64114           }
   64115         }
   64116         if( i>=pAggInfo->nFunc ){
   64117           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
   64118           */
   64119           u8 enc = ENC(pParse->db);
   64120           i = addAggInfoFunc(pParse->db, pAggInfo);
   64121           if( i>=0 ){
   64122             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   64123             pItem = &pAggInfo->aFunc[i];
   64124             pItem->pExpr = pExpr;
   64125             pItem->iMem = ++pParse->nMem;
   64126             assert( !ExprHasProperty(pExpr, EP_IntValue) );
   64127             pItem->pFunc = sqlite3FindFunction(pParse->db,
   64128                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
   64129                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
   64130             if( pExpr->flags & EP_Distinct ){
   64131               pItem->iDistinct = pParse->nTab++;
   64132             }else{
   64133               pItem->iDistinct = -1;
   64134             }
   64135           }
   64136         }
   64137         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
   64138         */
   64139         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   64140         ExprSetIrreducible(pExpr);
   64141         pExpr->iAgg = (i16)i;
   64142         pExpr->pAggInfo = pAggInfo;
   64143         return WRC_Prune;
   64144       }
   64145     }
   64146   }
   64147   return WRC_Continue;
   64148 }
   64149 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
   64150   NameContext *pNC = pWalker->u.pNC;
   64151   if( pNC->nDepth==0 ){
   64152     pNC->nDepth++;
   64153     sqlite3WalkSelect(pWalker, pSelect);
   64154     pNC->nDepth--;
   64155     return WRC_Prune;
   64156   }else{
   64157     return WRC_Continue;
   64158   }
   64159 }
   64160 
   64161 /*
   64162 ** Analyze the given expression looking for aggregate functions and
   64163 ** for variables that need to be added to the pParse->aAgg[] array.
   64164 ** Make additional entries to the pParse->aAgg[] array as necessary.
   64165 **
   64166 ** This routine should only be called after the expression has been
   64167 ** analyzed by sqlite3ResolveExprNames().
   64168 */
   64169 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
   64170   Walker w;
   64171   w.xExprCallback = analyzeAggregate;
   64172   w.xSelectCallback = analyzeAggregatesInSelect;
   64173   w.u.pNC = pNC;
   64174   assert( pNC->pSrcList!=0 );
   64175   sqlite3WalkExpr(&w, pExpr);
   64176 }
   64177 
   64178 /*
   64179 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
   64180 ** expression list.  Return the number of errors.
   64181 **
   64182 ** If an error is found, the analysis is cut short.
   64183 */
   64184 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
   64185   struct ExprList_item *pItem;
   64186   int i;
   64187   if( pList ){
   64188     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
   64189       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
   64190     }
   64191   }
   64192 }
   64193 
   64194 /*
   64195 ** Allocate a single new register for use to hold some intermediate result.
   64196 */
   64197 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
   64198   if( pParse->nTempReg==0 ){
   64199     return ++pParse->nMem;
   64200   }
   64201   return pParse->aTempReg[--pParse->nTempReg];
   64202 }
   64203 
   64204 /*
   64205 ** Deallocate a register, making available for reuse for some other
   64206 ** purpose.
   64207 **
   64208 ** If a register is currently being used by the column cache, then
   64209 ** the dallocation is deferred until the column cache line that uses
   64210 ** the register becomes stale.
   64211 */
   64212 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
   64213   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
   64214     int i;
   64215     struct yColCache *p;
   64216     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   64217       if( p->iReg==iReg ){
   64218         p->tempReg = 1;
   64219         return;
   64220       }
   64221     }
   64222     pParse->aTempReg[pParse->nTempReg++] = iReg;
   64223   }
   64224 }
   64225 
   64226 /*
   64227 ** Allocate or deallocate a block of nReg consecutive registers
   64228 */
   64229 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
   64230   int i, n;
   64231   i = pParse->iRangeReg;
   64232   n = pParse->nRangeReg;
   64233   if( nReg<=n ){
   64234     assert( !usedAsColumnCache(pParse, i, i+n-1) );
   64235     pParse->iRangeReg += nReg;
   64236     pParse->nRangeReg -= nReg;
   64237   }else{
   64238     i = pParse->nMem+1;
   64239     pParse->nMem += nReg;
   64240   }
   64241   return i;
   64242 }
   64243 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
   64244   sqlite3ExprCacheRemove(pParse, iReg, nReg);
   64245   if( nReg>pParse->nRangeReg ){
   64246     pParse->nRangeReg = nReg;
   64247     pParse->iRangeReg = iReg;
   64248   }
   64249 }
   64250 
   64251 /************** End of expr.c ************************************************/
   64252 /************** Begin file alter.c *******************************************/
   64253 /*
   64254 ** 2005 February 15
   64255 **
   64256 ** The author disclaims copyright to this source code.  In place of
   64257 ** a legal notice, here is a blessing:
   64258 **
   64259 **    May you do good and not evil.
   64260 **    May you find forgiveness for yourself and forgive others.
   64261 **    May you share freely, never taking more than you give.
   64262 **
   64263 *************************************************************************
   64264 ** This file contains C code routines that used to generate VDBE code
   64265 ** that implements the ALTER TABLE command.
   64266 */
   64267 
   64268 /*
   64269 ** The code in this file only exists if we are not omitting the
   64270 ** ALTER TABLE logic from the build.
   64271 */
   64272 #ifndef SQLITE_OMIT_ALTERTABLE
   64273 
   64274 
   64275 /*
   64276 ** This function is used by SQL generated to implement the
   64277 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
   64278 ** CREATE INDEX command. The second is a table name. The table name in
   64279 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
   64280 ** argument and the result returned. Examples:
   64281 **
   64282 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
   64283 **     -> 'CREATE TABLE def(a, b, c)'
   64284 **
   64285 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
   64286 **     -> 'CREATE INDEX i ON def(a, b, c)'
   64287 */
   64288 static void renameTableFunc(
   64289   sqlite3_context *context,
   64290   int NotUsed,
   64291   sqlite3_value **argv
   64292 ){
   64293   unsigned char const *zSql = sqlite3_value_text(argv[0]);
   64294   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
   64295 
   64296   int token;
   64297   Token tname;
   64298   unsigned char const *zCsr = zSql;
   64299   int len = 0;
   64300   char *zRet;
   64301 
   64302   sqlite3 *db = sqlite3_context_db_handle(context);
   64303 
   64304   UNUSED_PARAMETER(NotUsed);
   64305 
   64306   /* The principle used to locate the table name in the CREATE TABLE
   64307   ** statement is that the table name is the first non-space token that
   64308   ** is immediately followed by a TK_LP or TK_USING token.
   64309   */
   64310   if( zSql ){
   64311     do {
   64312       if( !*zCsr ){
   64313         /* Ran out of input before finding an opening bracket. Return NULL. */
   64314         return;
   64315       }
   64316 
   64317       /* Store the token that zCsr points to in tname. */
   64318       tname.z = (char*)zCsr;
   64319       tname.n = len;
   64320 
   64321       /* Advance zCsr to the next token. Store that token type in 'token',
   64322       ** and its length in 'len' (to be used next iteration of this loop).
   64323       */
   64324       do {
   64325         zCsr += len;
   64326         len = sqlite3GetToken(zCsr, &token);
   64327       } while( token==TK_SPACE );
   64328       assert( len>0 );
   64329     } while( token!=TK_LP && token!=TK_USING );
   64330 
   64331     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
   64332        zTableName, tname.z+tname.n);
   64333     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
   64334   }
   64335 }
   64336 
   64337 /*
   64338 ** This C function implements an SQL user function that is used by SQL code
   64339 ** generated by the ALTER TABLE ... RENAME command to modify the definition
   64340 ** of any foreign key constraints that use the table being renamed as the
   64341 ** parent table. It is passed three arguments:
   64342 **
   64343 **   1) The complete text of the CREATE TABLE statement being modified,
   64344 **   2) The old name of the table being renamed, and
   64345 **   3) The new name of the table being renamed.
   64346 **
   64347 ** It returns the new CREATE TABLE statement. For example:
   64348 **
   64349 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
   64350 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
   64351 */
   64352 #ifndef SQLITE_OMIT_FOREIGN_KEY
   64353 static void renameParentFunc(
   64354   sqlite3_context *context,
   64355   int NotUsed,
   64356   sqlite3_value **argv
   64357 ){
   64358   sqlite3 *db = sqlite3_context_db_handle(context);
   64359   char *zOutput = 0;
   64360   char *zResult;
   64361   unsigned char const *zInput = sqlite3_value_text(argv[0]);
   64362   unsigned char const *zOld = sqlite3_value_text(argv[1]);
   64363   unsigned char const *zNew = sqlite3_value_text(argv[2]);
   64364 
   64365   unsigned const char *z;         /* Pointer to token */
   64366   int n;                          /* Length of token z */
   64367   int token;                      /* Type of token */
   64368 
   64369   UNUSED_PARAMETER(NotUsed);
   64370   for(z=zInput; *z; z=z+n){
   64371     n = sqlite3GetToken(z, &token);
   64372     if( token==TK_REFERENCES ){
   64373       char *zParent;
   64374       do {
   64375         z += n;
   64376         n = sqlite3GetToken(z, &token);
   64377       }while( token==TK_SPACE );
   64378 
   64379       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
   64380       if( zParent==0 ) break;
   64381       sqlite3Dequote(zParent);
   64382       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
   64383         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
   64384             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
   64385         );
   64386         sqlite3DbFree(db, zOutput);
   64387         zOutput = zOut;
   64388         zInput = &z[n];
   64389       }
   64390       sqlite3DbFree(db, zParent);
   64391     }
   64392   }
   64393 
   64394   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
   64395   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
   64396   sqlite3DbFree(db, zOutput);
   64397 }
   64398 #endif
   64399 
   64400 #ifndef SQLITE_OMIT_TRIGGER
   64401 /* This function is used by SQL generated to implement the
   64402 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
   64403 ** statement. The second is a table name. The table name in the CREATE
   64404 ** TRIGGER statement is replaced with the third argument and the result
   64405 ** returned. This is analagous to renameTableFunc() above, except for CREATE
   64406 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
   64407 */
   64408 static void renameTriggerFunc(
   64409   sqlite3_context *context,
   64410   int NotUsed,
   64411   sqlite3_value **argv
   64412 ){
   64413   unsigned char const *zSql = sqlite3_value_text(argv[0]);
   64414   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
   64415 
   64416   int token;
   64417   Token tname;
   64418   int dist = 3;
   64419   unsigned char const *zCsr = zSql;
   64420   int len = 0;
   64421   char *zRet;
   64422   sqlite3 *db = sqlite3_context_db_handle(context);
   64423 
   64424   UNUSED_PARAMETER(NotUsed);
   64425 
   64426   /* The principle used to locate the table name in the CREATE TRIGGER
   64427   ** statement is that the table name is the first token that is immediatedly
   64428   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
   64429   ** of TK_WHEN, TK_BEGIN or TK_FOR.
   64430   */
   64431   if( zSql ){
   64432     do {
   64433 
   64434       if( !*zCsr ){
   64435         /* Ran out of input before finding the table name. Return NULL. */
   64436         return;
   64437       }
   64438 
   64439       /* Store the token that zCsr points to in tname. */
   64440       tname.z = (char*)zCsr;
   64441       tname.n = len;
   64442 
   64443       /* Advance zCsr to the next token. Store that token type in 'token',
   64444       ** and its length in 'len' (to be used next iteration of this loop).
   64445       */
   64446       do {
   64447         zCsr += len;
   64448         len = sqlite3GetToken(zCsr, &token);
   64449       }while( token==TK_SPACE );
   64450       assert( len>0 );
   64451 
   64452       /* Variable 'dist' stores the number of tokens read since the most
   64453       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
   64454       ** token is read and 'dist' equals 2, the condition stated above
   64455       ** to be met.
   64456       **
   64457       ** Note that ON cannot be a database, table or column name, so
   64458       ** there is no need to worry about syntax like
   64459       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
   64460       */
   64461       dist++;
   64462       if( token==TK_DOT || token==TK_ON ){
   64463         dist = 0;
   64464       }
   64465     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
   64466 
   64467     /* Variable tname now contains the token that is the old table-name
   64468     ** in the CREATE TRIGGER statement.
   64469     */
   64470     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
   64471        zTableName, tname.z+tname.n);
   64472     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
   64473   }
   64474 }
   64475 #endif   /* !SQLITE_OMIT_TRIGGER */
   64476 
   64477 /*
   64478 ** Register built-in functions used to help implement ALTER TABLE
   64479 */
   64480 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
   64481   sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
   64482                          renameTableFunc, 0, 0);
   64483 #ifndef SQLITE_OMIT_TRIGGER
   64484   sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
   64485                          renameTriggerFunc, 0, 0);
   64486 #endif
   64487 #ifndef SQLITE_OMIT_FOREIGN_KEY
   64488   sqlite3CreateFunc(db, "sqlite_rename_parent", 3, SQLITE_UTF8, 0,
   64489                          renameParentFunc, 0, 0);
   64490 #endif
   64491 }
   64492 
   64493 /*
   64494 ** This function is used to create the text of expressions of the form:
   64495 **
   64496 **   name=<constant1> OR name=<constant2> OR ...
   64497 **
   64498 ** If argument zWhere is NULL, then a pointer string containing the text
   64499 ** "name=<constant>" is returned, where <constant> is the quoted version
   64500 ** of the string passed as argument zConstant. The returned buffer is
   64501 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
   64502 ** caller to ensure that it is eventually freed.
   64503 **
   64504 ** If argument zWhere is not NULL, then the string returned is
   64505 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
   64506 ** In this case zWhere is passed to sqlite3DbFree() before returning.
   64507 **
   64508 */
   64509 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
   64510   char *zNew;
   64511   if( !zWhere ){
   64512     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
   64513   }else{
   64514     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
   64515     sqlite3DbFree(db, zWhere);
   64516   }
   64517   return zNew;
   64518 }
   64519 
   64520 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   64521 /*
   64522 ** Generate the text of a WHERE expression which can be used to select all
   64523 ** tables that have foreign key constraints that refer to table pTab (i.e.
   64524 ** constraints for which pTab is the parent table) from the sqlite_master
   64525 ** table.
   64526 */
   64527 static char *whereForeignKeys(Parse *pParse, Table *pTab){
   64528   FKey *p;
   64529   char *zWhere = 0;
   64530   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   64531     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
   64532   }
   64533   return zWhere;
   64534 }
   64535 #endif
   64536 
   64537 /*
   64538 ** Generate the text of a WHERE expression which can be used to select all
   64539 ** temporary triggers on table pTab from the sqlite_temp_master table. If
   64540 ** table pTab has no temporary triggers, or is itself stored in the
   64541 ** temporary database, NULL is returned.
   64542 */
   64543 static char *whereTempTriggers(Parse *pParse, Table *pTab){
   64544   Trigger *pTrig;
   64545   char *zWhere = 0;
   64546   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
   64547 
   64548   /* If the table is not located in the temp-db (in which case NULL is
   64549   ** returned, loop through the tables list of triggers. For each trigger
   64550   ** that is not part of the temp-db schema, add a clause to the WHERE
   64551   ** expression being built up in zWhere.
   64552   */
   64553   if( pTab->pSchema!=pTempSchema ){
   64554     sqlite3 *db = pParse->db;
   64555     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
   64556       if( pTrig->pSchema==pTempSchema ){
   64557         zWhere = whereOrName(db, zWhere, pTrig->zName);
   64558       }
   64559     }
   64560   }
   64561   return zWhere;
   64562 }
   64563 
   64564 /*
   64565 ** Generate code to drop and reload the internal representation of table
   64566 ** pTab from the database, including triggers and temporary triggers.
   64567 ** Argument zName is the name of the table in the database schema at
   64568 ** the time the generated code is executed. This can be different from
   64569 ** pTab->zName if this function is being called to code part of an
   64570 ** "ALTER TABLE RENAME TO" statement.
   64571 */
   64572 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
   64573   Vdbe *v;
   64574   char *zWhere;
   64575   int iDb;                   /* Index of database containing pTab */
   64576 #ifndef SQLITE_OMIT_TRIGGER
   64577   Trigger *pTrig;
   64578 #endif
   64579 
   64580   v = sqlite3GetVdbe(pParse);
   64581   if( NEVER(v==0) ) return;
   64582   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   64583   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   64584   assert( iDb>=0 );
   64585 
   64586 #ifndef SQLITE_OMIT_TRIGGER
   64587   /* Drop any table triggers from the internal schema. */
   64588   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
   64589     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
   64590     assert( iTrigDb==iDb || iTrigDb==1 );
   64591     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
   64592   }
   64593 #endif
   64594 
   64595   /* Drop the table and index from the internal schema.  */
   64596   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
   64597 
   64598   /* Reload the table, index and permanent trigger schemas. */
   64599   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
   64600   if( !zWhere ) return;
   64601   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
   64602 
   64603 #ifndef SQLITE_OMIT_TRIGGER
   64604   /* Now, if the table is not stored in the temp database, reload any temp
   64605   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
   64606   */
   64607   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
   64608     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
   64609   }
   64610 #endif
   64611 }
   64612 
   64613 /*
   64614 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
   64615 ** command.
   64616 */
   64617 SQLITE_PRIVATE void sqlite3AlterRenameTable(
   64618   Parse *pParse,            /* Parser context. */
   64619   SrcList *pSrc,            /* The table to rename. */
   64620   Token *pName              /* The new table name. */
   64621 ){
   64622   int iDb;                  /* Database that contains the table */
   64623   char *zDb;                /* Name of database iDb */
   64624   Table *pTab;              /* Table being renamed */
   64625   char *zName = 0;          /* NULL-terminated version of pName */
   64626   sqlite3 *db = pParse->db; /* Database connection */
   64627   int nTabName;             /* Number of UTF-8 characters in zTabName */
   64628   const char *zTabName;     /* Original name of the table */
   64629   Vdbe *v;
   64630 #ifndef SQLITE_OMIT_TRIGGER
   64631   char *zWhere = 0;         /* Where clause to locate temp triggers */
   64632 #endif
   64633   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
   64634 
   64635   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
   64636   assert( pSrc->nSrc==1 );
   64637   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   64638 
   64639   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
   64640   if( !pTab ) goto exit_rename_table;
   64641   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   64642   zDb = db->aDb[iDb].zName;
   64643 
   64644   /* Get a NULL terminated version of the new table name. */
   64645   zName = sqlite3NameFromToken(db, pName);
   64646   if( !zName ) goto exit_rename_table;
   64647 
   64648   /* Check that a table or index named 'zName' does not already exist
   64649   ** in database iDb. If so, this is an error.
   64650   */
   64651   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
   64652     sqlite3ErrorMsg(pParse,
   64653         "there is already another table or index with this name: %s", zName);
   64654     goto exit_rename_table;
   64655   }
   64656 
   64657   /* Make sure it is not a system table being altered, or a reserved name
   64658   ** that the table is being renamed to.
   64659   */
   64660   if( sqlite3Strlen30(pTab->zName)>6
   64661    && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
   64662   ){
   64663     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
   64664     goto exit_rename_table;
   64665   }
   64666   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   64667     goto exit_rename_table;
   64668   }
   64669 
   64670 #ifndef SQLITE_OMIT_VIEW
   64671   if( pTab->pSelect ){
   64672     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
   64673     goto exit_rename_table;
   64674   }
   64675 #endif
   64676 
   64677 #ifndef SQLITE_OMIT_AUTHORIZATION
   64678   /* Invoke the authorization callback. */
   64679   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
   64680     goto exit_rename_table;
   64681   }
   64682 #endif
   64683 
   64684 #ifndef SQLITE_OMIT_VIRTUALTABLE
   64685   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   64686     goto exit_rename_table;
   64687   }
   64688   if( IsVirtual(pTab) ){
   64689     pVTab = sqlite3GetVTable(db, pTab);
   64690     if( pVTab->pVtab->pModule->xRename==0 ){
   64691       pVTab = 0;
   64692     }
   64693   }
   64694 #endif
   64695 
   64696   /* Begin a transaction and code the VerifyCookie for database iDb.
   64697   ** Then modify the schema cookie (since the ALTER TABLE modifies the
   64698   ** schema). Open a statement transaction if the table is a virtual
   64699   ** table.
   64700   */
   64701   v = sqlite3GetVdbe(pParse);
   64702   if( v==0 ){
   64703     goto exit_rename_table;
   64704   }
   64705   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
   64706   sqlite3ChangeCookie(pParse, iDb);
   64707 
   64708   /* If this is a virtual table, invoke the xRename() function if
   64709   ** one is defined. The xRename() callback will modify the names
   64710   ** of any resources used by the v-table implementation (including other
   64711   ** SQLite tables) that are identified by the name of the virtual table.
   64712   */
   64713 #ifndef SQLITE_OMIT_VIRTUALTABLE
   64714   if( pVTab ){
   64715     int i = ++pParse->nMem;
   64716     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
   64717     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
   64718     sqlite3MayAbort(pParse);
   64719   }
   64720 #endif
   64721 
   64722   /* figure out how many UTF-8 characters are in zName */
   64723   zTabName = pTab->zName;
   64724   nTabName = sqlite3Utf8CharLen(zTabName, -1);
   64725 
   64726 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   64727   if( db->flags&SQLITE_ForeignKeys ){
   64728     /* If foreign-key support is enabled, rewrite the CREATE TABLE
   64729     ** statements corresponding to all child tables of foreign key constraints
   64730     ** for which the renamed table is the parent table.  */
   64731     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
   64732       sqlite3NestedParse(pParse,
   64733           "UPDATE sqlite_master SET "
   64734               "sql = sqlite_rename_parent(sql, %Q, %Q) "
   64735               "WHERE %s;", zTabName, zName, zWhere);
   64736       sqlite3DbFree(db, zWhere);
   64737     }
   64738   }
   64739 #endif
   64740 
   64741   /* Modify the sqlite_master table to use the new table name. */
   64742   sqlite3NestedParse(pParse,
   64743       "UPDATE %Q.%s SET "
   64744 #ifdef SQLITE_OMIT_TRIGGER
   64745           "sql = sqlite_rename_table(sql, %Q), "
   64746 #else
   64747           "sql = CASE "
   64748             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
   64749             "ELSE sqlite_rename_table(sql, %Q) END, "
   64750 #endif
   64751           "tbl_name = %Q, "
   64752           "name = CASE "
   64753             "WHEN type='table' THEN %Q "
   64754             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
   64755              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
   64756             "ELSE name END "
   64757       "WHERE tbl_name=%Q AND "
   64758           "(type='table' OR type='index' OR type='trigger');",
   64759       zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
   64760 #ifndef SQLITE_OMIT_TRIGGER
   64761       zName,
   64762 #endif
   64763       zName, nTabName, zTabName
   64764   );
   64765 
   64766 #ifndef SQLITE_OMIT_AUTOINCREMENT
   64767   /* If the sqlite_sequence table exists in this database, then update
   64768   ** it with the new table name.
   64769   */
   64770   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
   64771     sqlite3NestedParse(pParse,
   64772         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
   64773         zDb, zName, pTab->zName);
   64774   }
   64775 #endif
   64776 
   64777 #ifndef SQLITE_OMIT_TRIGGER
   64778   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
   64779   ** table. Don't do this if the table being ALTERed is itself located in
   64780   ** the temp database.
   64781   */
   64782   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
   64783     sqlite3NestedParse(pParse,
   64784         "UPDATE sqlite_temp_master SET "
   64785             "sql = sqlite_rename_trigger(sql, %Q), "
   64786             "tbl_name = %Q "
   64787             "WHERE %s;", zName, zName, zWhere);
   64788     sqlite3DbFree(db, zWhere);
   64789   }
   64790 #endif
   64791 
   64792 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   64793   if( db->flags&SQLITE_ForeignKeys ){
   64794     FKey *p;
   64795     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   64796       Table *pFrom = p->pFrom;
   64797       if( pFrom!=pTab ){
   64798         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
   64799       }
   64800     }
   64801   }
   64802 #endif
   64803 
   64804   /* Drop and reload the internal table schema. */
   64805   reloadTableSchema(pParse, pTab, zName);
   64806 
   64807 exit_rename_table:
   64808   sqlite3SrcListDelete(db, pSrc);
   64809   sqlite3DbFree(db, zName);
   64810 }
   64811 
   64812 
   64813 /*
   64814 ** Generate code to make sure the file format number is at least minFormat.
   64815 ** The generated code will increase the file format number if necessary.
   64816 */
   64817 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
   64818   Vdbe *v;
   64819   v = sqlite3GetVdbe(pParse);
   64820   /* The VDBE should have been allocated before this routine is called.
   64821   ** If that allocation failed, we would have quit before reaching this
   64822   ** point */
   64823   if( ALWAYS(v) ){
   64824     int r1 = sqlite3GetTempReg(pParse);
   64825     int r2 = sqlite3GetTempReg(pParse);
   64826     int j1;
   64827     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
   64828     sqlite3VdbeUsesBtree(v, iDb);
   64829     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
   64830     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
   64831     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
   64832     sqlite3VdbeJumpHere(v, j1);
   64833     sqlite3ReleaseTempReg(pParse, r1);
   64834     sqlite3ReleaseTempReg(pParse, r2);
   64835   }
   64836 }
   64837 
   64838 /*
   64839 ** This function is called after an "ALTER TABLE ... ADD" statement
   64840 ** has been parsed. Argument pColDef contains the text of the new
   64841 ** column definition.
   64842 **
   64843 ** The Table structure pParse->pNewTable was extended to include
   64844 ** the new column during parsing.
   64845 */
   64846 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
   64847   Table *pNew;              /* Copy of pParse->pNewTable */
   64848   Table *pTab;              /* Table being altered */
   64849   int iDb;                  /* Database number */
   64850   const char *zDb;          /* Database name */
   64851   const char *zTab;         /* Table name */
   64852   char *zCol;               /* Null-terminated column definition */
   64853   Column *pCol;             /* The new column */
   64854   Expr *pDflt;              /* Default value for the new column */
   64855   sqlite3 *db;              /* The database connection; */
   64856 
   64857   db = pParse->db;
   64858   if( pParse->nErr || db->mallocFailed ) return;
   64859   pNew = pParse->pNewTable;
   64860   assert( pNew );
   64861 
   64862   assert( sqlite3BtreeHoldsAllMutexes(db) );
   64863   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
   64864   zDb = db->aDb[iDb].zName;
   64865   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
   64866   pCol = &pNew->aCol[pNew->nCol-1];
   64867   pDflt = pCol->pDflt;
   64868   pTab = sqlite3FindTable(db, zTab, zDb);
   64869   assert( pTab );
   64870 
   64871 #ifndef SQLITE_OMIT_AUTHORIZATION
   64872   /* Invoke the authorization callback. */
   64873   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
   64874     return;
   64875   }
   64876 #endif
   64877 
   64878   /* If the default value for the new column was specified with a
   64879   ** literal NULL, then set pDflt to 0. This simplifies checking
   64880   ** for an SQL NULL default below.
   64881   */
   64882   if( pDflt && pDflt->op==TK_NULL ){
   64883     pDflt = 0;
   64884   }
   64885 
   64886   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
   64887   ** If there is a NOT NULL constraint, then the default value for the
   64888   ** column must not be NULL.
   64889   */
   64890   if( pCol->isPrimKey ){
   64891     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
   64892     return;
   64893   }
   64894   if( pNew->pIndex ){
   64895     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
   64896     return;
   64897   }
   64898   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
   64899     sqlite3ErrorMsg(pParse,
   64900         "Cannot add a REFERENCES column with non-NULL default value");
   64901     return;
   64902   }
   64903   if( pCol->notNull && !pDflt ){
   64904     sqlite3ErrorMsg(pParse,
   64905         "Cannot add a NOT NULL column with default value NULL");
   64906     return;
   64907   }
   64908 
   64909   /* Ensure the default expression is something that sqlite3ValueFromExpr()
   64910   ** can handle (i.e. not CURRENT_TIME etc.)
   64911   */
   64912   if( pDflt ){
   64913     sqlite3_value *pVal;
   64914     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
   64915       db->mallocFailed = 1;
   64916       return;
   64917     }
   64918     if( !pVal ){
   64919       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
   64920       return;
   64921     }
   64922     sqlite3ValueFree(pVal);
   64923   }
   64924 
   64925   /* Modify the CREATE TABLE statement. */
   64926   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
   64927   if( zCol ){
   64928     char *zEnd = &zCol[pColDef->n-1];
   64929     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
   64930       *zEnd-- = '\0';
   64931     }
   64932     sqlite3NestedParse(pParse,
   64933         "UPDATE \"%w\".%s SET "
   64934           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
   64935         "WHERE type = 'table' AND name = %Q",
   64936       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
   64937       zTab
   64938     );
   64939     sqlite3DbFree(db, zCol);
   64940   }
   64941 
   64942   /* If the default value of the new column is NULL, then set the file
   64943   ** format to 2. If the default value of the new column is not NULL,
   64944   ** the file format becomes 3.
   64945   */
   64946   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
   64947 
   64948   /* Reload the schema of the modified table. */
   64949   reloadTableSchema(pParse, pTab, pTab->zName);
   64950 }
   64951 
   64952 /*
   64953 ** This function is called by the parser after the table-name in
   64954 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
   64955 ** pSrc is the full-name of the table being altered.
   64956 **
   64957 ** This routine makes a (partial) copy of the Table structure
   64958 ** for the table being altered and sets Parse.pNewTable to point
   64959 ** to it. Routines called by the parser as the column definition
   64960 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
   64961 ** the copy. The copy of the Table structure is deleted by tokenize.c
   64962 ** after parsing is finished.
   64963 **
   64964 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
   64965 ** coding the "ALTER TABLE ... ADD" statement.
   64966 */
   64967 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
   64968   Table *pNew;
   64969   Table *pTab;
   64970   Vdbe *v;
   64971   int iDb;
   64972   int i;
   64973   int nAlloc;
   64974   sqlite3 *db = pParse->db;
   64975 
   64976   /* Look up the table being altered. */
   64977   assert( pParse->pNewTable==0 );
   64978   assert( sqlite3BtreeHoldsAllMutexes(db) );
   64979   if( db->mallocFailed ) goto exit_begin_add_column;
   64980   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
   64981   if( !pTab ) goto exit_begin_add_column;
   64982 
   64983 #ifndef SQLITE_OMIT_VIRTUALTABLE
   64984   if( IsVirtual(pTab) ){
   64985     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
   64986     goto exit_begin_add_column;
   64987   }
   64988 #endif
   64989 
   64990   /* Make sure this is not an attempt to ALTER a view. */
   64991   if( pTab->pSelect ){
   64992     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
   64993     goto exit_begin_add_column;
   64994   }
   64995 
   64996   assert( pTab->addColOffset>0 );
   64997   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   64998 
   64999   /* Put a copy of the Table struct in Parse.pNewTable for the
   65000   ** sqlite3AddColumn() function and friends to modify.  But modify
   65001   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
   65002   ** prefix, we insure that the name will not collide with an existing
   65003   ** table because user table are not allowed to have the "sqlite_"
   65004   ** prefix on their name.
   65005   */
   65006   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
   65007   if( !pNew ) goto exit_begin_add_column;
   65008   pParse->pNewTable = pNew;
   65009   pNew->nRef = 1;
   65010   pNew->dbMem = pTab->dbMem;
   65011   pNew->nCol = pTab->nCol;
   65012   assert( pNew->nCol>0 );
   65013   nAlloc = (((pNew->nCol-1)/8)*8)+8;
   65014   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
   65015   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
   65016   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
   65017   if( !pNew->aCol || !pNew->zName ){
   65018     db->mallocFailed = 1;
   65019     goto exit_begin_add_column;
   65020   }
   65021   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
   65022   for(i=0; i<pNew->nCol; i++){
   65023     Column *pCol = &pNew->aCol[i];
   65024     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
   65025     pCol->zColl = 0;
   65026     pCol->zType = 0;
   65027     pCol->pDflt = 0;
   65028     pCol->zDflt = 0;
   65029   }
   65030   pNew->pSchema = db->aDb[iDb].pSchema;
   65031   pNew->addColOffset = pTab->addColOffset;
   65032   pNew->nRef = 1;
   65033 
   65034   /* Begin a transaction and increment the schema cookie.  */
   65035   sqlite3BeginWriteOperation(pParse, 0, iDb);
   65036   v = sqlite3GetVdbe(pParse);
   65037   if( !v ) goto exit_begin_add_column;
   65038   sqlite3ChangeCookie(pParse, iDb);
   65039 
   65040 exit_begin_add_column:
   65041   sqlite3SrcListDelete(db, pSrc);
   65042   return;
   65043 }
   65044 #endif  /* SQLITE_ALTER_TABLE */
   65045 
   65046 /************** End of alter.c ***********************************************/
   65047 /************** Begin file analyze.c *****************************************/
   65048 /*
   65049 ** 2005 July 8
   65050 **
   65051 ** The author disclaims copyright to this source code.  In place of
   65052 ** a legal notice, here is a blessing:
   65053 **
   65054 **    May you do good and not evil.
   65055 **    May you find forgiveness for yourself and forgive others.
   65056 **    May you share freely, never taking more than you give.
   65057 **
   65058 *************************************************************************
   65059 ** This file contains code associated with the ANALYZE command.
   65060 */
   65061 #ifndef SQLITE_OMIT_ANALYZE
   65062 
   65063 /*
   65064 ** This routine generates code that opens the sqlite_stat1 table for
   65065 ** writing with cursor iStatCur. If the library was built with the
   65066 ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
   65067 ** opened for writing using cursor (iStatCur+1)
   65068 **
   65069 ** If the sqlite_stat1 tables does not previously exist, it is created.
   65070 ** Similarly, if the sqlite_stat2 table does not exist and the library
   65071 ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
   65072 **
   65073 ** Argument zWhere may be a pointer to a buffer containing a table name,
   65074 ** or it may be a NULL pointer. If it is not NULL, then all entries in
   65075 ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
   65076 ** with the named table are deleted. If zWhere==0, then code is generated
   65077 ** to delete all stat table entries.
   65078 */
   65079 static void openStatTable(
   65080   Parse *pParse,          /* Parsing context */
   65081   int iDb,                /* The database we are looking in */
   65082   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
   65083   const char *zWhere      /* Delete entries associated with this table */
   65084 ){
   65085   static struct {
   65086     const char *zName;
   65087     const char *zCols;
   65088   } aTable[] = {
   65089     { "sqlite_stat1", "tbl,idx,stat" },
   65090 #ifdef SQLITE_ENABLE_STAT2
   65091     { "sqlite_stat2", "tbl,idx,sampleno,sample" },
   65092 #endif
   65093   };
   65094 
   65095   int aRoot[] = {0, 0};
   65096   u8 aCreateTbl[] = {0, 0};
   65097 
   65098   int i;
   65099   sqlite3 *db = pParse->db;
   65100   Db *pDb;
   65101   Vdbe *v = sqlite3GetVdbe(pParse);
   65102   if( v==0 ) return;
   65103   assert( sqlite3BtreeHoldsAllMutexes(db) );
   65104   assert( sqlite3VdbeDb(v)==db );
   65105   pDb = &db->aDb[iDb];
   65106 
   65107   for(i=0; i<ArraySize(aTable); i++){
   65108     const char *zTab = aTable[i].zName;
   65109     Table *pStat;
   65110     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
   65111       /* The sqlite_stat[12] table does not exist. Create it. Note that a
   65112       ** side-effect of the CREATE TABLE statement is to leave the rootpage
   65113       ** of the new table in register pParse->regRoot. This is important
   65114       ** because the OpenWrite opcode below will be needing it. */
   65115       sqlite3NestedParse(pParse,
   65116           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
   65117       );
   65118       aRoot[i] = pParse->regRoot;
   65119       aCreateTbl[i] = 1;
   65120     }else{
   65121       /* The table already exists. If zWhere is not NULL, delete all entries
   65122       ** associated with the table zWhere. If zWhere is NULL, delete the
   65123       ** entire contents of the table. */
   65124       aRoot[i] = pStat->tnum;
   65125       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
   65126       if( zWhere ){
   65127         sqlite3NestedParse(pParse,
   65128            "DELETE FROM %Q.%s WHERE tbl=%Q", pDb->zName, zTab, zWhere
   65129         );
   65130       }else{
   65131         /* The sqlite_stat[12] table already exists.  Delete all rows. */
   65132         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
   65133       }
   65134     }
   65135   }
   65136 
   65137   /* Open the sqlite_stat[12] tables for writing. */
   65138   for(i=0; i<ArraySize(aTable); i++){
   65139     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
   65140     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
   65141     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
   65142   }
   65143 }
   65144 
   65145 /*
   65146 ** Generate code to do an analysis of all indices associated with
   65147 ** a single table.
   65148 */
   65149 static void analyzeOneTable(
   65150   Parse *pParse,   /* Parser context */
   65151   Table *pTab,     /* Table whose indices are to be analyzed */
   65152   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
   65153   int iMem         /* Available memory locations begin here */
   65154 ){
   65155   sqlite3 *db = pParse->db;    /* Database handle */
   65156   Index *pIdx;                 /* An index to being analyzed */
   65157   int iIdxCur;                 /* Cursor open on index being analyzed */
   65158   Vdbe *v;                     /* The virtual machine being built up */
   65159   int i;                       /* Loop counter */
   65160   int topOfLoop;               /* The top of the loop */
   65161   int endOfLoop;               /* The end of the loop */
   65162   int addr;                    /* The address of an instruction */
   65163   int iDb;                     /* Index of database containing pTab */
   65164   int regTabname = iMem++;     /* Register containing table name */
   65165   int regIdxname = iMem++;     /* Register containing index name */
   65166   int regSampleno = iMem++;    /* Register containing next sample number */
   65167   int regCol = iMem++;         /* Content of a column analyzed table */
   65168   int regRec = iMem++;         /* Register holding completed record */
   65169   int regTemp = iMem++;        /* Temporary use register */
   65170   int regRowid = iMem++;       /* Rowid for the inserted record */
   65171 
   65172 #ifdef SQLITE_ENABLE_STAT2
   65173   int regTemp2 = iMem++;       /* Temporary use register */
   65174   int regSamplerecno = iMem++; /* Index of next sample to record */
   65175   int regRecno = iMem++;       /* Current sample index */
   65176   int regLast = iMem++;        /* Index of last sample to record */
   65177   int regFirst = iMem++;       /* Index of first sample to record */
   65178 #endif
   65179 
   65180   v = sqlite3GetVdbe(pParse);
   65181   if( v==0 || NEVER(pTab==0) || pTab->pIndex==0 ){
   65182     /* Do no analysis for tables that have no indices */
   65183     return;
   65184   }
   65185   assert( sqlite3BtreeHoldsAllMutexes(db) );
   65186   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   65187   assert( iDb>=0 );
   65188 #ifndef SQLITE_OMIT_AUTHORIZATION
   65189   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
   65190       db->aDb[iDb].zName ) ){
   65191     return;
   65192   }
   65193 #endif
   65194 
   65195   /* Establish a read-lock on the table at the shared-cache level. */
   65196   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   65197 
   65198   iIdxCur = pParse->nTab++;
   65199   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   65200     int nCol = pIdx->nColumn;
   65201     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   65202 
   65203     if( iMem+1+(nCol*2)>pParse->nMem ){
   65204       pParse->nMem = iMem+1+(nCol*2);
   65205     }
   65206 
   65207     /* Open a cursor to the index to be analyzed. */
   65208     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
   65209     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
   65210         (char *)pKey, P4_KEYINFO_HANDOFF);
   65211     VdbeComment((v, "%s", pIdx->zName));
   65212 
   65213     /* Populate the registers containing the table and index names. */
   65214     if( pTab->pIndex==pIdx ){
   65215       sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
   65216     }
   65217     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
   65218 
   65219 #ifdef SQLITE_ENABLE_STAT2
   65220 
   65221     /* If this iteration of the loop is generating code to analyze the
   65222     ** first index in the pTab->pIndex list, then register regLast has
   65223     ** not been populated. In this case populate it now.  */
   65224     if( pTab->pIndex==pIdx ){
   65225       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
   65226       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
   65227       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
   65228 
   65229       sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
   65230       sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
   65231       addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
   65232       sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
   65233       sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
   65234       sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
   65235       sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
   65236       sqlite3VdbeJumpHere(v, addr);
   65237     }
   65238 
   65239     /* Zero the regSampleno and regRecno registers. */
   65240     sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
   65241     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
   65242     sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
   65243 #endif
   65244 
   65245     /* The block of memory cells initialized here is used as follows.
   65246     **
   65247     **    iMem:
   65248     **        The total number of rows in the table.
   65249     **
   65250     **    iMem+1 .. iMem+nCol:
   65251     **        Number of distinct entries in index considering the
   65252     **        left-most N columns only, where N is between 1 and nCol,
   65253     **        inclusive.
   65254     **
   65255     **    iMem+nCol+1 .. Mem+2*nCol:
   65256     **        Previous value of indexed columns, from left to right.
   65257     **
   65258     ** Cells iMem through iMem+nCol are initialized to 0. The others are
   65259     ** initialized to contain an SQL NULL.
   65260     */
   65261     for(i=0; i<=nCol; i++){
   65262       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
   65263     }
   65264     for(i=0; i<nCol; i++){
   65265       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
   65266     }
   65267 
   65268     /* Start the analysis loop. This loop runs through all the entries in
   65269     ** the index b-tree.  */
   65270     endOfLoop = sqlite3VdbeMakeLabel(v);
   65271     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
   65272     topOfLoop = sqlite3VdbeCurrentAddr(v);
   65273     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
   65274 
   65275     for(i=0; i<nCol; i++){
   65276       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
   65277 #ifdef SQLITE_ENABLE_STAT2
   65278       if( i==0 ){
   65279         /* Check if the record that cursor iIdxCur points to contains a
   65280         ** value that should be stored in the sqlite_stat2 table. If so,
   65281         ** store it.  */
   65282         int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
   65283         assert( regTabname+1==regIdxname
   65284              && regTabname+2==regSampleno
   65285              && regTabname+3==regCol
   65286         );
   65287         sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   65288         sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
   65289         sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
   65290         sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
   65291 
   65292         /* Calculate new values for regSamplerecno and regSampleno.
   65293         **
   65294         **   sampleno = sampleno + 1
   65295         **   samplerecno = samplerecno+(remaining records)/(remaining samples)
   65296         */
   65297         sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
   65298         sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
   65299         sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
   65300         sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
   65301         sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
   65302         sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
   65303         sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
   65304 
   65305         sqlite3VdbeJumpHere(v, ne);
   65306         sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
   65307       }
   65308 #endif
   65309 
   65310       sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
   65311       /**** TODO:  add collating sequence *****/
   65312       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   65313     }
   65314     if( db->mallocFailed ){
   65315       /* If a malloc failure has occurred, then the result of the expression
   65316       ** passed as the second argument to the call to sqlite3VdbeJumpHere()
   65317       ** below may be negative. Which causes an assert() to fail (or an
   65318       ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
   65319       return;
   65320     }
   65321     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
   65322     for(i=0; i<nCol; i++){
   65323       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-(nCol*2));
   65324       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
   65325       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
   65326     }
   65327 
   65328     /* End of the analysis loop. */
   65329     sqlite3VdbeResolveLabel(v, endOfLoop);
   65330     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
   65331     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
   65332 
   65333     /* Store the results in sqlite_stat1.
   65334     **
   65335     ** The result is a single row of the sqlite_stat1 table.  The first
   65336     ** two columns are the names of the table and index.  The third column
   65337     ** is a string composed of a list of integer statistics about the
   65338     ** index.  The first integer in the list is the total number of entries
   65339     ** in the index.  There is one additional integer in the list for each
   65340     ** column of the table.  This additional integer is a guess of how many
   65341     ** rows of the table the index will select.  If D is the count of distinct
   65342     ** values and K is the total number of rows, then the integer is computed
   65343     ** as:
   65344     **
   65345     **        I = (K+D-1)/D
   65346     **
   65347     ** If K==0 then no entry is made into the sqlite_stat1 table.
   65348     ** If K>0 then it is always the case the D>0 so division by zero
   65349     ** is never possible.
   65350     */
   65351     addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
   65352     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
   65353     for(i=0; i<nCol; i++){
   65354       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
   65355       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
   65356       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
   65357       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
   65358       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
   65359       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
   65360       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
   65361     }
   65362     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
   65363     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
   65364     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
   65365     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   65366     sqlite3VdbeJumpHere(v, addr);
   65367   }
   65368 }
   65369 
   65370 /*
   65371 ** Generate code that will cause the most recent index analysis to
   65372 ** be laoded into internal hash tables where is can be used.
   65373 */
   65374 static void loadAnalysis(Parse *pParse, int iDb){
   65375   Vdbe *v = sqlite3GetVdbe(pParse);
   65376   if( v ){
   65377     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
   65378   }
   65379 }
   65380 
   65381 /*
   65382 ** Generate code that will do an analysis of an entire database
   65383 */
   65384 static void analyzeDatabase(Parse *pParse, int iDb){
   65385   sqlite3 *db = pParse->db;
   65386   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
   65387   HashElem *k;
   65388   int iStatCur;
   65389   int iMem;
   65390 
   65391   sqlite3BeginWriteOperation(pParse, 0, iDb);
   65392   iStatCur = pParse->nTab;
   65393   pParse->nTab += 2;
   65394   openStatTable(pParse, iDb, iStatCur, 0);
   65395   iMem = pParse->nMem+1;
   65396   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
   65397     Table *pTab = (Table*)sqliteHashData(k);
   65398     analyzeOneTable(pParse, pTab, iStatCur, iMem);
   65399   }
   65400   loadAnalysis(pParse, iDb);
   65401 }
   65402 
   65403 /*
   65404 ** Generate code that will do an analysis of a single table in
   65405 ** a database.
   65406 */
   65407 static void analyzeTable(Parse *pParse, Table *pTab){
   65408   int iDb;
   65409   int iStatCur;
   65410 
   65411   assert( pTab!=0 );
   65412   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   65413   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   65414   sqlite3BeginWriteOperation(pParse, 0, iDb);
   65415   iStatCur = pParse->nTab;
   65416   pParse->nTab += 2;
   65417   openStatTable(pParse, iDb, iStatCur, pTab->zName);
   65418   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
   65419   loadAnalysis(pParse, iDb);
   65420 }
   65421 
   65422 /*
   65423 ** Generate code for the ANALYZE command.  The parser calls this routine
   65424 ** when it recognizes an ANALYZE command.
   65425 **
   65426 **        ANALYZE                            -- 1
   65427 **        ANALYZE  <database>                -- 2
   65428 **        ANALYZE  ?<database>.?<tablename>  -- 3
   65429 **
   65430 ** Form 1 causes all indices in all attached databases to be analyzed.
   65431 ** Form 2 analyzes all indices the single database named.
   65432 ** Form 3 analyzes all indices associated with the named table.
   65433 */
   65434 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
   65435   sqlite3 *db = pParse->db;
   65436   int iDb;
   65437   int i;
   65438   char *z, *zDb;
   65439   Table *pTab;
   65440   Token *pTableName;
   65441 
   65442   /* Read the database schema. If an error occurs, leave an error message
   65443   ** and code in pParse and return NULL. */
   65444   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   65445   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   65446     return;
   65447   }
   65448 
   65449   assert( pName2!=0 || pName1==0 );
   65450   if( pName1==0 ){
   65451     /* Form 1:  Analyze everything */
   65452     for(i=0; i<db->nDb; i++){
   65453       if( i==1 ) continue;  /* Do not analyze the TEMP database */
   65454       analyzeDatabase(pParse, i);
   65455     }
   65456   }else if( pName2->n==0 ){
   65457     /* Form 2:  Analyze the database or table named */
   65458     iDb = sqlite3FindDb(db, pName1);
   65459     if( iDb>=0 ){
   65460       analyzeDatabase(pParse, iDb);
   65461     }else{
   65462       z = sqlite3NameFromToken(db, pName1);
   65463       if( z ){
   65464         pTab = sqlite3LocateTable(pParse, 0, z, 0);
   65465         sqlite3DbFree(db, z);
   65466         if( pTab ){
   65467           analyzeTable(pParse, pTab);
   65468         }
   65469       }
   65470     }
   65471   }else{
   65472     /* Form 3: Analyze the fully qualified table name */
   65473     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
   65474     if( iDb>=0 ){
   65475       zDb = db->aDb[iDb].zName;
   65476       z = sqlite3NameFromToken(db, pTableName);
   65477       if( z ){
   65478         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
   65479         sqlite3DbFree(db, z);
   65480         if( pTab ){
   65481           analyzeTable(pParse, pTab);
   65482         }
   65483       }
   65484     }
   65485   }
   65486 }
   65487 
   65488 /*
   65489 ** Used to pass information from the analyzer reader through to the
   65490 ** callback routine.
   65491 */
   65492 typedef struct analysisInfo analysisInfo;
   65493 struct analysisInfo {
   65494   sqlite3 *db;
   65495   const char *zDatabase;
   65496 };
   65497 
   65498 /*
   65499 ** This callback is invoked once for each index when reading the
   65500 ** sqlite_stat1 table.
   65501 **
   65502 **     argv[0] = name of the index
   65503 **     argv[1] = results of analysis - on integer for each column
   65504 */
   65505 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
   65506   analysisInfo *pInfo = (analysisInfo*)pData;
   65507   Index *pIndex;
   65508   int i, c;
   65509   unsigned int v;
   65510   const char *z;
   65511 
   65512   assert( argc==2 );
   65513   UNUSED_PARAMETER2(NotUsed, argc);
   65514 
   65515   if( argv==0 || argv[0]==0 || argv[1]==0 ){
   65516     return 0;
   65517   }
   65518   pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
   65519   if( pIndex==0 ){
   65520     return 0;
   65521   }
   65522   z = argv[1];
   65523   for(i=0; *z && i<=pIndex->nColumn; i++){
   65524     v = 0;
   65525     while( (c=z[0])>='0' && c<='9' ){
   65526       v = v*10 + c - '0';
   65527       z++;
   65528     }
   65529     pIndex->aiRowEst[i] = v;
   65530     if( *z==' ' ) z++;
   65531   }
   65532   return 0;
   65533 }
   65534 
   65535 /*
   65536 ** If the Index.aSample variable is not NULL, delete the aSample[] array
   65537 ** and its contents.
   65538 */
   65539 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index *pIdx){
   65540 #ifdef SQLITE_ENABLE_STAT2
   65541   if( pIdx->aSample ){
   65542     int j;
   65543     sqlite3 *dbMem = pIdx->pTable->dbMem;
   65544     for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
   65545       IndexSample *p = &pIdx->aSample[j];
   65546       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
   65547         sqlite3DbFree(pIdx->pTable->dbMem, p->u.z);
   65548       }
   65549     }
   65550     sqlite3DbFree(dbMem, pIdx->aSample);
   65551     pIdx->aSample = 0;
   65552   }
   65553 #else
   65554   UNUSED_PARAMETER(pIdx);
   65555 #endif
   65556 }
   65557 
   65558 /*
   65559 ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
   65560 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
   65561 ** arrays. The contents of sqlite_stat2 are used to populate the
   65562 ** Index.aSample[] arrays.
   65563 **
   65564 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
   65565 ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
   65566 ** during compilation and the sqlite_stat2 table is present, no data is
   65567 ** read from it.
   65568 **
   65569 ** If SQLITE_ENABLE_STAT2 was defined during compilation and the
   65570 ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
   65571 ** returned. However, in this case, data is read from the sqlite_stat1
   65572 ** table (if it is present) before returning.
   65573 **
   65574 ** If an OOM error occurs, this function always sets db->mallocFailed.
   65575 ** This means if the caller does not care about other errors, the return
   65576 ** code may be ignored.
   65577 */
   65578 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
   65579   analysisInfo sInfo;
   65580   HashElem *i;
   65581   char *zSql;
   65582   int rc;
   65583 
   65584   assert( iDb>=0 && iDb<db->nDb );
   65585   assert( db->aDb[iDb].pBt!=0 );
   65586   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
   65587 
   65588   /* Clear any prior statistics */
   65589   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
   65590     Index *pIdx = sqliteHashData(i);
   65591     sqlite3DefaultRowEst(pIdx);
   65592     sqlite3DeleteIndexSamples(pIdx);
   65593   }
   65594 
   65595   /* Check to make sure the sqlite_stat1 table exists */
   65596   sInfo.db = db;
   65597   sInfo.zDatabase = db->aDb[iDb].zName;
   65598   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
   65599     return SQLITE_ERROR;
   65600   }
   65601 
   65602   /* Load new statistics out of the sqlite_stat1 table */
   65603   zSql = sqlite3MPrintf(db,
   65604       "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
   65605   if( zSql==0 ){
   65606     rc = SQLITE_NOMEM;
   65607   }else{
   65608     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
   65609     sqlite3DbFree(db, zSql);
   65610   }
   65611 
   65612 
   65613   /* Load the statistics from the sqlite_stat2 table. */
   65614 #ifdef SQLITE_ENABLE_STAT2
   65615   if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
   65616     rc = SQLITE_ERROR;
   65617   }
   65618   if( rc==SQLITE_OK ){
   65619     sqlite3_stmt *pStmt = 0;
   65620 
   65621     zSql = sqlite3MPrintf(db,
   65622         "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
   65623     if( !zSql ){
   65624       rc = SQLITE_NOMEM;
   65625     }else{
   65626       rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   65627       sqlite3DbFree(db, zSql);
   65628     }
   65629 
   65630     if( rc==SQLITE_OK ){
   65631       while( sqlite3_step(pStmt)==SQLITE_ROW ){
   65632         char *zIndex = (char *)sqlite3_column_text(pStmt, 0);
   65633         Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
   65634         if( pIdx ){
   65635           int iSample = sqlite3_column_int(pStmt, 1);
   65636           sqlite3 *dbMem = pIdx->pTable->dbMem;
   65637           assert( dbMem==db || dbMem==0 );
   65638           if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
   65639             int eType = sqlite3_column_type(pStmt, 2);
   65640 
   65641             if( pIdx->aSample==0 ){
   65642               static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
   65643               pIdx->aSample = (IndexSample *)sqlite3DbMallocZero(dbMem, sz);
   65644               if( pIdx->aSample==0 ){
   65645                 db->mallocFailed = 1;
   65646                 break;
   65647               }
   65648             }
   65649 
   65650             assert( pIdx->aSample );
   65651             {
   65652               IndexSample *pSample = &pIdx->aSample[iSample];
   65653               pSample->eType = (u8)eType;
   65654               if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
   65655                 pSample->u.r = sqlite3_column_double(pStmt, 2);
   65656               }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
   65657                 const char *z = (const char *)(
   65658                     (eType==SQLITE_BLOB) ?
   65659                     sqlite3_column_blob(pStmt, 2):
   65660                     sqlite3_column_text(pStmt, 2)
   65661                 );
   65662                 int n = sqlite3_column_bytes(pStmt, 2);
   65663                 if( n>24 ){
   65664                   n = 24;
   65665                 }
   65666                 pSample->nByte = (u8)n;
   65667                 pSample->u.z = sqlite3DbMallocRaw(dbMem, n);
   65668                 if( pSample->u.z ){
   65669                   memcpy(pSample->u.z, z, n);
   65670                 }else{
   65671                   db->mallocFailed = 1;
   65672                   break;
   65673                 }
   65674               }
   65675             }
   65676           }
   65677         }
   65678       }
   65679       rc = sqlite3_finalize(pStmt);
   65680     }
   65681   }
   65682 #endif
   65683 
   65684   if( rc==SQLITE_NOMEM ){
   65685     db->mallocFailed = 1;
   65686   }
   65687   return rc;
   65688 }
   65689 
   65690 
   65691 #endif /* SQLITE_OMIT_ANALYZE */
   65692 
   65693 /************** End of analyze.c *********************************************/
   65694 /************** Begin file attach.c ******************************************/
   65695 /*
   65696 ** 2003 April 6
   65697 **
   65698 ** The author disclaims copyright to this source code.  In place of
   65699 ** a legal notice, here is a blessing:
   65700 **
   65701 **    May you do good and not evil.
   65702 **    May you find forgiveness for yourself and forgive others.
   65703 **    May you share freely, never taking more than you give.
   65704 **
   65705 *************************************************************************
   65706 ** This file contains code used to implement the ATTACH and DETACH commands.
   65707 */
   65708 
   65709 #ifndef SQLITE_OMIT_ATTACH
   65710 /*
   65711 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
   65712 ** is slightly different from resolving a normal SQL expression, because simple
   65713 ** identifiers are treated as strings, not possible column names or aliases.
   65714 **
   65715 ** i.e. if the parser sees:
   65716 **
   65717 **     ATTACH DATABASE abc AS def
   65718 **
   65719 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
   65720 ** looking for columns of the same name.
   65721 **
   65722 ** This only applies to the root node of pExpr, so the statement:
   65723 **
   65724 **     ATTACH DATABASE abc||def AS 'db2'
   65725 **
   65726 ** will fail because neither abc or def can be resolved.
   65727 */
   65728 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
   65729 {
   65730   int rc = SQLITE_OK;
   65731   if( pExpr ){
   65732     if( pExpr->op!=TK_ID ){
   65733       rc = sqlite3ResolveExprNames(pName, pExpr);
   65734       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
   65735         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
   65736         return SQLITE_ERROR;
   65737       }
   65738     }else{
   65739       pExpr->op = TK_STRING;
   65740     }
   65741   }
   65742   return rc;
   65743 }
   65744 
   65745 /*
   65746 ** An SQL user-function registered to do the work of an ATTACH statement. The
   65747 ** three arguments to the function come directly from an attach statement:
   65748 **
   65749 **     ATTACH DATABASE x AS y KEY z
   65750 **
   65751 **     SELECT sqlite_attach(x, y, z)
   65752 **
   65753 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
   65754 ** third argument.
   65755 */
   65756 static void attachFunc(
   65757   sqlite3_context *context,
   65758   int NotUsed,
   65759   sqlite3_value **argv
   65760 ){
   65761   int i;
   65762   int rc = 0;
   65763   sqlite3 *db = sqlite3_context_db_handle(context);
   65764   const char *zName;
   65765   const char *zFile;
   65766   Db *aNew;
   65767   char *zErrDyn = 0;
   65768 
   65769   UNUSED_PARAMETER(NotUsed);
   65770 
   65771   zFile = (const char *)sqlite3_value_text(argv[0]);
   65772   zName = (const char *)sqlite3_value_text(argv[1]);
   65773   if( zFile==0 ) zFile = "";
   65774   if( zName==0 ) zName = "";
   65775 
   65776   /* Check for the following errors:
   65777   **
   65778   **     * Too many attached databases,
   65779   **     * Transaction currently open
   65780   **     * Specified database name already being used.
   65781   */
   65782   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
   65783     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
   65784       db->aLimit[SQLITE_LIMIT_ATTACHED]
   65785     );
   65786     goto attach_error;
   65787   }
   65788   if( !db->autoCommit ){
   65789     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
   65790     goto attach_error;
   65791   }
   65792   for(i=0; i<db->nDb; i++){
   65793     char *z = db->aDb[i].zName;
   65794     assert( z && zName );
   65795     if( sqlite3StrICmp(z, zName)==0 ){
   65796       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
   65797       goto attach_error;
   65798     }
   65799   }
   65800 
   65801   /* Allocate the new entry in the db->aDb[] array and initialise the schema
   65802   ** hash tables.
   65803   */
   65804   if( db->aDb==db->aDbStatic ){
   65805     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
   65806     if( aNew==0 ) return;
   65807     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
   65808   }else{
   65809     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
   65810     if( aNew==0 ) return;
   65811   }
   65812   db->aDb = aNew;
   65813   aNew = &db->aDb[db->nDb];
   65814   memset(aNew, 0, sizeof(*aNew));
   65815 
   65816   /* Open the database file. If the btree is successfully opened, use
   65817   ** it to obtain the database schema. At this point the schema may
   65818   ** or may not be initialised.
   65819   */
   65820   rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
   65821                            db->openFlags | SQLITE_OPEN_MAIN_DB | SQLITE_OPEN_CREATE /* Android Change */,
   65822                            &aNew->pBt);
   65823   db->nDb++;
   65824   if( rc==SQLITE_CONSTRAINT ){
   65825     rc = SQLITE_ERROR;
   65826     zErrDyn = sqlite3MPrintf(db, "database is already attached");
   65827   }else if( rc==SQLITE_OK ){
   65828     Pager *pPager;
   65829     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
   65830     if( !aNew->pSchema ){
   65831       rc = SQLITE_NOMEM;
   65832     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
   65833       zErrDyn = sqlite3MPrintf(db,
   65834         "attached databases must use the same text encoding as main database");
   65835       rc = SQLITE_ERROR;
   65836     }
   65837     pPager = sqlite3BtreePager(aNew->pBt);
   65838     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
   65839     sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
   65840   }
   65841   aNew->safety_level = 3;
   65842   aNew->zName = sqlite3DbStrDup(db, zName);
   65843   if( rc==SQLITE_OK && aNew->zName==0 ){
   65844     rc = SQLITE_NOMEM;
   65845   }
   65846 
   65847 
   65848 #if SQLITE_HAS_CODEC
   65849   if( rc==SQLITE_OK ){
   65850     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
   65851     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
   65852     int nKey;
   65853     char *zKey;
   65854     int t = sqlite3_value_type(argv[2]);
   65855     switch( t ){
   65856       case SQLITE_INTEGER:
   65857       case SQLITE_FLOAT:
   65858         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
   65859         rc = SQLITE_ERROR;
   65860         break;
   65861 
   65862       case SQLITE_TEXT:
   65863       case SQLITE_BLOB:
   65864         nKey = sqlite3_value_bytes(argv[2]);
   65865         zKey = (char *)sqlite3_value_blob(argv[2]);
   65866         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
   65867         break;
   65868 
   65869       case SQLITE_NULL:
   65870         /* No key specified.  Use the key from the main database */
   65871         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
   65872         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
   65873         break;
   65874     }
   65875   }
   65876 #endif
   65877 
   65878   /* If the file was opened successfully, read the schema for the new database.
   65879   ** If this fails, or if opening the file failed, then close the file and
   65880   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
   65881   ** we found it.
   65882   */
   65883   if( rc==SQLITE_OK ){
   65884     sqlite3BtreeEnterAll(db);
   65885     rc = sqlite3Init(db, &zErrDyn);
   65886     sqlite3BtreeLeaveAll(db);
   65887   }
   65888   if( rc ){
   65889     int iDb = db->nDb - 1;
   65890     assert( iDb>=2 );
   65891     if( db->aDb[iDb].pBt ){
   65892       sqlite3BtreeClose(db->aDb[iDb].pBt);
   65893       db->aDb[iDb].pBt = 0;
   65894       db->aDb[iDb].pSchema = 0;
   65895     }
   65896     sqlite3ResetInternalSchema(db, 0);
   65897     db->nDb = iDb;
   65898     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   65899       db->mallocFailed = 1;
   65900       sqlite3DbFree(db, zErrDyn);
   65901       zErrDyn = sqlite3MPrintf(db, "out of memory");
   65902     }else if( zErrDyn==0 ){
   65903       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
   65904     }
   65905     goto attach_error;
   65906   }
   65907 
   65908   return;
   65909 
   65910 attach_error:
   65911   /* Return an error if we get here */
   65912   if( zErrDyn ){
   65913     sqlite3_result_error(context, zErrDyn, -1);
   65914     sqlite3DbFree(db, zErrDyn);
   65915   }
   65916   if( rc ) sqlite3_result_error_code(context, rc);
   65917 }
   65918 
   65919 /*
   65920 ** An SQL user-function registered to do the work of an DETACH statement. The
   65921 ** three arguments to the function come directly from a detach statement:
   65922 **
   65923 **     DETACH DATABASE x
   65924 **
   65925 **     SELECT sqlite_detach(x)
   65926 */
   65927 static void detachFunc(
   65928   sqlite3_context *context,
   65929   int NotUsed,
   65930   sqlite3_value **argv
   65931 ){
   65932   const char *zName = (const char *)sqlite3_value_text(argv[0]);
   65933   sqlite3 *db = sqlite3_context_db_handle(context);
   65934   int i;
   65935   Db *pDb = 0;
   65936   char zErr[128];
   65937 
   65938   UNUSED_PARAMETER(NotUsed);
   65939 
   65940   if( zName==0 ) zName = "";
   65941   for(i=0; i<db->nDb; i++){
   65942     pDb = &db->aDb[i];
   65943     if( pDb->pBt==0 ) continue;
   65944     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
   65945   }
   65946 
   65947   if( i>=db->nDb ){
   65948     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
   65949     goto detach_error;
   65950   }
   65951   if( i<2 ){
   65952     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
   65953     goto detach_error;
   65954   }
   65955   if( !db->autoCommit ){
   65956     sqlite3_snprintf(sizeof(zErr), zErr,
   65957                      "cannot DETACH database within transaction");
   65958     goto detach_error;
   65959   }
   65960   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
   65961     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
   65962     goto detach_error;
   65963   }
   65964 
   65965   sqlite3BtreeClose(pDb->pBt);
   65966   pDb->pBt = 0;
   65967   pDb->pSchema = 0;
   65968   sqlite3ResetInternalSchema(db, 0);
   65969   return;
   65970 
   65971 detach_error:
   65972   sqlite3_result_error(context, zErr, -1);
   65973 }
   65974 
   65975 /*
   65976 ** This procedure generates VDBE code for a single invocation of either the
   65977 ** sqlite_detach() or sqlite_attach() SQL user functions.
   65978 */
   65979 static void codeAttach(
   65980   Parse *pParse,       /* The parser context */
   65981   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
   65982   FuncDef *pFunc,      /* FuncDef wrapper for detachFunc() or attachFunc() */
   65983   Expr *pAuthArg,      /* Expression to pass to authorization callback */
   65984   Expr *pFilename,     /* Name of database file */
   65985   Expr *pDbname,       /* Name of the database to use internally */
   65986   Expr *pKey           /* Database key for encryption extension */
   65987 ){
   65988   int rc;
   65989   NameContext sName;
   65990   Vdbe *v;
   65991   sqlite3* db = pParse->db;
   65992   int regArgs;
   65993 
   65994   memset(&sName, 0, sizeof(NameContext));
   65995   sName.pParse = pParse;
   65996 
   65997   if(
   65998       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
   65999       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
   66000       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
   66001   ){
   66002     pParse->nErr++;
   66003     goto attach_end;
   66004   }
   66005 
   66006 #ifndef SQLITE_OMIT_AUTHORIZATION
   66007   if( pAuthArg ){
   66008     char *zAuthArg = pAuthArg->u.zToken;
   66009     if( NEVER(zAuthArg==0) ){
   66010       goto attach_end;
   66011     }
   66012     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
   66013     if(rc!=SQLITE_OK ){
   66014       goto attach_end;
   66015     }
   66016   }
   66017 #endif /* SQLITE_OMIT_AUTHORIZATION */
   66018 
   66019 
   66020   v = sqlite3GetVdbe(pParse);
   66021   regArgs = sqlite3GetTempRange(pParse, 4);
   66022   sqlite3ExprCode(pParse, pFilename, regArgs);
   66023   sqlite3ExprCode(pParse, pDbname, regArgs+1);
   66024   sqlite3ExprCode(pParse, pKey, regArgs+2);
   66025 
   66026   assert( v || db->mallocFailed );
   66027   if( v ){
   66028     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
   66029     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
   66030     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
   66031     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
   66032 
   66033     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
   66034     ** statement only). For DETACH, set it to false (expire all existing
   66035     ** statements).
   66036     */
   66037     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
   66038   }
   66039 
   66040 attach_end:
   66041   sqlite3ExprDelete(db, pFilename);
   66042   sqlite3ExprDelete(db, pDbname);
   66043   sqlite3ExprDelete(db, pKey);
   66044 }
   66045 
   66046 /*
   66047 ** Called by the parser to compile a DETACH statement.
   66048 **
   66049 **     DETACH pDbname
   66050 */
   66051 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
   66052   static FuncDef detach_func = {
   66053     1,                /* nArg */
   66054     SQLITE_UTF8,      /* iPrefEnc */
   66055     0,                /* flags */
   66056     0,                /* pUserData */
   66057     0,                /* pNext */
   66058     detachFunc,       /* xFunc */
   66059     0,                /* xStep */
   66060     0,                /* xFinalize */
   66061     "sqlite_detach",  /* zName */
   66062     0                 /* pHash */
   66063   };
   66064   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
   66065 }
   66066 
   66067 /*
   66068 ** Called by the parser to compile an ATTACH statement.
   66069 **
   66070 **     ATTACH p AS pDbname KEY pKey
   66071 */
   66072 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
   66073   static FuncDef attach_func = {
   66074     3,                /* nArg */
   66075     SQLITE_UTF8,      /* iPrefEnc */
   66076     0,                /* flags */
   66077     0,                /* pUserData */
   66078     0,                /* pNext */
   66079     attachFunc,       /* xFunc */
   66080     0,                /* xStep */
   66081     0,                /* xFinalize */
   66082     "sqlite_attach",  /* zName */
   66083     0                 /* pHash */
   66084   };
   66085   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
   66086 }
   66087 #endif /* SQLITE_OMIT_ATTACH */
   66088 
   66089 /*
   66090 ** Initialize a DbFixer structure.  This routine must be called prior
   66091 ** to passing the structure to one of the sqliteFixAAAA() routines below.
   66092 **
   66093 ** The return value indicates whether or not fixation is required.  TRUE
   66094 ** means we do need to fix the database references, FALSE means we do not.
   66095 */
   66096 SQLITE_PRIVATE int sqlite3FixInit(
   66097   DbFixer *pFix,      /* The fixer to be initialized */
   66098   Parse *pParse,      /* Error messages will be written here */
   66099   int iDb,            /* This is the database that must be used */
   66100   const char *zType,  /* "view", "trigger", or "index" */
   66101   const Token *pName  /* Name of the view, trigger, or index */
   66102 ){
   66103   sqlite3 *db;
   66104 
   66105   if( NEVER(iDb<0) || iDb==1 ) return 0;
   66106   db = pParse->db;
   66107   assert( db->nDb>iDb );
   66108   pFix->pParse = pParse;
   66109   pFix->zDb = db->aDb[iDb].zName;
   66110   pFix->zType = zType;
   66111   pFix->pName = pName;
   66112   return 1;
   66113 }
   66114 
   66115 /*
   66116 ** The following set of routines walk through the parse tree and assign
   66117 ** a specific database to all table references where the database name
   66118 ** was left unspecified in the original SQL statement.  The pFix structure
   66119 ** must have been initialized by a prior call to sqlite3FixInit().
   66120 **
   66121 ** These routines are used to make sure that an index, trigger, or
   66122 ** view in one database does not refer to objects in a different database.
   66123 ** (Exception: indices, triggers, and views in the TEMP database are
   66124 ** allowed to refer to anything.)  If a reference is explicitly made
   66125 ** to an object in a different database, an error message is added to
   66126 ** pParse->zErrMsg and these routines return non-zero.  If everything
   66127 ** checks out, these routines return 0.
   66128 */
   66129 SQLITE_PRIVATE int sqlite3FixSrcList(
   66130   DbFixer *pFix,       /* Context of the fixation */
   66131   SrcList *pList       /* The Source list to check and modify */
   66132 ){
   66133   int i;
   66134   const char *zDb;
   66135   struct SrcList_item *pItem;
   66136 
   66137   if( NEVER(pList==0) ) return 0;
   66138   zDb = pFix->zDb;
   66139   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
   66140     if( pItem->zDatabase==0 ){
   66141       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
   66142     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
   66143       sqlite3ErrorMsg(pFix->pParse,
   66144          "%s %T cannot reference objects in database %s",
   66145          pFix->zType, pFix->pName, pItem->zDatabase);
   66146       return 1;
   66147     }
   66148 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
   66149     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
   66150     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
   66151 #endif
   66152   }
   66153   return 0;
   66154 }
   66155 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
   66156 SQLITE_PRIVATE int sqlite3FixSelect(
   66157   DbFixer *pFix,       /* Context of the fixation */
   66158   Select *pSelect      /* The SELECT statement to be fixed to one database */
   66159 ){
   66160   while( pSelect ){
   66161     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
   66162       return 1;
   66163     }
   66164     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
   66165       return 1;
   66166     }
   66167     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
   66168       return 1;
   66169     }
   66170     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
   66171       return 1;
   66172     }
   66173     pSelect = pSelect->pPrior;
   66174   }
   66175   return 0;
   66176 }
   66177 SQLITE_PRIVATE int sqlite3FixExpr(
   66178   DbFixer *pFix,     /* Context of the fixation */
   66179   Expr *pExpr        /* The expression to be fixed to one database */
   66180 ){
   66181   while( pExpr ){
   66182     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
   66183     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   66184       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
   66185     }else{
   66186       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
   66187     }
   66188     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
   66189       return 1;
   66190     }
   66191     pExpr = pExpr->pLeft;
   66192   }
   66193   return 0;
   66194 }
   66195 SQLITE_PRIVATE int sqlite3FixExprList(
   66196   DbFixer *pFix,     /* Context of the fixation */
   66197   ExprList *pList    /* The expression to be fixed to one database */
   66198 ){
   66199   int i;
   66200   struct ExprList_item *pItem;
   66201   if( pList==0 ) return 0;
   66202   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
   66203     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
   66204       return 1;
   66205     }
   66206   }
   66207   return 0;
   66208 }
   66209 #endif
   66210 
   66211 #ifndef SQLITE_OMIT_TRIGGER
   66212 SQLITE_PRIVATE int sqlite3FixTriggerStep(
   66213   DbFixer *pFix,     /* Context of the fixation */
   66214   TriggerStep *pStep /* The trigger step be fixed to one database */
   66215 ){
   66216   while( pStep ){
   66217     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
   66218       return 1;
   66219     }
   66220     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
   66221       return 1;
   66222     }
   66223     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
   66224       return 1;
   66225     }
   66226     pStep = pStep->pNext;
   66227   }
   66228   return 0;
   66229 }
   66230 #endif
   66231 
   66232 /************** End of attach.c **********************************************/
   66233 /************** Begin file auth.c ********************************************/
   66234 /*
   66235 ** 2003 January 11
   66236 **
   66237 ** The author disclaims copyright to this source code.  In place of
   66238 ** a legal notice, here is a blessing:
   66239 **
   66240 **    May you do good and not evil.
   66241 **    May you find forgiveness for yourself and forgive others.
   66242 **    May you share freely, never taking more than you give.
   66243 **
   66244 *************************************************************************
   66245 ** This file contains code used to implement the sqlite3_set_authorizer()
   66246 ** API.  This facility is an optional feature of the library.  Embedded
   66247 ** systems that do not need this facility may omit it by recompiling
   66248 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
   66249 */
   66250 
   66251 /*
   66252 ** All of the code in this file may be omitted by defining a single
   66253 ** macro.
   66254 */
   66255 #ifndef SQLITE_OMIT_AUTHORIZATION
   66256 
   66257 /*
   66258 ** Set or clear the access authorization function.
   66259 **
   66260 ** The access authorization function is be called during the compilation
   66261 ** phase to verify that the user has read and/or write access permission on
   66262 ** various fields of the database.  The first argument to the auth function
   66263 ** is a copy of the 3rd argument to this routine.  The second argument
   66264 ** to the auth function is one of these constants:
   66265 **
   66266 **       SQLITE_CREATE_INDEX
   66267 **       SQLITE_CREATE_TABLE
   66268 **       SQLITE_CREATE_TEMP_INDEX
   66269 **       SQLITE_CREATE_TEMP_TABLE
   66270 **       SQLITE_CREATE_TEMP_TRIGGER
   66271 **       SQLITE_CREATE_TEMP_VIEW
   66272 **       SQLITE_CREATE_TRIGGER
   66273 **       SQLITE_CREATE_VIEW
   66274 **       SQLITE_DELETE
   66275 **       SQLITE_DROP_INDEX
   66276 **       SQLITE_DROP_TABLE
   66277 **       SQLITE_DROP_TEMP_INDEX
   66278 **       SQLITE_DROP_TEMP_TABLE
   66279 **       SQLITE_DROP_TEMP_TRIGGER
   66280 **       SQLITE_DROP_TEMP_VIEW
   66281 **       SQLITE_DROP_TRIGGER
   66282 **       SQLITE_DROP_VIEW
   66283 **       SQLITE_INSERT
   66284 **       SQLITE_PRAGMA
   66285 **       SQLITE_READ
   66286 **       SQLITE_SELECT
   66287 **       SQLITE_TRANSACTION
   66288 **       SQLITE_UPDATE
   66289 **
   66290 ** The third and fourth arguments to the auth function are the name of
   66291 ** the table and the column that are being accessed.  The auth function
   66292 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
   66293 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
   66294 ** means that the SQL statement will never-run - the sqlite3_exec() call
   66295 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
   66296 ** should run but attempts to read the specified column will return NULL
   66297 ** and attempts to write the column will be ignored.
   66298 **
   66299 ** Setting the auth function to NULL disables this hook.  The default
   66300 ** setting of the auth function is NULL.
   66301 */
   66302 SQLITE_API int sqlite3_set_authorizer(
   66303   sqlite3 *db,
   66304   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
   66305   void *pArg
   66306 ){
   66307   sqlite3_mutex_enter(db->mutex);
   66308   db->xAuth = xAuth;
   66309   db->pAuthArg = pArg;
   66310   sqlite3ExpirePreparedStatements(db);
   66311   sqlite3_mutex_leave(db->mutex);
   66312   return SQLITE_OK;
   66313 }
   66314 
   66315 /*
   66316 ** Write an error message into pParse->zErrMsg that explains that the
   66317 ** user-supplied authorization function returned an illegal value.
   66318 */
   66319 static void sqliteAuthBadReturnCode(Parse *pParse){
   66320   sqlite3ErrorMsg(pParse, "authorizer malfunction");
   66321   pParse->rc = SQLITE_ERROR;
   66322 }
   66323 
   66324 /*
   66325 ** Invoke the authorization callback for permission to read column zCol from
   66326 ** table zTab in database zDb. This function assumes that an authorization
   66327 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
   66328 **
   66329 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
   66330 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
   66331 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
   66332 */
   66333 SQLITE_PRIVATE int sqlite3AuthReadCol(
   66334   Parse *pParse,                  /* The parser context */
   66335   const char *zTab,               /* Table name */
   66336   const char *zCol,               /* Column name */
   66337   int iDb                         /* Index of containing database. */
   66338 ){
   66339   sqlite3 *db = pParse->db;       /* Database handle */
   66340   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
   66341   int rc;                         /* Auth callback return code */
   66342 
   66343   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
   66344   if( rc==SQLITE_DENY ){
   66345     if( db->nDb>2 || iDb!=0 ){
   66346       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
   66347     }else{
   66348       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
   66349     }
   66350     pParse->rc = SQLITE_AUTH;
   66351   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
   66352     sqliteAuthBadReturnCode(pParse);
   66353   }
   66354   return rc;
   66355 }
   66356 
   66357 /*
   66358 ** The pExpr should be a TK_COLUMN expression.  The table referred to
   66359 ** is in pTabList or else it is the NEW or OLD table of a trigger.
   66360 ** Check to see if it is OK to read this particular column.
   66361 **
   66362 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
   66363 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
   66364 ** then generate an error.
   66365 */
   66366 SQLITE_PRIVATE void sqlite3AuthRead(
   66367   Parse *pParse,        /* The parser context */
   66368   Expr *pExpr,          /* The expression to check authorization on */
   66369   Schema *pSchema,      /* The schema of the expression */
   66370   SrcList *pTabList     /* All table that pExpr might refer to */
   66371 ){
   66372   sqlite3 *db = pParse->db;
   66373   Table *pTab = 0;      /* The table being read */
   66374   const char *zCol;     /* Name of the column of the table */
   66375   int iSrc;             /* Index in pTabList->a[] of table being read */
   66376   int iDb;              /* The index of the database the expression refers to */
   66377   int iCol;             /* Index of column in table */
   66378 
   66379   if( db->xAuth==0 ) return;
   66380   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
   66381   if( iDb<0 ){
   66382     /* An attempt to read a column out of a subquery or other
   66383     ** temporary table. */
   66384     return;
   66385   }
   66386 
   66387   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
   66388   if( pExpr->op==TK_TRIGGER ){
   66389     pTab = pParse->pTriggerTab;
   66390   }else{
   66391     assert( pTabList );
   66392     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
   66393       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
   66394         pTab = pTabList->a[iSrc].pTab;
   66395         break;
   66396       }
   66397     }
   66398   }
   66399   iCol = pExpr->iColumn;
   66400   if( NEVER(pTab==0) ) return;
   66401 
   66402   if( iCol>=0 ){
   66403     assert( iCol<pTab->nCol );
   66404     zCol = pTab->aCol[iCol].zName;
   66405   }else if( pTab->iPKey>=0 ){
   66406     assert( pTab->iPKey<pTab->nCol );
   66407     zCol = pTab->aCol[pTab->iPKey].zName;
   66408   }else{
   66409     zCol = "ROWID";
   66410   }
   66411   assert( iDb>=0 && iDb<db->nDb );
   66412   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
   66413     pExpr->op = TK_NULL;
   66414   }
   66415 }
   66416 
   66417 /*
   66418 ** Do an authorization check using the code and arguments given.  Return
   66419 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
   66420 ** is returned, then the error count and error message in pParse are
   66421 ** modified appropriately.
   66422 */
   66423 SQLITE_PRIVATE int sqlite3AuthCheck(
   66424   Parse *pParse,
   66425   int code,
   66426   const char *zArg1,
   66427   const char *zArg2,
   66428   const char *zArg3
   66429 ){
   66430   sqlite3 *db = pParse->db;
   66431   int rc;
   66432 
   66433   /* Don't do any authorization checks if the database is initialising
   66434   ** or if the parser is being invoked from within sqlite3_declare_vtab.
   66435   */
   66436   if( db->init.busy || IN_DECLARE_VTAB ){
   66437     return SQLITE_OK;
   66438   }
   66439 
   66440   if( db->xAuth==0 ){
   66441     return SQLITE_OK;
   66442   }
   66443   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
   66444   if( rc==SQLITE_DENY ){
   66445     sqlite3ErrorMsg(pParse, "not authorized");
   66446     pParse->rc = SQLITE_AUTH;
   66447   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
   66448     rc = SQLITE_DENY;
   66449     sqliteAuthBadReturnCode(pParse);
   66450   }
   66451   return rc;
   66452 }
   66453 
   66454 /*
   66455 ** Push an authorization context.  After this routine is called, the
   66456 ** zArg3 argument to authorization callbacks will be zContext until
   66457 ** popped.  Or if pParse==0, this routine is a no-op.
   66458 */
   66459 SQLITE_PRIVATE void sqlite3AuthContextPush(
   66460   Parse *pParse,
   66461   AuthContext *pContext,
   66462   const char *zContext
   66463 ){
   66464   assert( pParse );
   66465   pContext->pParse = pParse;
   66466   pContext->zAuthContext = pParse->zAuthContext;
   66467   pParse->zAuthContext = zContext;
   66468 }
   66469 
   66470 /*
   66471 ** Pop an authorization context that was previously pushed
   66472 ** by sqlite3AuthContextPush
   66473 */
   66474 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
   66475   if( pContext->pParse ){
   66476     pContext->pParse->zAuthContext = pContext->zAuthContext;
   66477     pContext->pParse = 0;
   66478   }
   66479 }
   66480 
   66481 #endif /* SQLITE_OMIT_AUTHORIZATION */
   66482 
   66483 /************** End of auth.c ************************************************/
   66484 /************** Begin file build.c *******************************************/
   66485 /*
   66486 ** 2001 September 15
   66487 **
   66488 ** The author disclaims copyright to this source code.  In place of
   66489 ** a legal notice, here is a blessing:
   66490 **
   66491 **    May you do good and not evil.
   66492 **    May you find forgiveness for yourself and forgive others.
   66493 **    May you share freely, never taking more than you give.
   66494 **
   66495 *************************************************************************
   66496 ** This file contains C code routines that are called by the SQLite parser
   66497 ** when syntax rules are reduced.  The routines in this file handle the
   66498 ** following kinds of SQL syntax:
   66499 **
   66500 **     CREATE TABLE
   66501 **     DROP TABLE
   66502 **     CREATE INDEX
   66503 **     DROP INDEX
   66504 **     creating ID lists
   66505 **     BEGIN TRANSACTION
   66506 **     COMMIT
   66507 **     ROLLBACK
   66508 */
   66509 
   66510 /*
   66511 ** This routine is called when a new SQL statement is beginning to
   66512 ** be parsed.  Initialize the pParse structure as needed.
   66513 */
   66514 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
   66515   pParse->explain = (u8)explainFlag;
   66516   pParse->nVar = 0;
   66517 }
   66518 
   66519 #ifndef SQLITE_OMIT_SHARED_CACHE
   66520 /*
   66521 ** The TableLock structure is only used by the sqlite3TableLock() and
   66522 ** codeTableLocks() functions.
   66523 */
   66524 struct TableLock {
   66525   int iDb;             /* The database containing the table to be locked */
   66526   int iTab;            /* The root page of the table to be locked */
   66527   u8 isWriteLock;      /* True for write lock.  False for a read lock */
   66528   const char *zName;   /* Name of the table */
   66529 };
   66530 
   66531 /*
   66532 ** Record the fact that we want to lock a table at run-time.
   66533 **
   66534 ** The table to be locked has root page iTab and is found in database iDb.
   66535 ** A read or a write lock can be taken depending on isWritelock.
   66536 **
   66537 ** This routine just records the fact that the lock is desired.  The
   66538 ** code to make the lock occur is generated by a later call to
   66539 ** codeTableLocks() which occurs during sqlite3FinishCoding().
   66540 */
   66541 SQLITE_PRIVATE void sqlite3TableLock(
   66542   Parse *pParse,     /* Parsing context */
   66543   int iDb,           /* Index of the database containing the table to lock */
   66544   int iTab,          /* Root page number of the table to be locked */
   66545   u8 isWriteLock,    /* True for a write lock */
   66546   const char *zName  /* Name of the table to be locked */
   66547 ){
   66548   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   66549   int i;
   66550   int nBytes;
   66551   TableLock *p;
   66552   assert( iDb>=0 );
   66553 
   66554   for(i=0; i<pToplevel->nTableLock; i++){
   66555     p = &pToplevel->aTableLock[i];
   66556     if( p->iDb==iDb && p->iTab==iTab ){
   66557       p->isWriteLock = (p->isWriteLock || isWriteLock);
   66558       return;
   66559     }
   66560   }
   66561 
   66562   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
   66563   pToplevel->aTableLock =
   66564       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
   66565   if( pToplevel->aTableLock ){
   66566     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
   66567     p->iDb = iDb;
   66568     p->iTab = iTab;
   66569     p->isWriteLock = isWriteLock;
   66570     p->zName = zName;
   66571   }else{
   66572     pToplevel->nTableLock = 0;
   66573     pToplevel->db->mallocFailed = 1;
   66574   }
   66575 }
   66576 
   66577 /*
   66578 ** Code an OP_TableLock instruction for each table locked by the
   66579 ** statement (configured by calls to sqlite3TableLock()).
   66580 */
   66581 static void codeTableLocks(Parse *pParse){
   66582   int i;
   66583   Vdbe *pVdbe;
   66584 
   66585   pVdbe = sqlite3GetVdbe(pParse);
   66586   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
   66587 
   66588   for(i=0; i<pParse->nTableLock; i++){
   66589     TableLock *p = &pParse->aTableLock[i];
   66590     int p1 = p->iDb;
   66591     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
   66592                       p->zName, P4_STATIC);
   66593   }
   66594 }
   66595 #else
   66596   #define codeTableLocks(x)
   66597 #endif
   66598 
   66599 /*
   66600 ** This routine is called after a single SQL statement has been
   66601 ** parsed and a VDBE program to execute that statement has been
   66602 ** prepared.  This routine puts the finishing touches on the
   66603 ** VDBE program and resets the pParse structure for the next
   66604 ** parse.
   66605 **
   66606 ** Note that if an error occurred, it might be the case that
   66607 ** no VDBE code was generated.
   66608 */
   66609 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
   66610   sqlite3 *db;
   66611   Vdbe *v;
   66612 
   66613   db = pParse->db;
   66614   if( db->mallocFailed ) return;
   66615   if( pParse->nested ) return;
   66616   if( pParse->nErr ) return;
   66617 
   66618   /* Begin by generating some termination code at the end of the
   66619   ** vdbe program
   66620   */
   66621   v = sqlite3GetVdbe(pParse);
   66622   assert( !pParse->isMultiWrite
   66623        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
   66624   if( v ){
   66625     sqlite3VdbeAddOp0(v, OP_Halt);
   66626 
   66627     /* The cookie mask contains one bit for each database file open.
   66628     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
   66629     ** set for each database that is used.  Generate code to start a
   66630     ** transaction on each used database and to verify the schema cookie
   66631     ** on each used database.
   66632     */
   66633     if( pParse->cookieGoto>0 ){
   66634       u32 mask;
   66635       int iDb;
   66636       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
   66637       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
   66638         if( (mask & pParse->cookieMask)==0 ) continue;
   66639         sqlite3VdbeUsesBtree(v, iDb);
   66640         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
   66641         if( db->init.busy==0 ){
   66642           sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
   66643         }
   66644       }
   66645 #ifndef SQLITE_OMIT_VIRTUALTABLE
   66646       {
   66647         int i;
   66648         for(i=0; i<pParse->nVtabLock; i++){
   66649           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
   66650           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
   66651         }
   66652         pParse->nVtabLock = 0;
   66653       }
   66654 #endif
   66655 
   66656       /* Once all the cookies have been verified and transactions opened,
   66657       ** obtain the required table-locks. This is a no-op unless the
   66658       ** shared-cache feature is enabled.
   66659       */
   66660       codeTableLocks(pParse);
   66661 
   66662       /* Initialize any AUTOINCREMENT data structures required.
   66663       */
   66664       sqlite3AutoincrementBegin(pParse);
   66665 
   66666       /* Finally, jump back to the beginning of the executable code. */
   66667       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
   66668     }
   66669   }
   66670 
   66671 
   66672   /* Get the VDBE program ready for execution
   66673   */
   66674   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
   66675 #ifdef SQLITE_DEBUG
   66676     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
   66677     sqlite3VdbeTrace(v, trace);
   66678 #endif
   66679     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
   66680     /* A minimum of one cursor is required if autoincrement is used
   66681     *  See ticket [a696379c1f08866] */
   66682     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
   66683     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
   66684                          pParse->nTab, pParse->nMaxArg, pParse->explain,
   66685                          pParse->isMultiWrite && pParse->mayAbort);
   66686     pParse->rc = SQLITE_DONE;
   66687     pParse->colNamesSet = 0;
   66688   }else if( pParse->rc==SQLITE_OK ){
   66689     pParse->rc = SQLITE_ERROR;
   66690   }
   66691   pParse->nTab = 0;
   66692   pParse->nMem = 0;
   66693   pParse->nSet = 0;
   66694   pParse->nVar = 0;
   66695   pParse->cookieMask = 0;
   66696   pParse->cookieGoto = 0;
   66697 }
   66698 
   66699 /*
   66700 ** Run the parser and code generator recursively in order to generate
   66701 ** code for the SQL statement given onto the end of the pParse context
   66702 ** currently under construction.  When the parser is run recursively
   66703 ** this way, the final OP_Halt is not appended and other initialization
   66704 ** and finalization steps are omitted because those are handling by the
   66705 ** outermost parser.
   66706 **
   66707 ** Not everything is nestable.  This facility is designed to permit
   66708 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
   66709 ** care if you decide to try to use this routine for some other purposes.
   66710 */
   66711 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
   66712   va_list ap;
   66713   char *zSql;
   66714   char *zErrMsg = 0;
   66715   sqlite3 *db = pParse->db;
   66716 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
   66717   char saveBuf[SAVE_SZ];
   66718 
   66719   if( pParse->nErr ) return;
   66720   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
   66721   va_start(ap, zFormat);
   66722   zSql = sqlite3VMPrintf(db, zFormat, ap);
   66723   va_end(ap);
   66724   if( zSql==0 ){
   66725     return;   /* A malloc must have failed */
   66726   }
   66727   pParse->nested++;
   66728   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
   66729   memset(&pParse->nVar, 0, SAVE_SZ);
   66730   sqlite3RunParser(pParse, zSql, &zErrMsg);
   66731   sqlite3DbFree(db, zErrMsg);
   66732   sqlite3DbFree(db, zSql);
   66733   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
   66734   pParse->nested--;
   66735 }
   66736 
   66737 /*
   66738 ** Locate the in-memory structure that describes a particular database
   66739 ** table given the name of that table and (optionally) the name of the
   66740 ** database containing the table.  Return NULL if not found.
   66741 **
   66742 ** If zDatabase is 0, all databases are searched for the table and the
   66743 ** first matching table is returned.  (No checking for duplicate table
   66744 ** names is done.)  The search order is TEMP first, then MAIN, then any
   66745 ** auxiliary databases added using the ATTACH command.
   66746 **
   66747 ** See also sqlite3LocateTable().
   66748 */
   66749 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
   66750   Table *p = 0;
   66751   int i;
   66752   int nName;
   66753   assert( zName!=0 );
   66754   nName = sqlite3Strlen30(zName);
   66755   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   66756     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
   66757     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
   66758     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
   66759     if( p ) break;
   66760   }
   66761   return p;
   66762 }
   66763 
   66764 /*
   66765 ** Locate the in-memory structure that describes a particular database
   66766 ** table given the name of that table and (optionally) the name of the
   66767 ** database containing the table.  Return NULL if not found.  Also leave an
   66768 ** error message in pParse->zErrMsg.
   66769 **
   66770 ** The difference between this routine and sqlite3FindTable() is that this
   66771 ** routine leaves an error message in pParse->zErrMsg where
   66772 ** sqlite3FindTable() does not.
   66773 */
   66774 SQLITE_PRIVATE Table *sqlite3LocateTable(
   66775   Parse *pParse,         /* context in which to report errors */
   66776   int isView,            /* True if looking for a VIEW rather than a TABLE */
   66777   const char *zName,     /* Name of the table we are looking for */
   66778   const char *zDbase     /* Name of the database.  Might be NULL */
   66779 ){
   66780   Table *p;
   66781 
   66782   /* Read the database schema. If an error occurs, leave an error message
   66783   ** and code in pParse and return NULL. */
   66784   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   66785     return 0;
   66786   }
   66787 
   66788   p = sqlite3FindTable(pParse->db, zName, zDbase);
   66789   if( p==0 ){
   66790     const char *zMsg = isView ? "no such view" : "no such table";
   66791     if( zDbase ){
   66792       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
   66793     }else{
   66794       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
   66795     }
   66796     pParse->checkSchema = 1;
   66797   }
   66798   return p;
   66799 }
   66800 
   66801 /*
   66802 ** Locate the in-memory structure that describes
   66803 ** a particular index given the name of that index
   66804 ** and the name of the database that contains the index.
   66805 ** Return NULL if not found.
   66806 **
   66807 ** If zDatabase is 0, all databases are searched for the
   66808 ** table and the first matching index is returned.  (No checking
   66809 ** for duplicate index names is done.)  The search order is
   66810 ** TEMP first, then MAIN, then any auxiliary databases added
   66811 ** using the ATTACH command.
   66812 */
   66813 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
   66814   Index *p = 0;
   66815   int i;
   66816   int nName = sqlite3Strlen30(zName);
   66817   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   66818     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   66819     Schema *pSchema = db->aDb[j].pSchema;
   66820     assert( pSchema );
   66821     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
   66822     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
   66823     if( p ) break;
   66824   }
   66825   return p;
   66826 }
   66827 
   66828 /*
   66829 ** Reclaim the memory used by an index
   66830 */
   66831 static void freeIndex(Index *p){
   66832   sqlite3 *db = p->pTable->dbMem;
   66833 #ifndef SQLITE_OMIT_ANALYZE
   66834   sqlite3DeleteIndexSamples(p);
   66835 #endif
   66836   sqlite3DbFree(db, p->zColAff);
   66837   sqlite3DbFree(db, p);
   66838 }
   66839 
   66840 /*
   66841 ** Remove the given index from the index hash table, and free
   66842 ** its memory structures.
   66843 **
   66844 ** The index is removed from the database hash tables but
   66845 ** it is not unlinked from the Table that it indexes.
   66846 ** Unlinking from the Table must be done by the calling function.
   66847 */
   66848 static void sqlite3DeleteIndex(Index *p){
   66849   Index *pOld;
   66850   const char *zName = p->zName;
   66851 
   66852   pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
   66853                            sqlite3Strlen30(zName), 0);
   66854   assert( pOld==0 || pOld==p );
   66855   freeIndex(p);
   66856 }
   66857 
   66858 /*
   66859 ** For the index called zIdxName which is found in the database iDb,
   66860 ** unlike that index from its Table then remove the index from
   66861 ** the index hash table and free all memory structures associated
   66862 ** with the index.
   66863 */
   66864 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
   66865   Index *pIndex;
   66866   int len;
   66867   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
   66868 
   66869   len = sqlite3Strlen30(zIdxName);
   66870   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
   66871   if( pIndex ){
   66872     if( pIndex->pTable->pIndex==pIndex ){
   66873       pIndex->pTable->pIndex = pIndex->pNext;
   66874     }else{
   66875       Index *p;
   66876       /* Justification of ALWAYS();  The index must be on the list of
   66877       ** indices. */
   66878       p = pIndex->pTable->pIndex;
   66879       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
   66880       if( ALWAYS(p && p->pNext==pIndex) ){
   66881         p->pNext = pIndex->pNext;
   66882       }
   66883     }
   66884     freeIndex(pIndex);
   66885   }
   66886   db->flags |= SQLITE_InternChanges;
   66887 }
   66888 
   66889 /*
   66890 ** Erase all schema information from the in-memory hash tables of
   66891 ** a single database.  This routine is called to reclaim memory
   66892 ** before the database closes.  It is also called during a rollback
   66893 ** if there were schema changes during the transaction or if a
   66894 ** schema-cookie mismatch occurs.
   66895 **
   66896 ** If iDb==0 then reset the internal schema tables for all database
   66897 ** files.  If iDb>=1 then reset the internal schema for only the
   66898 ** single file indicated.
   66899 */
   66900 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
   66901   int i, j;
   66902   assert( iDb>=0 && iDb<db->nDb );
   66903 
   66904   if( iDb==0 ){
   66905     sqlite3BtreeEnterAll(db);
   66906   }
   66907   for(i=iDb; i<db->nDb; i++){
   66908     Db *pDb = &db->aDb[i];
   66909     if( pDb->pSchema ){
   66910       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
   66911       sqlite3SchemaFree(pDb->pSchema);
   66912     }
   66913     if( iDb>0 ) return;
   66914   }
   66915   assert( iDb==0 );
   66916   db->flags &= ~SQLITE_InternChanges;
   66917   sqlite3VtabUnlockList(db);
   66918   sqlite3BtreeLeaveAll(db);
   66919 
   66920   /* If one or more of the auxiliary database files has been closed,
   66921   ** then remove them from the auxiliary database list.  We take the
   66922   ** opportunity to do this here since we have just deleted all of the
   66923   ** schema hash tables and therefore do not have to make any changes
   66924   ** to any of those tables.
   66925   */
   66926   for(i=j=2; i<db->nDb; i++){
   66927     struct Db *pDb = &db->aDb[i];
   66928     if( pDb->pBt==0 ){
   66929       sqlite3DbFree(db, pDb->zName);
   66930       pDb->zName = 0;
   66931       continue;
   66932     }
   66933     if( j<i ){
   66934       db->aDb[j] = db->aDb[i];
   66935     }
   66936     j++;
   66937   }
   66938   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
   66939   db->nDb = j;
   66940   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
   66941     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
   66942     sqlite3DbFree(db, db->aDb);
   66943     db->aDb = db->aDbStatic;
   66944   }
   66945 }
   66946 
   66947 /*
   66948 ** This routine is called when a commit occurs.
   66949 */
   66950 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
   66951   db->flags &= ~SQLITE_InternChanges;
   66952 }
   66953 
   66954 /*
   66955 ** Clear the column names from a table or view.
   66956 */
   66957 static void sqliteResetColumnNames(Table *pTable){
   66958   int i;
   66959   Column *pCol;
   66960   sqlite3 *db = pTable->dbMem;
   66961   testcase( db==0 );
   66962   assert( pTable!=0 );
   66963   if( (pCol = pTable->aCol)!=0 ){
   66964     for(i=0; i<pTable->nCol; i++, pCol++){
   66965       sqlite3DbFree(db, pCol->zName);
   66966       sqlite3ExprDelete(db, pCol->pDflt);
   66967       sqlite3DbFree(db, pCol->zDflt);
   66968       sqlite3DbFree(db, pCol->zType);
   66969       sqlite3DbFree(db, pCol->zColl);
   66970     }
   66971     sqlite3DbFree(db, pTable->aCol);
   66972   }
   66973   pTable->aCol = 0;
   66974   pTable->nCol = 0;
   66975 }
   66976 
   66977 /*
   66978 ** Remove the memory data structures associated with the given
   66979 ** Table.  No changes are made to disk by this routine.
   66980 **
   66981 ** This routine just deletes the data structure.  It does not unlink
   66982 ** the table data structure from the hash table.  But it does destroy
   66983 ** memory structures of the indices and foreign keys associated with
   66984 ** the table.
   66985 */
   66986 SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
   66987   Index *pIndex, *pNext;
   66988   sqlite3 *db;
   66989 
   66990   if( pTable==0 ) return;
   66991   db = pTable->dbMem;
   66992   testcase( db==0 );
   66993 
   66994   /* Do not delete the table until the reference count reaches zero. */
   66995   pTable->nRef--;
   66996   if( pTable->nRef>0 ){
   66997     return;
   66998   }
   66999   assert( pTable->nRef==0 );
   67000 
   67001   /* Delete all indices associated with this table
   67002   */
   67003   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
   67004     pNext = pIndex->pNext;
   67005     assert( pIndex->pSchema==pTable->pSchema );
   67006     sqlite3DeleteIndex(pIndex);
   67007   }
   67008 
   67009   /* Delete any foreign keys attached to this table. */
   67010   sqlite3FkDelete(pTable);
   67011 
   67012   /* Delete the Table structure itself.
   67013   */
   67014   sqliteResetColumnNames(pTable);
   67015   sqlite3DbFree(db, pTable->zName);
   67016   sqlite3DbFree(db, pTable->zColAff);
   67017   sqlite3SelectDelete(db, pTable->pSelect);
   67018 #ifndef SQLITE_OMIT_CHECK
   67019   sqlite3ExprDelete(db, pTable->pCheck);
   67020 #endif
   67021   sqlite3VtabClear(pTable);
   67022   sqlite3DbFree(db, pTable);
   67023 }
   67024 
   67025 /*
   67026 ** Unlink the given table from the hash tables and the delete the
   67027 ** table structure with all its indices and foreign keys.
   67028 */
   67029 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
   67030   Table *p;
   67031   Db *pDb;
   67032 
   67033   assert( db!=0 );
   67034   assert( iDb>=0 && iDb<db->nDb );
   67035   assert( zTabName );
   67036   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
   67037   pDb = &db->aDb[iDb];
   67038   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
   67039                         sqlite3Strlen30(zTabName),0);
   67040   sqlite3DeleteTable(p);
   67041   db->flags |= SQLITE_InternChanges;
   67042 }
   67043 
   67044 /*
   67045 ** Given a token, return a string that consists of the text of that
   67046 ** token.  Space to hold the returned string
   67047 ** is obtained from sqliteMalloc() and must be freed by the calling
   67048 ** function.
   67049 **
   67050 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
   67051 ** surround the body of the token are removed.
   67052 **
   67053 ** Tokens are often just pointers into the original SQL text and so
   67054 ** are not \000 terminated and are not persistent.  The returned string
   67055 ** is \000 terminated and is persistent.
   67056 */
   67057 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
   67058   char *zName;
   67059   if( pName ){
   67060     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
   67061     sqlite3Dequote(zName);
   67062   }else{
   67063     zName = 0;
   67064   }
   67065   return zName;
   67066 }
   67067 
   67068 /*
   67069 ** Open the sqlite_master table stored in database number iDb for
   67070 ** writing. The table is opened using cursor 0.
   67071 */
   67072 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
   67073   Vdbe *v = sqlite3GetVdbe(p);
   67074   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
   67075   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
   67076   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
   67077   if( p->nTab==0 ){
   67078     p->nTab = 1;
   67079   }
   67080 }
   67081 
   67082 /*
   67083 ** Parameter zName points to a nul-terminated buffer containing the name
   67084 ** of a database ("main", "temp" or the name of an attached db). This
   67085 ** function returns the index of the named database in db->aDb[], or
   67086 ** -1 if the named db cannot be found.
   67087 */
   67088 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
   67089   int i = -1;         /* Database number */
   67090   if( zName ){
   67091     Db *pDb;
   67092     int n = sqlite3Strlen30(zName);
   67093     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
   67094       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
   67095           0==sqlite3StrICmp(pDb->zName, zName) ){
   67096         break;
   67097       }
   67098     }
   67099   }
   67100   return i;
   67101 }
   67102 
   67103 /*
   67104 ** The token *pName contains the name of a database (either "main" or
   67105 ** "temp" or the name of an attached db). This routine returns the
   67106 ** index of the named database in db->aDb[], or -1 if the named db
   67107 ** does not exist.
   67108 */
   67109 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
   67110   int i;                               /* Database number */
   67111   char *zName;                         /* Name we are searching for */
   67112   zName = sqlite3NameFromToken(db, pName);
   67113   i = sqlite3FindDbName(db, zName);
   67114   sqlite3DbFree(db, zName);
   67115   return i;
   67116 }
   67117 
   67118 /* The table or view or trigger name is passed to this routine via tokens
   67119 ** pName1 and pName2. If the table name was fully qualified, for example:
   67120 **
   67121 ** CREATE TABLE xxx.yyy (...);
   67122 **
   67123 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   67124 ** the table name is not fully qualified, i.e.:
   67125 **
   67126 ** CREATE TABLE yyy(...);
   67127 **
   67128 ** Then pName1 is set to "yyy" and pName2 is "".
   67129 **
   67130 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
   67131 ** pName2) that stores the unqualified table name.  The index of the
   67132 ** database "xxx" is returned.
   67133 */
   67134 SQLITE_PRIVATE int sqlite3TwoPartName(
   67135   Parse *pParse,      /* Parsing and code generating context */
   67136   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
   67137   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
   67138   Token **pUnqual     /* Write the unqualified object name here */
   67139 ){
   67140   int iDb;                    /* Database holding the object */
   67141   sqlite3 *db = pParse->db;
   67142 
   67143   if( ALWAYS(pName2!=0) && pName2->n>0 ){
   67144     if( db->init.busy ) {
   67145       sqlite3ErrorMsg(pParse, "corrupt database");
   67146       pParse->nErr++;
   67147       return -1;
   67148     }
   67149     *pUnqual = pName2;
   67150     iDb = sqlite3FindDb(db, pName1);
   67151     if( iDb<0 ){
   67152       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
   67153       pParse->nErr++;
   67154       return -1;
   67155     }
   67156   }else{
   67157     assert( db->init.iDb==0 || db->init.busy );
   67158     iDb = db->init.iDb;
   67159     *pUnqual = pName1;
   67160   }
   67161   return iDb;
   67162 }
   67163 
   67164 /*
   67165 ** This routine is used to check if the UTF-8 string zName is a legal
   67166 ** unqualified name for a new schema object (table, index, view or
   67167 ** trigger). All names are legal except those that begin with the string
   67168 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
   67169 ** is reserved for internal use.
   67170 */
   67171 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
   67172   if( !pParse->db->init.busy && pParse->nested==0
   67173           && (pParse->db->flags & SQLITE_WriteSchema)==0
   67174           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
   67175     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
   67176     return SQLITE_ERROR;
   67177   }
   67178   return SQLITE_OK;
   67179 }
   67180 
   67181 /*
   67182 ** Begin constructing a new table representation in memory.  This is
   67183 ** the first of several action routines that get called in response
   67184 ** to a CREATE TABLE statement.  In particular, this routine is called
   67185 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
   67186 ** flag is true if the table should be stored in the auxiliary database
   67187 ** file instead of in the main database file.  This is normally the case
   67188 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
   67189 ** CREATE and TABLE.
   67190 **
   67191 ** The new table record is initialized and put in pParse->pNewTable.
   67192 ** As more of the CREATE TABLE statement is parsed, additional action
   67193 ** routines will be called to add more information to this record.
   67194 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
   67195 ** is called to complete the construction of the new table record.
   67196 */
   67197 SQLITE_PRIVATE void sqlite3StartTable(
   67198   Parse *pParse,   /* Parser context */
   67199   Token *pName1,   /* First part of the name of the table or view */
   67200   Token *pName2,   /* Second part of the name of the table or view */
   67201   int isTemp,      /* True if this is a TEMP table */
   67202   int isView,      /* True if this is a VIEW */
   67203   int isVirtual,   /* True if this is a VIRTUAL table */
   67204   int noErr        /* Do nothing if table already exists */
   67205 ){
   67206   Table *pTable;
   67207   char *zName = 0; /* The name of the new table */
   67208   sqlite3 *db = pParse->db;
   67209   Vdbe *v;
   67210   int iDb;         /* Database number to create the table in */
   67211   Token *pName;    /* Unqualified name of the table to create */
   67212 
   67213   /* The table or view name to create is passed to this routine via tokens
   67214   ** pName1 and pName2. If the table name was fully qualified, for example:
   67215   **
   67216   ** CREATE TABLE xxx.yyy (...);
   67217   **
   67218   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   67219   ** the table name is not fully qualified, i.e.:
   67220   **
   67221   ** CREATE TABLE yyy(...);
   67222   **
   67223   ** Then pName1 is set to "yyy" and pName2 is "".
   67224   **
   67225   ** The call below sets the pName pointer to point at the token (pName1 or
   67226   ** pName2) that stores the unqualified table name. The variable iDb is
   67227   ** set to the index of the database that the table or view is to be
   67228   ** created in.
   67229   */
   67230   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   67231   if( iDb<0 ) return;
   67232   if( !OMIT_TEMPDB && isTemp && iDb>1 ){
   67233     /* If creating a temp table, the name may not be qualified */
   67234     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
   67235     return;
   67236   }
   67237   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
   67238 
   67239   pParse->sNameToken = *pName;
   67240   zName = sqlite3NameFromToken(db, pName);
   67241   if( zName==0 ) return;
   67242   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   67243     goto begin_table_error;
   67244   }
   67245   if( db->init.iDb==1 ) isTemp = 1;
   67246 #ifndef SQLITE_OMIT_AUTHORIZATION
   67247   assert( (isTemp & 1)==isTemp );
   67248   {
   67249     int code;
   67250     char *zDb = db->aDb[iDb].zName;
   67251     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
   67252       goto begin_table_error;
   67253     }
   67254     if( isView ){
   67255       if( !OMIT_TEMPDB && isTemp ){
   67256         code = SQLITE_CREATE_TEMP_VIEW;
   67257       }else{
   67258         code = SQLITE_CREATE_VIEW;
   67259       }
   67260     }else{
   67261       if( !OMIT_TEMPDB && isTemp ){
   67262         code = SQLITE_CREATE_TEMP_TABLE;
   67263       }else{
   67264         code = SQLITE_CREATE_TABLE;
   67265       }
   67266     }
   67267     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
   67268       goto begin_table_error;
   67269     }
   67270   }
   67271 #endif
   67272 
   67273   /* Make sure the new table name does not collide with an existing
   67274   ** index or table name in the same database.  Issue an error message if
   67275   ** it does. The exception is if the statement being parsed was passed
   67276   ** to an sqlite3_declare_vtab() call. In that case only the column names
   67277   ** and types will be used, so there is no need to test for namespace
   67278   ** collisions.
   67279   */
   67280   if( !IN_DECLARE_VTAB ){
   67281     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   67282       goto begin_table_error;
   67283     }
   67284     pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
   67285     if( pTable ){
   67286       if( !noErr ){
   67287         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
   67288       }
   67289       goto begin_table_error;
   67290     }
   67291     if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
   67292       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
   67293       goto begin_table_error;
   67294     }
   67295   }
   67296 
   67297   pTable = sqlite3DbMallocZero(db, sizeof(Table));
   67298   if( pTable==0 ){
   67299     db->mallocFailed = 1;
   67300     pParse->rc = SQLITE_NOMEM;
   67301     pParse->nErr++;
   67302     goto begin_table_error;
   67303   }
   67304   pTable->zName = zName;
   67305   pTable->iPKey = -1;
   67306   pTable->pSchema = db->aDb[iDb].pSchema;
   67307   pTable->nRef = 1;
   67308   pTable->dbMem = 0;
   67309   assert( pParse->pNewTable==0 );
   67310   pParse->pNewTable = pTable;
   67311 
   67312   /* If this is the magic sqlite_sequence table used by autoincrement,
   67313   ** then record a pointer to this table in the main database structure
   67314   ** so that INSERT can find the table easily.
   67315   */
   67316 #ifndef SQLITE_OMIT_AUTOINCREMENT
   67317   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
   67318     pTable->pSchema->pSeqTab = pTable;
   67319   }
   67320 #endif
   67321 
   67322   /* Begin generating the code that will insert the table record into
   67323   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
   67324   ** and allocate the record number for the table entry now.  Before any
   67325   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
   67326   ** indices to be created and the table record must come before the
   67327   ** indices.  Hence, the record number for the table must be allocated
   67328   ** now.
   67329   */
   67330   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
   67331     int j1;
   67332     int fileFormat;
   67333     int reg1, reg2, reg3;
   67334     sqlite3BeginWriteOperation(pParse, 0, iDb);
   67335 
   67336 #ifndef SQLITE_OMIT_VIRTUALTABLE
   67337     if( isVirtual ){
   67338       sqlite3VdbeAddOp0(v, OP_VBegin);
   67339     }
   67340 #endif
   67341 
   67342     /* If the file format and encoding in the database have not been set,
   67343     ** set them now.
   67344     */
   67345     reg1 = pParse->regRowid = ++pParse->nMem;
   67346     reg2 = pParse->regRoot = ++pParse->nMem;
   67347     reg3 = ++pParse->nMem;
   67348     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
   67349     sqlite3VdbeUsesBtree(v, iDb);
   67350     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
   67351     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
   67352                   1 : SQLITE_MAX_FILE_FORMAT;
   67353     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
   67354     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
   67355     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
   67356     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
   67357     sqlite3VdbeJumpHere(v, j1);
   67358 
   67359     /* This just creates a place-holder record in the sqlite_master table.
   67360     ** The record created does not contain anything yet.  It will be replaced
   67361     ** by the real entry in code generated at sqlite3EndTable().
   67362     **
   67363     ** The rowid for the new entry is left in register pParse->regRowid.
   67364     ** The root page number of the new table is left in reg pParse->regRoot.
   67365     ** The rowid and root page number values are needed by the code that
   67366     ** sqlite3EndTable will generate.
   67367     */
   67368 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   67369     if( isView || isVirtual ){
   67370       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
   67371     }else
   67372 #endif
   67373     {
   67374       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
   67375     }
   67376     sqlite3OpenMasterTable(pParse, iDb);
   67377     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
   67378     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
   67379     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
   67380     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   67381     sqlite3VdbeAddOp0(v, OP_Close);
   67382   }
   67383 
   67384   /* Normal (non-error) return. */
   67385   return;
   67386 
   67387   /* If an error occurs, we jump here */
   67388 begin_table_error:
   67389   sqlite3DbFree(db, zName);
   67390   return;
   67391 }
   67392 
   67393 /*
   67394 ** This macro is used to compare two strings in a case-insensitive manner.
   67395 ** It is slightly faster than calling sqlite3StrICmp() directly, but
   67396 ** produces larger code.
   67397 **
   67398 ** WARNING: This macro is not compatible with the strcmp() family. It
   67399 ** returns true if the two strings are equal, otherwise false.
   67400 */
   67401 #define STRICMP(x, y) (\
   67402 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
   67403 sqlite3UpperToLower[*(unsigned char *)(y)]     \
   67404 && sqlite3StrICmp((x)+1,(y)+1)==0 )
   67405 
   67406 /*
   67407 ** Add a new column to the table currently being constructed.
   67408 **
   67409 ** The parser calls this routine once for each column declaration
   67410 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
   67411 ** first to get things going.  Then this routine is called for each
   67412 ** column.
   67413 */
   67414 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
   67415   Table *p;
   67416   int i;
   67417   char *z;
   67418   Column *pCol;
   67419   sqlite3 *db = pParse->db;
   67420   if( (p = pParse->pNewTable)==0 ) return;
   67421 #if SQLITE_MAX_COLUMN
   67422   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   67423     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
   67424     return;
   67425   }
   67426 #endif
   67427   z = sqlite3NameFromToken(db, pName);
   67428   if( z==0 ) return;
   67429   for(i=0; i<p->nCol; i++){
   67430     if( STRICMP(z, p->aCol[i].zName) ){
   67431       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
   67432       sqlite3DbFree(db, z);
   67433       return;
   67434     }
   67435   }
   67436   if( (p->nCol & 0x7)==0 ){
   67437     Column *aNew;
   67438     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
   67439     if( aNew==0 ){
   67440       sqlite3DbFree(db, z);
   67441       return;
   67442     }
   67443     p->aCol = aNew;
   67444   }
   67445   pCol = &p->aCol[p->nCol];
   67446   memset(pCol, 0, sizeof(p->aCol[0]));
   67447   pCol->zName = z;
   67448 
   67449   /* If there is no type specified, columns have the default affinity
   67450   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
   67451   ** be called next to set pCol->affinity correctly.
   67452   */
   67453   pCol->affinity = SQLITE_AFF_NONE;
   67454   p->nCol++;
   67455 }
   67456 
   67457 /*
   67458 ** This routine is called by the parser while in the middle of
   67459 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
   67460 ** been seen on a column.  This routine sets the notNull flag on
   67461 ** the column currently under construction.
   67462 */
   67463 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
   67464   Table *p;
   67465   p = pParse->pNewTable;
   67466   if( p==0 || NEVER(p->nCol<1) ) return;
   67467   p->aCol[p->nCol-1].notNull = (u8)onError;
   67468 }
   67469 
   67470 /*
   67471 ** Scan the column type name zType (length nType) and return the
   67472 ** associated affinity type.
   67473 **
   67474 ** This routine does a case-independent search of zType for the
   67475 ** substrings in the following table. If one of the substrings is
   67476 ** found, the corresponding affinity is returned. If zType contains
   67477 ** more than one of the substrings, entries toward the top of
   67478 ** the table take priority. For example, if zType is 'BLOBINT',
   67479 ** SQLITE_AFF_INTEGER is returned.
   67480 **
   67481 ** Substring     | Affinity
   67482 ** --------------------------------
   67483 ** 'INT'         | SQLITE_AFF_INTEGER
   67484 ** 'CHAR'        | SQLITE_AFF_TEXT
   67485 ** 'CLOB'        | SQLITE_AFF_TEXT
   67486 ** 'TEXT'        | SQLITE_AFF_TEXT
   67487 ** 'BLOB'        | SQLITE_AFF_NONE
   67488 ** 'REAL'        | SQLITE_AFF_REAL
   67489 ** 'FLOA'        | SQLITE_AFF_REAL
   67490 ** 'DOUB'        | SQLITE_AFF_REAL
   67491 **
   67492 ** If none of the substrings in the above table are found,
   67493 ** SQLITE_AFF_NUMERIC is returned.
   67494 */
   67495 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
   67496   u32 h = 0;
   67497   char aff = SQLITE_AFF_NUMERIC;
   67498 
   67499   if( zIn ) while( zIn[0] ){
   67500     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
   67501     zIn++;
   67502     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
   67503       aff = SQLITE_AFF_TEXT;
   67504     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
   67505       aff = SQLITE_AFF_TEXT;
   67506     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
   67507       aff = SQLITE_AFF_TEXT;
   67508     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
   67509         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
   67510       aff = SQLITE_AFF_NONE;
   67511 #ifndef SQLITE_OMIT_FLOATING_POINT
   67512     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
   67513         && aff==SQLITE_AFF_NUMERIC ){
   67514       aff = SQLITE_AFF_REAL;
   67515     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
   67516         && aff==SQLITE_AFF_NUMERIC ){
   67517       aff = SQLITE_AFF_REAL;
   67518     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
   67519         && aff==SQLITE_AFF_NUMERIC ){
   67520       aff = SQLITE_AFF_REAL;
   67521 #endif
   67522     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
   67523       aff = SQLITE_AFF_INTEGER;
   67524       break;
   67525     }
   67526   }
   67527 
   67528   return aff;
   67529 }
   67530 
   67531 /*
   67532 ** This routine is called by the parser while in the middle of
   67533 ** parsing a CREATE TABLE statement.  The pFirst token is the first
   67534 ** token in the sequence of tokens that describe the type of the
   67535 ** column currently under construction.   pLast is the last token
   67536 ** in the sequence.  Use this information to construct a string
   67537 ** that contains the typename of the column and store that string
   67538 ** in zType.
   67539 */
   67540 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
   67541   Table *p;
   67542   Column *pCol;
   67543 
   67544   p = pParse->pNewTable;
   67545   if( p==0 || NEVER(p->nCol<1) ) return;
   67546   pCol = &p->aCol[p->nCol-1];
   67547   assert( pCol->zType==0 );
   67548   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
   67549   pCol->affinity = sqlite3AffinityType(pCol->zType);
   67550 }
   67551 
   67552 /*
   67553 ** The expression is the default value for the most recently added column
   67554 ** of the table currently under construction.
   67555 **
   67556 ** Default value expressions must be constant.  Raise an exception if this
   67557 ** is not the case.
   67558 **
   67559 ** This routine is called by the parser while in the middle of
   67560 ** parsing a CREATE TABLE statement.
   67561 */
   67562 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
   67563   Table *p;
   67564   Column *pCol;
   67565   sqlite3 *db = pParse->db;
   67566   p = pParse->pNewTable;
   67567   if( p!=0 ){
   67568     pCol = &(p->aCol[p->nCol-1]);
   67569     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
   67570       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
   67571           pCol->zName);
   67572     }else{
   67573       /* A copy of pExpr is used instead of the original, as pExpr contains
   67574       ** tokens that point to volatile memory. The 'span' of the expression
   67575       ** is required by pragma table_info.
   67576       */
   67577       sqlite3ExprDelete(db, pCol->pDflt);
   67578       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
   67579       sqlite3DbFree(db, pCol->zDflt);
   67580       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
   67581                                      (int)(pSpan->zEnd - pSpan->zStart));
   67582     }
   67583   }
   67584   sqlite3ExprDelete(db, pSpan->pExpr);
   67585 }
   67586 
   67587 /*
   67588 ** Designate the PRIMARY KEY for the table.  pList is a list of names
   67589 ** of columns that form the primary key.  If pList is NULL, then the
   67590 ** most recently added column of the table is the primary key.
   67591 **
   67592 ** A table can have at most one primary key.  If the table already has
   67593 ** a primary key (and this is the second primary key) then create an
   67594 ** error.
   67595 **
   67596 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
   67597 ** then we will try to use that column as the rowid.  Set the Table.iPKey
   67598 ** field of the table under construction to be the index of the
   67599 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
   67600 ** no INTEGER PRIMARY KEY.
   67601 **
   67602 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
   67603 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
   67604 */
   67605 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
   67606   Parse *pParse,    /* Parsing context */
   67607   ExprList *pList,  /* List of field names to be indexed */
   67608   int onError,      /* What to do with a uniqueness conflict */
   67609   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
   67610   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
   67611 ){
   67612   Table *pTab = pParse->pNewTable;
   67613   char *zType = 0;
   67614   int iCol = -1, i;
   67615   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
   67616   if( pTab->tabFlags & TF_HasPrimaryKey ){
   67617     sqlite3ErrorMsg(pParse,
   67618       "table \"%s\" has more than one primary key", pTab->zName);
   67619     goto primary_key_exit;
   67620   }
   67621   pTab->tabFlags |= TF_HasPrimaryKey;
   67622   if( pList==0 ){
   67623     iCol = pTab->nCol - 1;
   67624     pTab->aCol[iCol].isPrimKey = 1;
   67625   }else{
   67626     for(i=0; i<pList->nExpr; i++){
   67627       for(iCol=0; iCol<pTab->nCol; iCol++){
   67628         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
   67629           break;
   67630         }
   67631       }
   67632       if( iCol<pTab->nCol ){
   67633         pTab->aCol[iCol].isPrimKey = 1;
   67634       }
   67635     }
   67636     if( pList->nExpr>1 ) iCol = -1;
   67637   }
   67638   if( iCol>=0 && iCol<pTab->nCol ){
   67639     zType = pTab->aCol[iCol].zType;
   67640   }
   67641   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
   67642         && sortOrder==SQLITE_SO_ASC ){
   67643     pTab->iPKey = iCol;
   67644     pTab->keyConf = (u8)onError;
   67645     assert( autoInc==0 || autoInc==1 );
   67646     pTab->tabFlags |= autoInc*TF_Autoincrement;
   67647   }else if( autoInc ){
   67648 #ifndef SQLITE_OMIT_AUTOINCREMENT
   67649     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
   67650        "INTEGER PRIMARY KEY");
   67651 #endif
   67652   }else{
   67653     Index *p;
   67654     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
   67655     if( p ){
   67656       p->autoIndex = 2;
   67657     }
   67658     pList = 0;
   67659   }
   67660 
   67661 primary_key_exit:
   67662   sqlite3ExprListDelete(pParse->db, pList);
   67663   return;
   67664 }
   67665 
   67666 /*
   67667 ** Add a new CHECK constraint to the table currently under construction.
   67668 */
   67669 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
   67670   Parse *pParse,    /* Parsing context */
   67671   Expr *pCheckExpr  /* The check expression */
   67672 ){
   67673   sqlite3 *db = pParse->db;
   67674 #ifndef SQLITE_OMIT_CHECK
   67675   Table *pTab = pParse->pNewTable;
   67676   if( pTab && !IN_DECLARE_VTAB ){
   67677     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
   67678   }else
   67679 #endif
   67680   {
   67681     sqlite3ExprDelete(db, pCheckExpr);
   67682   }
   67683 }
   67684 
   67685 /*
   67686 ** Set the collation function of the most recently parsed table column
   67687 ** to the CollSeq given.
   67688 */
   67689 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
   67690   Table *p;
   67691   int i;
   67692   char *zColl;              /* Dequoted name of collation sequence */
   67693   sqlite3 *db;
   67694 
   67695   if( (p = pParse->pNewTable)==0 ) return;
   67696   i = p->nCol-1;
   67697   db = pParse->db;
   67698   zColl = sqlite3NameFromToken(db, pToken);
   67699   if( !zColl ) return;
   67700 
   67701   if( sqlite3LocateCollSeq(pParse, zColl) ){
   67702     Index *pIdx;
   67703     p->aCol[i].zColl = zColl;
   67704 
   67705     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
   67706     ** then an index may have been created on this column before the
   67707     ** collation type was added. Correct this if it is the case.
   67708     */
   67709     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
   67710       assert( pIdx->nColumn==1 );
   67711       if( pIdx->aiColumn[0]==i ){
   67712         pIdx->azColl[0] = p->aCol[i].zColl;
   67713       }
   67714     }
   67715   }else{
   67716     sqlite3DbFree(db, zColl);
   67717   }
   67718 }
   67719 
   67720 /*
   67721 ** This function returns the collation sequence for database native text
   67722 ** encoding identified by the string zName, length nName.
   67723 **
   67724 ** If the requested collation sequence is not available, or not available
   67725 ** in the database native encoding, the collation factory is invoked to
   67726 ** request it. If the collation factory does not supply such a sequence,
   67727 ** and the sequence is available in another text encoding, then that is
   67728 ** returned instead.
   67729 **
   67730 ** If no versions of the requested collations sequence are available, or
   67731 ** another error occurs, NULL is returned and an error message written into
   67732 ** pParse.
   67733 **
   67734 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
   67735 ** invokes the collation factory if the named collation cannot be found
   67736 ** and generates an error message.
   67737 **
   67738 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
   67739 */
   67740 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
   67741   sqlite3 *db = pParse->db;
   67742   u8 enc = ENC(db);
   67743   u8 initbusy = db->init.busy;
   67744   CollSeq *pColl;
   67745 
   67746   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
   67747   if( !initbusy && (!pColl || !pColl->xCmp) ){
   67748     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
   67749     if( !pColl ){
   67750       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
   67751     }
   67752   }
   67753 
   67754   return pColl;
   67755 }
   67756 
   67757 
   67758 /*
   67759 ** Generate code that will increment the schema cookie.
   67760 **
   67761 ** The schema cookie is used to determine when the schema for the
   67762 ** database changes.  After each schema change, the cookie value
   67763 ** changes.  When a process first reads the schema it records the
   67764 ** cookie.  Thereafter, whenever it goes to access the database,
   67765 ** it checks the cookie to make sure the schema has not changed
   67766 ** since it was last read.
   67767 **
   67768 ** This plan is not completely bullet-proof.  It is possible for
   67769 ** the schema to change multiple times and for the cookie to be
   67770 ** set back to prior value.  But schema changes are infrequent
   67771 ** and the probability of hitting the same cookie value is only
   67772 ** 1 chance in 2^32.  So we're safe enough.
   67773 */
   67774 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
   67775   int r1 = sqlite3GetTempReg(pParse);
   67776   sqlite3 *db = pParse->db;
   67777   Vdbe *v = pParse->pVdbe;
   67778   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
   67779   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
   67780   sqlite3ReleaseTempReg(pParse, r1);
   67781 }
   67782 
   67783 /*
   67784 ** Measure the number of characters needed to output the given
   67785 ** identifier.  The number returned includes any quotes used
   67786 ** but does not include the null terminator.
   67787 **
   67788 ** The estimate is conservative.  It might be larger that what is
   67789 ** really needed.
   67790 */
   67791 static int identLength(const char *z){
   67792   int n;
   67793   for(n=0; *z; n++, z++){
   67794     if( *z=='"' ){ n++; }
   67795   }
   67796   return n + 2;
   67797 }
   67798 
   67799 /*
   67800 ** The first parameter is a pointer to an output buffer. The second
   67801 ** parameter is a pointer to an integer that contains the offset at
   67802 ** which to write into the output buffer. This function copies the
   67803 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
   67804 ** to the specified offset in the buffer and updates *pIdx to refer
   67805 ** to the first byte after the last byte written before returning.
   67806 **
   67807 ** If the string zSignedIdent consists entirely of alpha-numeric
   67808 ** characters, does not begin with a digit and is not an SQL keyword,
   67809 ** then it is copied to the output buffer exactly as it is. Otherwise,
   67810 ** it is quoted using double-quotes.
   67811 */
   67812 static void identPut(char *z, int *pIdx, char *zSignedIdent){
   67813   unsigned char *zIdent = (unsigned char*)zSignedIdent;
   67814   int i, j, needQuote;
   67815   i = *pIdx;
   67816 
   67817   for(j=0; zIdent[j]; j++){
   67818     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
   67819   }
   67820   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
   67821   if( !needQuote ){
   67822     needQuote = zIdent[j];
   67823   }
   67824 
   67825   if( needQuote ) z[i++] = '"';
   67826   for(j=0; zIdent[j]; j++){
   67827     z[i++] = zIdent[j];
   67828     if( zIdent[j]=='"' ) z[i++] = '"';
   67829   }
   67830   if( needQuote ) z[i++] = '"';
   67831   z[i] = 0;
   67832   *pIdx = i;
   67833 }
   67834 
   67835 /*
   67836 ** Generate a CREATE TABLE statement appropriate for the given
   67837 ** table.  Memory to hold the text of the statement is obtained
   67838 ** from sqliteMalloc() and must be freed by the calling function.
   67839 */
   67840 static char *createTableStmt(sqlite3 *db, Table *p){
   67841   int i, k, n;
   67842   char *zStmt;
   67843   char *zSep, *zSep2, *zEnd;
   67844   Column *pCol;
   67845   n = 0;
   67846   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
   67847     n += identLength(pCol->zName) + 5;
   67848   }
   67849   n += identLength(p->zName);
   67850   if( n<50 ){
   67851     zSep = "";
   67852     zSep2 = ",";
   67853     zEnd = ")";
   67854   }else{
   67855     zSep = "\n  ";
   67856     zSep2 = ",\n  ";
   67857     zEnd = "\n)";
   67858   }
   67859   n += 35 + 6*p->nCol;
   67860   zStmt = sqlite3Malloc( n );
   67861   if( zStmt==0 ){
   67862     db->mallocFailed = 1;
   67863     return 0;
   67864   }
   67865   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
   67866   k = sqlite3Strlen30(zStmt);
   67867   identPut(zStmt, &k, p->zName);
   67868   zStmt[k++] = '(';
   67869   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
   67870     static const char * const azType[] = {
   67871         /* SQLITE_AFF_TEXT    */ " TEXT",
   67872         /* SQLITE_AFF_NONE    */ "",
   67873         /* SQLITE_AFF_NUMERIC */ " NUM",
   67874         /* SQLITE_AFF_INTEGER */ " INT",
   67875         /* SQLITE_AFF_REAL    */ " REAL"
   67876     };
   67877     int len;
   67878     const char *zType;
   67879 
   67880     sqlite3_snprintf(n-k, &zStmt[k], zSep);
   67881     k += sqlite3Strlen30(&zStmt[k]);
   67882     zSep = zSep2;
   67883     identPut(zStmt, &k, pCol->zName);
   67884     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
   67885     assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
   67886     testcase( pCol->affinity==SQLITE_AFF_TEXT );
   67887     testcase( pCol->affinity==SQLITE_AFF_NONE );
   67888     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
   67889     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
   67890     testcase( pCol->affinity==SQLITE_AFF_REAL );
   67891 
   67892     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
   67893     len = sqlite3Strlen30(zType);
   67894     assert( pCol->affinity==SQLITE_AFF_NONE
   67895             || pCol->affinity==sqlite3AffinityType(zType) );
   67896     memcpy(&zStmt[k], zType, len);
   67897     k += len;
   67898     assert( k<=n );
   67899   }
   67900   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
   67901   return zStmt;
   67902 }
   67903 
   67904 /*
   67905 ** This routine is called to report the final ")" that terminates
   67906 ** a CREATE TABLE statement.
   67907 **
   67908 ** The table structure that other action routines have been building
   67909 ** is added to the internal hash tables, assuming no errors have
   67910 ** occurred.
   67911 **
   67912 ** An entry for the table is made in the master table on disk, unless
   67913 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
   67914 ** it means we are reading the sqlite_master table because we just
   67915 ** connected to the database or because the sqlite_master table has
   67916 ** recently changed, so the entry for this table already exists in
   67917 ** the sqlite_master table.  We do not want to create it again.
   67918 **
   67919 ** If the pSelect argument is not NULL, it means that this routine
   67920 ** was called to create a table generated from a
   67921 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
   67922 ** the new table will match the result set of the SELECT.
   67923 */
   67924 SQLITE_PRIVATE void sqlite3EndTable(
   67925   Parse *pParse,          /* Parse context */
   67926   Token *pCons,           /* The ',' token after the last column defn. */
   67927   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
   67928   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
   67929 ){
   67930   Table *p;
   67931   sqlite3 *db = pParse->db;
   67932   int iDb;
   67933 
   67934   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
   67935     return;
   67936   }
   67937   p = pParse->pNewTable;
   67938   if( p==0 ) return;
   67939 
   67940   assert( !db->init.busy || !pSelect );
   67941 
   67942   iDb = sqlite3SchemaToIndex(db, p->pSchema);
   67943 
   67944 #ifndef SQLITE_OMIT_CHECK
   67945   /* Resolve names in all CHECK constraint expressions.
   67946   */
   67947   if( p->pCheck ){
   67948     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
   67949     NameContext sNC;                /* Name context for pParse->pNewTable */
   67950 
   67951     memset(&sNC, 0, sizeof(sNC));
   67952     memset(&sSrc, 0, sizeof(sSrc));
   67953     sSrc.nSrc = 1;
   67954     sSrc.a[0].zName = p->zName;
   67955     sSrc.a[0].pTab = p;
   67956     sSrc.a[0].iCursor = -1;
   67957     sNC.pParse = pParse;
   67958     sNC.pSrcList = &sSrc;
   67959     sNC.isCheck = 1;
   67960     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
   67961       return;
   67962     }
   67963   }
   67964 #endif /* !defined(SQLITE_OMIT_CHECK) */
   67965 
   67966   /* If the db->init.busy is 1 it means we are reading the SQL off the
   67967   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
   67968   ** So do not write to the disk again.  Extract the root page number
   67969   ** for the table from the db->init.newTnum field.  (The page number
   67970   ** should have been put there by the sqliteOpenCb routine.)
   67971   */
   67972   if( db->init.busy ){
   67973     p->tnum = db->init.newTnum;
   67974   }
   67975 
   67976   /* If not initializing, then create a record for the new table
   67977   ** in the SQLITE_MASTER table of the database.
   67978   **
   67979   ** If this is a TEMPORARY table, write the entry into the auxiliary
   67980   ** file instead of into the main database file.
   67981   */
   67982   if( !db->init.busy ){
   67983     int n;
   67984     Vdbe *v;
   67985     char *zType;    /* "view" or "table" */
   67986     char *zType2;   /* "VIEW" or "TABLE" */
   67987     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
   67988 
   67989     v = sqlite3GetVdbe(pParse);
   67990     if( NEVER(v==0) ) return;
   67991 
   67992     sqlite3VdbeAddOp1(v, OP_Close, 0);
   67993 
   67994     /*
   67995     ** Initialize zType for the new view or table.
   67996     */
   67997     if( p->pSelect==0 ){
   67998       /* A regular table */
   67999       zType = "table";
   68000       zType2 = "TABLE";
   68001 #ifndef SQLITE_OMIT_VIEW
   68002     }else{
   68003       /* A view */
   68004       zType = "view";
   68005       zType2 = "VIEW";
   68006 #endif
   68007     }
   68008 
   68009     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
   68010     ** statement to populate the new table. The root-page number for the
   68011     ** new table is in register pParse->regRoot.
   68012     **
   68013     ** Once the SELECT has been coded by sqlite3Select(), it is in a
   68014     ** suitable state to query for the column names and types to be used
   68015     ** by the new table.
   68016     **
   68017     ** A shared-cache write-lock is not required to write to the new table,
   68018     ** as a schema-lock must have already been obtained to create it. Since
   68019     ** a schema-lock excludes all other database users, the write-lock would
   68020     ** be redundant.
   68021     */
   68022     if( pSelect ){
   68023       SelectDest dest;
   68024       Table *pSelTab;
   68025 
   68026       assert(pParse->nTab==1);
   68027       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
   68028       sqlite3VdbeChangeP5(v, 1);
   68029       pParse->nTab = 2;
   68030       sqlite3SelectDestInit(&dest, SRT_Table, 1);
   68031       sqlite3Select(pParse, pSelect, &dest);
   68032       sqlite3VdbeAddOp1(v, OP_Close, 1);
   68033       if( pParse->nErr==0 ){
   68034         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
   68035         if( pSelTab==0 ) return;
   68036         assert( p->aCol==0 );
   68037         p->nCol = pSelTab->nCol;
   68038         p->aCol = pSelTab->aCol;
   68039         pSelTab->nCol = 0;
   68040         pSelTab->aCol = 0;
   68041         sqlite3DeleteTable(pSelTab);
   68042       }
   68043     }
   68044 
   68045     /* Compute the complete text of the CREATE statement */
   68046     if( pSelect ){
   68047       zStmt = createTableStmt(db, p);
   68048     }else{
   68049       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
   68050       zStmt = sqlite3MPrintf(db,
   68051           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
   68052       );
   68053     }
   68054 
   68055     /* A slot for the record has already been allocated in the
   68056     ** SQLITE_MASTER table.  We just need to update that slot with all
   68057     ** the information we've collected.
   68058     */
   68059     sqlite3NestedParse(pParse,
   68060       "UPDATE %Q.%s "
   68061          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
   68062        "WHERE rowid=#%d",
   68063       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   68064       zType,
   68065       p->zName,
   68066       p->zName,
   68067       pParse->regRoot,
   68068       zStmt,
   68069       pParse->regRowid
   68070     );
   68071     sqlite3DbFree(db, zStmt);
   68072     sqlite3ChangeCookie(pParse, iDb);
   68073 
   68074 #ifndef SQLITE_OMIT_AUTOINCREMENT
   68075     /* Check to see if we need to create an sqlite_sequence table for
   68076     ** keeping track of autoincrement keys.
   68077     */
   68078     if( p->tabFlags & TF_Autoincrement ){
   68079       Db *pDb = &db->aDb[iDb];
   68080       if( pDb->pSchema->pSeqTab==0 ){
   68081         sqlite3NestedParse(pParse,
   68082           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
   68083           pDb->zName
   68084         );
   68085       }
   68086     }
   68087 #endif
   68088 
   68089     /* Reparse everything to update our internal data structures */
   68090     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
   68091         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
   68092   }
   68093 
   68094 
   68095   /* Add the table to the in-memory representation of the database.
   68096   */
   68097   if( db->init.busy ){
   68098     Table *pOld;
   68099     Schema *pSchema = p->pSchema;
   68100     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
   68101                              sqlite3Strlen30(p->zName),p);
   68102     if( pOld ){
   68103       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
   68104       db->mallocFailed = 1;
   68105       return;
   68106     }
   68107     pParse->pNewTable = 0;
   68108     db->nTable++;
   68109     db->flags |= SQLITE_InternChanges;
   68110 
   68111 #ifndef SQLITE_OMIT_ALTERTABLE
   68112     if( !p->pSelect ){
   68113       const char *zName = (const char *)pParse->sNameToken.z;
   68114       int nName;
   68115       assert( !pSelect && pCons && pEnd );
   68116       if( pCons->z==0 ){
   68117         pCons = pEnd;
   68118       }
   68119       nName = (int)((const char *)pCons->z - zName);
   68120       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
   68121     }
   68122 #endif
   68123   }
   68124 }
   68125 
   68126 #ifndef SQLITE_OMIT_VIEW
   68127 /*
   68128 ** The parser calls this routine in order to create a new VIEW
   68129 */
   68130 SQLITE_PRIVATE void sqlite3CreateView(
   68131   Parse *pParse,     /* The parsing context */
   68132   Token *pBegin,     /* The CREATE token that begins the statement */
   68133   Token *pName1,     /* The token that holds the name of the view */
   68134   Token *pName2,     /* The token that holds the name of the view */
   68135   Select *pSelect,   /* A SELECT statement that will become the new view */
   68136   int isTemp,        /* TRUE for a TEMPORARY view */
   68137   int noErr          /* Suppress error messages if VIEW already exists */
   68138 ){
   68139   Table *p;
   68140   int n;
   68141   const char *z;
   68142   Token sEnd;
   68143   DbFixer sFix;
   68144   Token *pName;
   68145   int iDb;
   68146   sqlite3 *db = pParse->db;
   68147 
   68148   if( pParse->nVar>0 ){
   68149     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
   68150     sqlite3SelectDelete(db, pSelect);
   68151     return;
   68152   }
   68153   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
   68154   p = pParse->pNewTable;
   68155   if( p==0 ){
   68156     sqlite3SelectDelete(db, pSelect);
   68157     return;
   68158   }
   68159   assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
   68160                              ** there could not have been an error */
   68161   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   68162   iDb = sqlite3SchemaToIndex(db, p->pSchema);
   68163   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
   68164     && sqlite3FixSelect(&sFix, pSelect)
   68165   ){
   68166     sqlite3SelectDelete(db, pSelect);
   68167     return;
   68168   }
   68169 
   68170   /* Make a copy of the entire SELECT statement that defines the view.
   68171   ** This will force all the Expr.token.z values to be dynamically
   68172   ** allocated rather than point to the input string - which means that
   68173   ** they will persist after the current sqlite3_exec() call returns.
   68174   */
   68175   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   68176   sqlite3SelectDelete(db, pSelect);
   68177   if( db->mallocFailed ){
   68178     return;
   68179   }
   68180   if( !db->init.busy ){
   68181     sqlite3ViewGetColumnNames(pParse, p);
   68182   }
   68183 
   68184   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
   68185   ** the end.
   68186   */
   68187   sEnd = pParse->sLastToken;
   68188   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
   68189     sEnd.z += sEnd.n;
   68190   }
   68191   sEnd.n = 0;
   68192   n = (int)(sEnd.z - pBegin->z);
   68193   z = pBegin->z;
   68194   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
   68195   sEnd.z = &z[n-1];
   68196   sEnd.n = 1;
   68197 
   68198   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
   68199   sqlite3EndTable(pParse, 0, &sEnd, 0);
   68200   return;
   68201 }
   68202 #endif /* SQLITE_OMIT_VIEW */
   68203 
   68204 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   68205 /*
   68206 ** The Table structure pTable is really a VIEW.  Fill in the names of
   68207 ** the columns of the view in the pTable structure.  Return the number
   68208 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
   68209 */
   68210 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
   68211   Table *pSelTab;   /* A fake table from which we get the result set */
   68212   Select *pSel;     /* Copy of the SELECT that implements the view */
   68213   int nErr = 0;     /* Number of errors encountered */
   68214   int n;            /* Temporarily holds the number of cursors assigned */
   68215   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
   68216   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   68217 
   68218   assert( pTable );
   68219 
   68220 #ifndef SQLITE_OMIT_VIRTUALTABLE
   68221   if( sqlite3VtabCallConnect(pParse, pTable) ){
   68222     return SQLITE_ERROR;
   68223   }
   68224   if( IsVirtual(pTable) ) return 0;
   68225 #endif
   68226 
   68227 #ifndef SQLITE_OMIT_VIEW
   68228   /* A positive nCol means the columns names for this view are
   68229   ** already known.
   68230   */
   68231   if( pTable->nCol>0 ) return 0;
   68232 
   68233   /* A negative nCol is a special marker meaning that we are currently
   68234   ** trying to compute the column names.  If we enter this routine with
   68235   ** a negative nCol, it means two or more views form a loop, like this:
   68236   **
   68237   **     CREATE VIEW one AS SELECT * FROM two;
   68238   **     CREATE VIEW two AS SELECT * FROM one;
   68239   **
   68240   ** Actually, the error above is now caught prior to reaching this point.
   68241   ** But the following test is still important as it does come up
   68242   ** in the following:
   68243   **
   68244   **     CREATE TABLE main.ex1(a);
   68245   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
   68246   **     SELECT * FROM temp.ex1;
   68247   */
   68248   if( pTable->nCol<0 ){
   68249     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
   68250     return 1;
   68251   }
   68252   assert( pTable->nCol>=0 );
   68253 
   68254   /* If we get this far, it means we need to compute the table names.
   68255   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
   68256   ** "*" elements in the results set of the view and will assign cursors
   68257   ** to the elements of the FROM clause.  But we do not want these changes
   68258   ** to be permanent.  So the computation is done on a copy of the SELECT
   68259   ** statement that defines the view.
   68260   */
   68261   assert( pTable->pSelect );
   68262   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
   68263   if( pSel ){
   68264     u8 enableLookaside = db->lookaside.bEnabled;
   68265     n = pParse->nTab;
   68266     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
   68267     pTable->nCol = -1;
   68268     db->lookaside.bEnabled = 0;
   68269 #ifndef SQLITE_OMIT_AUTHORIZATION
   68270     xAuth = db->xAuth;
   68271     db->xAuth = 0;
   68272     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
   68273     db->xAuth = xAuth;
   68274 #else
   68275     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
   68276 #endif
   68277     db->lookaside.bEnabled = enableLookaside;
   68278     pParse->nTab = n;
   68279     if( pSelTab ){
   68280       assert( pTable->aCol==0 );
   68281       pTable->nCol = pSelTab->nCol;
   68282       pTable->aCol = pSelTab->aCol;
   68283       pSelTab->nCol = 0;
   68284       pSelTab->aCol = 0;
   68285       sqlite3DeleteTable(pSelTab);
   68286       pTable->pSchema->flags |= DB_UnresetViews;
   68287     }else{
   68288       pTable->nCol = 0;
   68289       nErr++;
   68290     }
   68291     sqlite3SelectDelete(db, pSel);
   68292   } else {
   68293     nErr++;
   68294   }
   68295 #endif /* SQLITE_OMIT_VIEW */
   68296   return nErr;
   68297 }
   68298 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
   68299 
   68300 #ifndef SQLITE_OMIT_VIEW
   68301 /*
   68302 ** Clear the column names from every VIEW in database idx.
   68303 */
   68304 static void sqliteViewResetAll(sqlite3 *db, int idx){
   68305   HashElem *i;
   68306   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
   68307   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
   68308     Table *pTab = sqliteHashData(i);
   68309     if( pTab->pSelect ){
   68310       sqliteResetColumnNames(pTab);
   68311     }
   68312   }
   68313   DbClearProperty(db, idx, DB_UnresetViews);
   68314 }
   68315 #else
   68316 # define sqliteViewResetAll(A,B)
   68317 #endif /* SQLITE_OMIT_VIEW */
   68318 
   68319 /*
   68320 ** This function is called by the VDBE to adjust the internal schema
   68321 ** used by SQLite when the btree layer moves a table root page. The
   68322 ** root-page of a table or index in database iDb has changed from iFrom
   68323 ** to iTo.
   68324 **
   68325 ** Ticket #1728:  The symbol table might still contain information
   68326 ** on tables and/or indices that are the process of being deleted.
   68327 ** If you are unlucky, one of those deleted indices or tables might
   68328 ** have the same rootpage number as the real table or index that is
   68329 ** being moved.  So we cannot stop searching after the first match
   68330 ** because the first match might be for one of the deleted indices
   68331 ** or tables and not the table/index that is actually being moved.
   68332 ** We must continue looping until all tables and indices with
   68333 ** rootpage==iFrom have been converted to have a rootpage of iTo
   68334 ** in order to be certain that we got the right one.
   68335 */
   68336 #ifndef SQLITE_OMIT_AUTOVACUUM
   68337 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
   68338   HashElem *pElem;
   68339   Hash *pHash;
   68340 
   68341   pHash = &pDb->pSchema->tblHash;
   68342   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
   68343     Table *pTab = sqliteHashData(pElem);
   68344     if( pTab->tnum==iFrom ){
   68345       pTab->tnum = iTo;
   68346     }
   68347   }
   68348   pHash = &pDb->pSchema->idxHash;
   68349   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
   68350     Index *pIdx = sqliteHashData(pElem);
   68351     if( pIdx->tnum==iFrom ){
   68352       pIdx->tnum = iTo;
   68353     }
   68354   }
   68355 }
   68356 #endif
   68357 
   68358 /*
   68359 ** Write code to erase the table with root-page iTable from database iDb.
   68360 ** Also write code to modify the sqlite_master table and internal schema
   68361 ** if a root-page of another table is moved by the btree-layer whilst
   68362 ** erasing iTable (this can happen with an auto-vacuum database).
   68363 */
   68364 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
   68365   Vdbe *v = sqlite3GetVdbe(pParse);
   68366   int r1 = sqlite3GetTempReg(pParse);
   68367   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
   68368   sqlite3MayAbort(pParse);
   68369 #ifndef SQLITE_OMIT_AUTOVACUUM
   68370   /* OP_Destroy stores an in integer r1. If this integer
   68371   ** is non-zero, then it is the root page number of a table moved to
   68372   ** location iTable. The following code modifies the sqlite_master table to
   68373   ** reflect this.
   68374   **
   68375   ** The "#NNN" in the SQL is a special constant that means whatever value
   68376   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
   68377   ** token for additional information.
   68378   */
   68379   sqlite3NestedParse(pParse,
   68380      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
   68381      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
   68382 #endif
   68383   sqlite3ReleaseTempReg(pParse, r1);
   68384 }
   68385 
   68386 /*
   68387 ** Write VDBE code to erase table pTab and all associated indices on disk.
   68388 ** Code to update the sqlite_master tables and internal schema definitions
   68389 ** in case a root-page belonging to another table is moved by the btree layer
   68390 ** is also added (this can happen with an auto-vacuum database).
   68391 */
   68392 static void destroyTable(Parse *pParse, Table *pTab){
   68393 #ifdef SQLITE_OMIT_AUTOVACUUM
   68394   Index *pIdx;
   68395   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   68396   destroyRootPage(pParse, pTab->tnum, iDb);
   68397   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   68398     destroyRootPage(pParse, pIdx->tnum, iDb);
   68399   }
   68400 #else
   68401   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
   68402   ** is not defined), then it is important to call OP_Destroy on the
   68403   ** table and index root-pages in order, starting with the numerically
   68404   ** largest root-page number. This guarantees that none of the root-pages
   68405   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
   68406   ** following were coded:
   68407   **
   68408   ** OP_Destroy 4 0
   68409   ** ...
   68410   ** OP_Destroy 5 0
   68411   **
   68412   ** and root page 5 happened to be the largest root-page number in the
   68413   ** database, then root page 5 would be moved to page 4 by the
   68414   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
   68415   ** a free-list page.
   68416   */
   68417   int iTab = pTab->tnum;
   68418   int iDestroyed = 0;
   68419 
   68420   while( 1 ){
   68421     Index *pIdx;
   68422     int iLargest = 0;
   68423 
   68424     if( iDestroyed==0 || iTab<iDestroyed ){
   68425       iLargest = iTab;
   68426     }
   68427     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   68428       int iIdx = pIdx->tnum;
   68429       assert( pIdx->pSchema==pTab->pSchema );
   68430       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
   68431         iLargest = iIdx;
   68432       }
   68433     }
   68434     if( iLargest==0 ){
   68435       return;
   68436     }else{
   68437       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   68438       destroyRootPage(pParse, iLargest, iDb);
   68439       iDestroyed = iLargest;
   68440     }
   68441   }
   68442 #endif
   68443 }
   68444 
   68445 /*
   68446 ** This routine is called to do the work of a DROP TABLE statement.
   68447 ** pName is the name of the table to be dropped.
   68448 */
   68449 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
   68450   Table *pTab;
   68451   Vdbe *v;
   68452   sqlite3 *db = pParse->db;
   68453   int iDb;
   68454 
   68455   if( db->mallocFailed ){
   68456     goto exit_drop_table;
   68457   }
   68458   assert( pParse->nErr==0 );
   68459   assert( pName->nSrc==1 );
   68460   if( noErr ) db->suppressErr++;
   68461   pTab = sqlite3LocateTable(pParse, isView,
   68462                             pName->a[0].zName, pName->a[0].zDatabase);
   68463   if( noErr ) db->suppressErr--;
   68464 
   68465   if( pTab==0 ){
   68466     goto exit_drop_table;
   68467   }
   68468   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   68469   assert( iDb>=0 && iDb<db->nDb );
   68470 
   68471   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
   68472   ** it is initialized.
   68473   */
   68474   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
   68475     goto exit_drop_table;
   68476   }
   68477 #ifndef SQLITE_OMIT_AUTHORIZATION
   68478   {
   68479     int code;
   68480     const char *zTab = SCHEMA_TABLE(iDb);
   68481     const char *zDb = db->aDb[iDb].zName;
   68482     const char *zArg2 = 0;
   68483     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
   68484       goto exit_drop_table;
   68485     }
   68486     if( isView ){
   68487       if( !OMIT_TEMPDB && iDb==1 ){
   68488         code = SQLITE_DROP_TEMP_VIEW;
   68489       }else{
   68490         code = SQLITE_DROP_VIEW;
   68491       }
   68492 #ifndef SQLITE_OMIT_VIRTUALTABLE
   68493     }else if( IsVirtual(pTab) ){
   68494       code = SQLITE_DROP_VTABLE;
   68495       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
   68496 #endif
   68497     }else{
   68498       if( !OMIT_TEMPDB && iDb==1 ){
   68499         code = SQLITE_DROP_TEMP_TABLE;
   68500       }else{
   68501         code = SQLITE_DROP_TABLE;
   68502       }
   68503     }
   68504     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
   68505       goto exit_drop_table;
   68506     }
   68507     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
   68508       goto exit_drop_table;
   68509     }
   68510   }
   68511 #endif
   68512   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
   68513     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
   68514     goto exit_drop_table;
   68515   }
   68516 
   68517 #ifndef SQLITE_OMIT_VIEW
   68518   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
   68519   ** on a table.
   68520   */
   68521   if( isView && pTab->pSelect==0 ){
   68522     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
   68523     goto exit_drop_table;
   68524   }
   68525   if( !isView && pTab->pSelect ){
   68526     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
   68527     goto exit_drop_table;
   68528   }
   68529 #endif
   68530 
   68531   /* Generate code to remove the table from the master table
   68532   ** on disk.
   68533   */
   68534   v = sqlite3GetVdbe(pParse);
   68535   if( v ){
   68536     Trigger *pTrigger;
   68537     Db *pDb = &db->aDb[iDb];
   68538     sqlite3BeginWriteOperation(pParse, 1, iDb);
   68539 
   68540 #ifndef SQLITE_OMIT_VIRTUALTABLE
   68541     if( IsVirtual(pTab) ){
   68542       sqlite3VdbeAddOp0(v, OP_VBegin);
   68543     }
   68544 #endif
   68545     sqlite3FkDropTable(pParse, pName, pTab);
   68546 
   68547     /* Drop all triggers associated with the table being dropped. Code
   68548     ** is generated to remove entries from sqlite_master and/or
   68549     ** sqlite_temp_master if required.
   68550     */
   68551     pTrigger = sqlite3TriggerList(pParse, pTab);
   68552     while( pTrigger ){
   68553       assert( pTrigger->pSchema==pTab->pSchema ||
   68554           pTrigger->pSchema==db->aDb[1].pSchema );
   68555       sqlite3DropTriggerPtr(pParse, pTrigger);
   68556       pTrigger = pTrigger->pNext;
   68557     }
   68558 
   68559 #ifndef SQLITE_OMIT_AUTOINCREMENT
   68560     /* Remove any entries of the sqlite_sequence table associated with
   68561     ** the table being dropped. This is done before the table is dropped
   68562     ** at the btree level, in case the sqlite_sequence table needs to
   68563     ** move as a result of the drop (can happen in auto-vacuum mode).
   68564     */
   68565     if( pTab->tabFlags & TF_Autoincrement ){
   68566       sqlite3NestedParse(pParse,
   68567         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
   68568         pDb->zName, pTab->zName
   68569       );
   68570     }
   68571 #endif
   68572 
   68573     /* Drop all SQLITE_MASTER table and index entries that refer to the
   68574     ** table. The program name loops through the master table and deletes
   68575     ** every row that refers to a table of the same name as the one being
   68576     ** dropped. Triggers are handled seperately because a trigger can be
   68577     ** created in the temp database that refers to a table in another
   68578     ** database.
   68579     */
   68580     sqlite3NestedParse(pParse,
   68581         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
   68582         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
   68583 
   68584     /* Drop any statistics from the sqlite_stat1 table, if it exists */
   68585     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
   68586       sqlite3NestedParse(pParse,
   68587         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
   68588       );
   68589     }
   68590 
   68591     if( !isView && !IsVirtual(pTab) ){
   68592       destroyTable(pParse, pTab);
   68593     }
   68594 
   68595     /* Remove the table entry from SQLite's internal schema and modify
   68596     ** the schema cookie.
   68597     */
   68598     if( IsVirtual(pTab) ){
   68599       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
   68600     }
   68601     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
   68602     sqlite3ChangeCookie(pParse, iDb);
   68603   }
   68604   sqliteViewResetAll(db, iDb);
   68605 
   68606 exit_drop_table:
   68607   sqlite3SrcListDelete(db, pName);
   68608 }
   68609 
   68610 /*
   68611 ** This routine is called to create a new foreign key on the table
   68612 ** currently under construction.  pFromCol determines which columns
   68613 ** in the current table point to the foreign key.  If pFromCol==0 then
   68614 ** connect the key to the last column inserted.  pTo is the name of
   68615 ** the table referred to.  pToCol is a list of tables in the other
   68616 ** pTo table that the foreign key points to.  flags contains all
   68617 ** information about the conflict resolution algorithms specified
   68618 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
   68619 **
   68620 ** An FKey structure is created and added to the table currently
   68621 ** under construction in the pParse->pNewTable field.
   68622 **
   68623 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
   68624 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
   68625 */
   68626 SQLITE_PRIVATE void sqlite3CreateForeignKey(
   68627   Parse *pParse,       /* Parsing context */
   68628   ExprList *pFromCol,  /* Columns in this table that point to other table */
   68629   Token *pTo,          /* Name of the other table */
   68630   ExprList *pToCol,    /* Columns in the other table */
   68631   int flags            /* Conflict resolution algorithms. */
   68632 ){
   68633   sqlite3 *db = pParse->db;
   68634 #ifndef SQLITE_OMIT_FOREIGN_KEY
   68635   FKey *pFKey = 0;
   68636   FKey *pNextTo;
   68637   Table *p = pParse->pNewTable;
   68638   int nByte;
   68639   int i;
   68640   int nCol;
   68641   char *z;
   68642 
   68643   assert( pTo!=0 );
   68644   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
   68645   if( pFromCol==0 ){
   68646     int iCol = p->nCol-1;
   68647     if( NEVER(iCol<0) ) goto fk_end;
   68648     if( pToCol && pToCol->nExpr!=1 ){
   68649       sqlite3ErrorMsg(pParse, "foreign key on %s"
   68650          " should reference only one column of table %T",
   68651          p->aCol[iCol].zName, pTo);
   68652       goto fk_end;
   68653     }
   68654     nCol = 1;
   68655   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
   68656     sqlite3ErrorMsg(pParse,
   68657         "number of columns in foreign key does not match the number of "
   68658         "columns in the referenced table");
   68659     goto fk_end;
   68660   }else{
   68661     nCol = pFromCol->nExpr;
   68662   }
   68663   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
   68664   if( pToCol ){
   68665     for(i=0; i<pToCol->nExpr; i++){
   68666       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
   68667     }
   68668   }
   68669   pFKey = sqlite3DbMallocZero(db, nByte );
   68670   if( pFKey==0 ){
   68671     goto fk_end;
   68672   }
   68673   pFKey->pFrom = p;
   68674   pFKey->pNextFrom = p->pFKey;
   68675   z = (char*)&pFKey->aCol[nCol];
   68676   pFKey->zTo = z;
   68677   memcpy(z, pTo->z, pTo->n);
   68678   z[pTo->n] = 0;
   68679   sqlite3Dequote(z);
   68680   z += pTo->n+1;
   68681   pFKey->nCol = nCol;
   68682   if( pFromCol==0 ){
   68683     pFKey->aCol[0].iFrom = p->nCol-1;
   68684   }else{
   68685     for(i=0; i<nCol; i++){
   68686       int j;
   68687       for(j=0; j<p->nCol; j++){
   68688         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
   68689           pFKey->aCol[i].iFrom = j;
   68690           break;
   68691         }
   68692       }
   68693       if( j>=p->nCol ){
   68694         sqlite3ErrorMsg(pParse,
   68695           "unknown column \"%s\" in foreign key definition",
   68696           pFromCol->a[i].zName);
   68697         goto fk_end;
   68698       }
   68699     }
   68700   }
   68701   if( pToCol ){
   68702     for(i=0; i<nCol; i++){
   68703       int n = sqlite3Strlen30(pToCol->a[i].zName);
   68704       pFKey->aCol[i].zCol = z;
   68705       memcpy(z, pToCol->a[i].zName, n);
   68706       z[n] = 0;
   68707       z += n+1;
   68708     }
   68709   }
   68710   pFKey->isDeferred = 0;
   68711   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
   68712   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
   68713 
   68714   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
   68715       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
   68716   );
   68717   if( pNextTo==pFKey ){
   68718     db->mallocFailed = 1;
   68719     goto fk_end;
   68720   }
   68721   if( pNextTo ){
   68722     assert( pNextTo->pPrevTo==0 );
   68723     pFKey->pNextTo = pNextTo;
   68724     pNextTo->pPrevTo = pFKey;
   68725   }
   68726 
   68727   /* Link the foreign key to the table as the last step.
   68728   */
   68729   p->pFKey = pFKey;
   68730   pFKey = 0;
   68731 
   68732 fk_end:
   68733   sqlite3DbFree(db, pFKey);
   68734 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   68735   sqlite3ExprListDelete(db, pFromCol);
   68736   sqlite3ExprListDelete(db, pToCol);
   68737 }
   68738 
   68739 /*
   68740 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
   68741 ** clause is seen as part of a foreign key definition.  The isDeferred
   68742 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
   68743 ** The behavior of the most recently created foreign key is adjusted
   68744 ** accordingly.
   68745 */
   68746 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
   68747 #ifndef SQLITE_OMIT_FOREIGN_KEY
   68748   Table *pTab;
   68749   FKey *pFKey;
   68750   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
   68751   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
   68752   pFKey->isDeferred = (u8)isDeferred;
   68753 #endif
   68754 }
   68755 
   68756 /*
   68757 ** Generate code that will erase and refill index *pIdx.  This is
   68758 ** used to initialize a newly created index or to recompute the
   68759 ** content of an index in response to a REINDEX command.
   68760 **
   68761 ** if memRootPage is not negative, it means that the index is newly
   68762 ** created.  The register specified by memRootPage contains the
   68763 ** root page number of the index.  If memRootPage is negative, then
   68764 ** the index already exists and must be cleared before being refilled and
   68765 ** the root page number of the index is taken from pIndex->tnum.
   68766 */
   68767 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
   68768   Table *pTab = pIndex->pTable;  /* The table that is indexed */
   68769   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
   68770   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
   68771   int addr1;                     /* Address of top of loop */
   68772   int tnum;                      /* Root page of index */
   68773   Vdbe *v;                       /* Generate code into this virtual machine */
   68774   KeyInfo *pKey;                 /* KeyInfo for index */
   68775   int regIdxKey;                 /* Registers containing the index key */
   68776   int regRecord;                 /* Register holding assemblied index record */
   68777   sqlite3 *db = pParse->db;      /* The database connection */
   68778   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
   68779 
   68780 #ifndef SQLITE_OMIT_AUTHORIZATION
   68781   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
   68782       db->aDb[iDb].zName ) ){
   68783     return;
   68784   }
   68785 #endif
   68786 
   68787   /* Require a write-lock on the table to perform this operation */
   68788   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
   68789 
   68790   v = sqlite3GetVdbe(pParse);
   68791   if( v==0 ) return;
   68792   if( memRootPage>=0 ){
   68793     tnum = memRootPage;
   68794   }else{
   68795     tnum = pIndex->tnum;
   68796     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
   68797   }
   68798   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
   68799   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
   68800                     (char *)pKey, P4_KEYINFO_HANDOFF);
   68801   if( memRootPage>=0 ){
   68802     sqlite3VdbeChangeP5(v, 1);
   68803   }
   68804   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
   68805   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
   68806   regRecord = sqlite3GetTempReg(pParse);
   68807   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
   68808   if( pIndex->onError!=OE_None ){
   68809     const int regRowid = regIdxKey + pIndex->nColumn;
   68810     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
   68811     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
   68812 
   68813     /* The registers accessed by the OP_IsUnique opcode were allocated
   68814     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
   68815     ** call above. Just before that function was freed they were released
   68816     ** (made available to the compiler for reuse) using
   68817     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
   68818     ** opcode use the values stored within seems dangerous. However, since
   68819     ** we can be sure that no other temp registers have been allocated
   68820     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
   68821     */
   68822     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
   68823     sqlite3HaltConstraint(
   68824         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
   68825   }
   68826   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
   68827   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   68828   sqlite3ReleaseTempReg(pParse, regRecord);
   68829   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
   68830   sqlite3VdbeJumpHere(v, addr1);
   68831   sqlite3VdbeAddOp1(v, OP_Close, iTab);
   68832   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
   68833 }
   68834 
   68835 /*
   68836 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
   68837 ** and pTblList is the name of the table that is to be indexed.  Both will
   68838 ** be NULL for a primary key or an index that is created to satisfy a
   68839 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
   68840 ** as the table to be indexed.  pParse->pNewTable is a table that is
   68841 ** currently being constructed by a CREATE TABLE statement.
   68842 **
   68843 ** pList is a list of columns to be indexed.  pList will be NULL if this
   68844 ** is a primary key or unique-constraint on the most recent column added
   68845 ** to the table currently under construction.
   68846 **
   68847 ** If the index is created successfully, return a pointer to the new Index
   68848 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
   68849 ** as the tables primary key (Index.autoIndex==2).
   68850 */
   68851 SQLITE_PRIVATE Index *sqlite3CreateIndex(
   68852   Parse *pParse,     /* All information about this parse */
   68853   Token *pName1,     /* First part of index name. May be NULL */
   68854   Token *pName2,     /* Second part of index name. May be NULL */
   68855   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
   68856   ExprList *pList,   /* A list of columns to be indexed */
   68857   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
   68858   Token *pStart,     /* The CREATE token that begins this statement */
   68859   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
   68860   int sortOrder,     /* Sort order of primary key when pList==NULL */
   68861   int ifNotExist     /* Omit error if index already exists */
   68862 ){
   68863   Index *pRet = 0;     /* Pointer to return */
   68864   Table *pTab = 0;     /* Table to be indexed */
   68865   Index *pIndex = 0;   /* The index to be created */
   68866   char *zName = 0;     /* Name of the index */
   68867   int nName;           /* Number of characters in zName */
   68868   int i, j;
   68869   Token nullId;        /* Fake token for an empty ID list */
   68870   DbFixer sFix;        /* For assigning database names to pTable */
   68871   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
   68872   sqlite3 *db = pParse->db;
   68873   Db *pDb;             /* The specific table containing the indexed database */
   68874   int iDb;             /* Index of the database that is being written */
   68875   Token *pName = 0;    /* Unqualified name of the index to create */
   68876   struct ExprList_item *pListItem; /* For looping over pList */
   68877   int nCol;
   68878   int nExtra = 0;
   68879   char *zExtra;
   68880 
   68881   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
   68882   assert( pParse->nErr==0 );      /* Never called with prior errors */
   68883   if( db->mallocFailed || IN_DECLARE_VTAB ){
   68884     goto exit_create_index;
   68885   }
   68886   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   68887     goto exit_create_index;
   68888   }
   68889 
   68890   /*
   68891   ** Find the table that is to be indexed.  Return early if not found.
   68892   */
   68893   if( pTblName!=0 ){
   68894 
   68895     /* Use the two-part index name to determine the database
   68896     ** to search for the table. 'Fix' the table name to this db
   68897     ** before looking up the table.
   68898     */
   68899     assert( pName1 && pName2 );
   68900     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   68901     if( iDb<0 ) goto exit_create_index;
   68902 
   68903 #ifndef SQLITE_OMIT_TEMPDB
   68904     /* If the index name was unqualified, check if the the table
   68905     ** is a temp table. If so, set the database to 1. Do not do this
   68906     ** if initialising a database schema.
   68907     */
   68908     if( !db->init.busy ){
   68909       pTab = sqlite3SrcListLookup(pParse, pTblName);
   68910       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
   68911         iDb = 1;
   68912       }
   68913     }
   68914 #endif
   68915 
   68916     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
   68917         sqlite3FixSrcList(&sFix, pTblName)
   68918     ){
   68919       /* Because the parser constructs pTblName from a single identifier,
   68920       ** sqlite3FixSrcList can never fail. */
   68921       assert(0);
   68922     }
   68923     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
   68924         pTblName->a[0].zDatabase);
   68925     if( !pTab || db->mallocFailed ) goto exit_create_index;
   68926     assert( db->aDb[iDb].pSchema==pTab->pSchema );
   68927   }else{
   68928     assert( pName==0 );
   68929     pTab = pParse->pNewTable;
   68930     if( !pTab ) goto exit_create_index;
   68931     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   68932   }
   68933   pDb = &db->aDb[iDb];
   68934 
   68935   assert( pTab!=0 );
   68936   assert( pParse->nErr==0 );
   68937   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
   68938        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
   68939     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
   68940     goto exit_create_index;
   68941   }
   68942 #ifndef SQLITE_OMIT_VIEW
   68943   if( pTab->pSelect ){
   68944     sqlite3ErrorMsg(pParse, "views may not be indexed");
   68945     goto exit_create_index;
   68946   }
   68947 #endif
   68948 #ifndef SQLITE_OMIT_VIRTUALTABLE
   68949   if( IsVirtual(pTab) ){
   68950     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
   68951     goto exit_create_index;
   68952   }
   68953 #endif
   68954 
   68955   /*
   68956   ** Find the name of the index.  Make sure there is not already another
   68957   ** index or table with the same name.
   68958   **
   68959   ** Exception:  If we are reading the names of permanent indices from the
   68960   ** sqlite_master table (because some other process changed the schema) and
   68961   ** one of the index names collides with the name of a temporary table or
   68962   ** index, then we will continue to process this index.
   68963   **
   68964   ** If pName==0 it means that we are
   68965   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
   68966   ** own name.
   68967   */
   68968   if( pName ){
   68969     zName = sqlite3NameFromToken(db, pName);
   68970     if( zName==0 ) goto exit_create_index;
   68971     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   68972       goto exit_create_index;
   68973     }
   68974     if( !db->init.busy ){
   68975       if( sqlite3FindTable(db, zName, 0)!=0 ){
   68976         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
   68977         goto exit_create_index;
   68978       }
   68979     }
   68980     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
   68981       if( !ifNotExist ){
   68982         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
   68983       }
   68984       goto exit_create_index;
   68985     }
   68986   }else{
   68987     int n;
   68988     Index *pLoop;
   68989     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
   68990     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
   68991     if( zName==0 ){
   68992       goto exit_create_index;
   68993     }
   68994   }
   68995 
   68996   /* Check for authorization to create an index.
   68997   */
   68998 #ifndef SQLITE_OMIT_AUTHORIZATION
   68999   {
   69000     const char *zDb = pDb->zName;
   69001     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
   69002       goto exit_create_index;
   69003     }
   69004     i = SQLITE_CREATE_INDEX;
   69005     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
   69006     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
   69007       goto exit_create_index;
   69008     }
   69009   }
   69010 #endif
   69011 
   69012   /* If pList==0, it means this routine was called to make a primary
   69013   ** key out of the last column added to the table under construction.
   69014   ** So create a fake list to simulate this.
   69015   */
   69016   if( pList==0 ){
   69017     nullId.z = pTab->aCol[pTab->nCol-1].zName;
   69018     nullId.n = sqlite3Strlen30((char*)nullId.z);
   69019     pList = sqlite3ExprListAppend(pParse, 0, 0);
   69020     if( pList==0 ) goto exit_create_index;
   69021     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
   69022     pList->a[0].sortOrder = (u8)sortOrder;
   69023   }
   69024 
   69025   /* Figure out how many bytes of space are required to store explicitly
   69026   ** specified collation sequence names.
   69027   */
   69028   for(i=0; i<pList->nExpr; i++){
   69029     Expr *pExpr = pList->a[i].pExpr;
   69030     if( pExpr ){
   69031       CollSeq *pColl = pExpr->pColl;
   69032       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
   69033       ** failure we have quit before reaching this point. */
   69034       if( ALWAYS(pColl) ){
   69035         nExtra += (1 + sqlite3Strlen30(pColl->zName));
   69036       }
   69037     }
   69038   }
   69039 
   69040   /*
   69041   ** Allocate the index structure.
   69042   */
   69043   nName = sqlite3Strlen30(zName);
   69044   nCol = pList->nExpr;
   69045   pIndex = sqlite3DbMallocZero(db,
   69046       sizeof(Index) +              /* Index structure  */
   69047       sizeof(int)*nCol +           /* Index.aiColumn   */
   69048       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
   69049       sizeof(char *)*nCol +        /* Index.azColl     */
   69050       sizeof(u8)*nCol +            /* Index.aSortOrder */
   69051       nName + 1 +                  /* Index.zName      */
   69052       nExtra                       /* Collation sequence names */
   69053   );
   69054   if( db->mallocFailed ){
   69055     goto exit_create_index;
   69056   }
   69057   pIndex->azColl = (char**)(&pIndex[1]);
   69058   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
   69059   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
   69060   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
   69061   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
   69062   zExtra = (char *)(&pIndex->zName[nName+1]);
   69063   memcpy(pIndex->zName, zName, nName+1);
   69064   pIndex->pTable = pTab;
   69065   pIndex->nColumn = pList->nExpr;
   69066   pIndex->onError = (u8)onError;
   69067   pIndex->autoIndex = (u8)(pName==0);
   69068   pIndex->pSchema = db->aDb[iDb].pSchema;
   69069 
   69070   /* Check to see if we should honor DESC requests on index columns
   69071   */
   69072   if( pDb->pSchema->file_format>=4 ){
   69073     sortOrderMask = -1;   /* Honor DESC */
   69074   }else{
   69075     sortOrderMask = 0;    /* Ignore DESC */
   69076   }
   69077 
   69078   /* Scan the names of the columns of the table to be indexed and
   69079   ** load the column indices into the Index structure.  Report an error
   69080   ** if any column is not found.
   69081   **
   69082   ** TODO:  Add a test to make sure that the same column is not named
   69083   ** more than once within the same index.  Only the first instance of
   69084   ** the column will ever be used by the optimizer.  Note that using the
   69085   ** same column more than once cannot be an error because that would
   69086   ** break backwards compatibility - it needs to be a warning.
   69087   */
   69088   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
   69089     const char *zColName = pListItem->zName;
   69090     Column *pTabCol;
   69091     int requestedSortOrder;
   69092     char *zColl;                   /* Collation sequence name */
   69093 
   69094     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
   69095       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
   69096     }
   69097     if( j>=pTab->nCol ){
   69098       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
   69099         pTab->zName, zColName);
   69100       goto exit_create_index;
   69101     }
   69102     pIndex->aiColumn[i] = j;
   69103     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
   69104     ** the way the "idxlist" non-terminal is constructed by the parser,
   69105     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
   69106     ** must exist or else there must have been an OOM error.  But if there
   69107     ** was an OOM error, we would never reach this point. */
   69108     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
   69109       int nColl;
   69110       zColl = pListItem->pExpr->pColl->zName;
   69111       nColl = sqlite3Strlen30(zColl) + 1;
   69112       assert( nExtra>=nColl );
   69113       memcpy(zExtra, zColl, nColl);
   69114       zColl = zExtra;
   69115       zExtra += nColl;
   69116       nExtra -= nColl;
   69117     }else{
   69118       zColl = pTab->aCol[j].zColl;
   69119       if( !zColl ){
   69120         zColl = db->pDfltColl->zName;
   69121       }
   69122     }
   69123     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
   69124       goto exit_create_index;
   69125     }
   69126     pIndex->azColl[i] = zColl;
   69127     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
   69128     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
   69129   }
   69130   sqlite3DefaultRowEst(pIndex);
   69131 
   69132   if( pTab==pParse->pNewTable ){
   69133     /* This routine has been called to create an automatic index as a
   69134     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
   69135     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
   69136     ** i.e. one of:
   69137     **
   69138     ** CREATE TABLE t(x PRIMARY KEY, y);
   69139     ** CREATE TABLE t(x, y, UNIQUE(x, y));
   69140     **
   69141     ** Either way, check to see if the table already has such an index. If
   69142     ** so, don't bother creating this one. This only applies to
   69143     ** automatically created indices. Users can do as they wish with
   69144     ** explicit indices.
   69145     **
   69146     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
   69147     ** (and thus suppressing the second one) even if they have different
   69148     ** sort orders.
   69149     **
   69150     ** If there are different collating sequences or if the columns of
   69151     ** the constraint occur in different orders, then the constraints are
   69152     ** considered distinct and both result in separate indices.
   69153     */
   69154     Index *pIdx;
   69155     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   69156       int k;
   69157       assert( pIdx->onError!=OE_None );
   69158       assert( pIdx->autoIndex );
   69159       assert( pIndex->onError!=OE_None );
   69160 
   69161       if( pIdx->nColumn!=pIndex->nColumn ) continue;
   69162       for(k=0; k<pIdx->nColumn; k++){
   69163         const char *z1;
   69164         const char *z2;
   69165         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
   69166         z1 = pIdx->azColl[k];
   69167         z2 = pIndex->azColl[k];
   69168         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
   69169       }
   69170       if( k==pIdx->nColumn ){
   69171         if( pIdx->onError!=pIndex->onError ){
   69172           /* This constraint creates the same index as a previous
   69173           ** constraint specified somewhere in the CREATE TABLE statement.
   69174           ** However the ON CONFLICT clauses are different. If both this
   69175           ** constraint and the previous equivalent constraint have explicit
   69176           ** ON CONFLICT clauses this is an error. Otherwise, use the
   69177           ** explicitly specified behaviour for the index.
   69178           */
   69179           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
   69180             sqlite3ErrorMsg(pParse,
   69181                 "conflicting ON CONFLICT clauses specified", 0);
   69182           }
   69183           if( pIdx->onError==OE_Default ){
   69184             pIdx->onError = pIndex->onError;
   69185           }
   69186         }
   69187         goto exit_create_index;
   69188       }
   69189     }
   69190   }
   69191 
   69192   /* Link the new Index structure to its table and to the other
   69193   ** in-memory database structures.
   69194   */
   69195   if( db->init.busy ){
   69196     Index *p;
   69197     p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
   69198                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
   69199                           pIndex);
   69200     if( p ){
   69201       assert( p==pIndex );  /* Malloc must have failed */
   69202       db->mallocFailed = 1;
   69203       goto exit_create_index;
   69204     }
   69205     db->flags |= SQLITE_InternChanges;
   69206     if( pTblName!=0 ){
   69207       pIndex->tnum = db->init.newTnum;
   69208     }
   69209   }
   69210 
   69211   /* If the db->init.busy is 0 then create the index on disk.  This
   69212   ** involves writing the index into the master table and filling in the
   69213   ** index with the current table contents.
   69214   **
   69215   ** The db->init.busy is 0 when the user first enters a CREATE INDEX
   69216   ** command.  db->init.busy is 1 when a database is opened and
   69217   ** CREATE INDEX statements are read out of the master table.  In
   69218   ** the latter case the index already exists on disk, which is why
   69219   ** we don't want to recreate it.
   69220   **
   69221   ** If pTblName==0 it means this index is generated as a primary key
   69222   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
   69223   ** has just been created, it contains no data and the index initialization
   69224   ** step can be skipped.
   69225   */
   69226   else{ /* if( db->init.busy==0 ) */
   69227     Vdbe *v;
   69228     char *zStmt;
   69229     int iMem = ++pParse->nMem;
   69230 
   69231     v = sqlite3GetVdbe(pParse);
   69232     if( v==0 ) goto exit_create_index;
   69233 
   69234 
   69235     /* Create the rootpage for the index
   69236     */
   69237     sqlite3BeginWriteOperation(pParse, 1, iDb);
   69238     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
   69239 
   69240     /* Gather the complete text of the CREATE INDEX statement into
   69241     ** the zStmt variable
   69242     */
   69243     if( pStart ){
   69244       assert( pEnd!=0 );
   69245       /* A named index with an explicit CREATE INDEX statement */
   69246       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
   69247         onError==OE_None ? "" : " UNIQUE",
   69248         pEnd->z - pName->z + 1,
   69249         pName->z);
   69250     }else{
   69251       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
   69252       /* zStmt = sqlite3MPrintf(""); */
   69253       zStmt = 0;
   69254     }
   69255 
   69256     /* Add an entry in sqlite_master for this index
   69257     */
   69258     sqlite3NestedParse(pParse,
   69259         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
   69260         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   69261         pIndex->zName,
   69262         pTab->zName,
   69263         iMem,
   69264         zStmt
   69265     );
   69266     sqlite3DbFree(db, zStmt);
   69267 
   69268     /* Fill the index with data and reparse the schema. Code an OP_Expire
   69269     ** to invalidate all pre-compiled statements.
   69270     */
   69271     if( pTblName ){
   69272       sqlite3RefillIndex(pParse, pIndex, iMem);
   69273       sqlite3ChangeCookie(pParse, iDb);
   69274       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
   69275          sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
   69276       sqlite3VdbeAddOp1(v, OP_Expire, 0);
   69277     }
   69278   }
   69279 
   69280   /* When adding an index to the list of indices for a table, make
   69281   ** sure all indices labeled OE_Replace come after all those labeled
   69282   ** OE_Ignore.  This is necessary for the correct constraint check
   69283   ** processing (in sqlite3GenerateConstraintChecks()) as part of
   69284   ** UPDATE and INSERT statements.
   69285   */
   69286   if( db->init.busy || pTblName==0 ){
   69287     if( onError!=OE_Replace || pTab->pIndex==0
   69288          || pTab->pIndex->onError==OE_Replace){
   69289       pIndex->pNext = pTab->pIndex;
   69290       pTab->pIndex = pIndex;
   69291     }else{
   69292       Index *pOther = pTab->pIndex;
   69293       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
   69294         pOther = pOther->pNext;
   69295       }
   69296       pIndex->pNext = pOther->pNext;
   69297       pOther->pNext = pIndex;
   69298     }
   69299     pRet = pIndex;
   69300     pIndex = 0;
   69301   }
   69302 
   69303   /* Clean up before exiting */
   69304 exit_create_index:
   69305   if( pIndex ){
   69306     sqlite3_free(pIndex->zColAff);
   69307     sqlite3DbFree(db, pIndex);
   69308   }
   69309   sqlite3ExprListDelete(db, pList);
   69310   sqlite3SrcListDelete(db, pTblName);
   69311   sqlite3DbFree(db, zName);
   69312   return pRet;
   69313 }
   69314 
   69315 /*
   69316 ** Fill the Index.aiRowEst[] array with default information - information
   69317 ** to be used when we have not run the ANALYZE command.
   69318 **
   69319 ** aiRowEst[0] is suppose to contain the number of elements in the index.
   69320 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
   69321 ** number of rows in the table that match any particular value of the
   69322 ** first column of the index.  aiRowEst[2] is an estimate of the number
   69323 ** of rows that match any particular combiniation of the first 2 columns
   69324 ** of the index.  And so forth.  It must always be the case that
   69325 *
   69326 **           aiRowEst[N]<=aiRowEst[N-1]
   69327 **           aiRowEst[N]>=1
   69328 **
   69329 ** Apart from that, we have little to go on besides intuition as to
   69330 ** how aiRowEst[] should be initialized.  The numbers generated here
   69331 ** are based on typical values found in actual indices.
   69332 */
   69333 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
   69334   unsigned *a = pIdx->aiRowEst;
   69335   int i;
   69336   assert( a!=0 );
   69337   a[0] = 1000000;
   69338   for(i=pIdx->nColumn; i>=5; i--){
   69339     a[i] = 5;
   69340   }
   69341   while( i>=1 ){
   69342     a[i] = 11 - i;
   69343     i--;
   69344   }
   69345   if( pIdx->onError!=OE_None ){
   69346     a[pIdx->nColumn] = 1;
   69347   }
   69348 }
   69349 
   69350 /*
   69351 ** This routine will drop an existing named index.  This routine
   69352 ** implements the DROP INDEX statement.
   69353 */
   69354 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
   69355   Index *pIndex;
   69356   Vdbe *v;
   69357   sqlite3 *db = pParse->db;
   69358   int iDb;
   69359 
   69360   assert( pParse->nErr==0 );   /* Never called with prior errors */
   69361   if( db->mallocFailed ){
   69362     goto exit_drop_index;
   69363   }
   69364   assert( pName->nSrc==1 );
   69365   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   69366     goto exit_drop_index;
   69367   }
   69368   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
   69369   if( pIndex==0 ){
   69370     if( !ifExists ){
   69371       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
   69372     }
   69373     pParse->checkSchema = 1;
   69374     goto exit_drop_index;
   69375   }
   69376   if( pIndex->autoIndex ){
   69377     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
   69378       "or PRIMARY KEY constraint cannot be dropped", 0);
   69379     goto exit_drop_index;
   69380   }
   69381   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
   69382 #ifndef SQLITE_OMIT_AUTHORIZATION
   69383   {
   69384     int code = SQLITE_DROP_INDEX;
   69385     Table *pTab = pIndex->pTable;
   69386     const char *zDb = db->aDb[iDb].zName;
   69387     const char *zTab = SCHEMA_TABLE(iDb);
   69388     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
   69389       goto exit_drop_index;
   69390     }
   69391     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
   69392     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
   69393       goto exit_drop_index;
   69394     }
   69395   }
   69396 #endif
   69397 
   69398   /* Generate code to remove the index and from the master table */
   69399   v = sqlite3GetVdbe(pParse);
   69400   if( v ){
   69401     sqlite3BeginWriteOperation(pParse, 1, iDb);
   69402     sqlite3NestedParse(pParse,
   69403        "DELETE FROM %Q.%s WHERE name=%Q",
   69404        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   69405        pIndex->zName
   69406     );
   69407     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
   69408       sqlite3NestedParse(pParse,
   69409         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
   69410         db->aDb[iDb].zName, pIndex->zName
   69411       );
   69412     }
   69413     sqlite3ChangeCookie(pParse, iDb);
   69414     destroyRootPage(pParse, pIndex->tnum, iDb);
   69415     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
   69416   }
   69417 
   69418 exit_drop_index:
   69419   sqlite3SrcListDelete(db, pName);
   69420 }
   69421 
   69422 /*
   69423 ** pArray is a pointer to an array of objects.  Each object in the
   69424 ** array is szEntry bytes in size.  This routine allocates a new
   69425 ** object on the end of the array.
   69426 **
   69427 ** *pnEntry is the number of entries already in use.  *pnAlloc is
   69428 ** the previously allocated size of the array.  initSize is the
   69429 ** suggested initial array size allocation.
   69430 **
   69431 ** The index of the new entry is returned in *pIdx.
   69432 **
   69433 ** This routine returns a pointer to the array of objects.  This
   69434 ** might be the same as the pArray parameter or it might be a different
   69435 ** pointer if the array was resized.
   69436 */
   69437 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
   69438   sqlite3 *db,      /* Connection to notify of malloc failures */
   69439   void *pArray,     /* Array of objects.  Might be reallocated */
   69440   int szEntry,      /* Size of each object in the array */
   69441   int initSize,     /* Suggested initial allocation, in elements */
   69442   int *pnEntry,     /* Number of objects currently in use */
   69443   int *pnAlloc,     /* Current size of the allocation, in elements */
   69444   int *pIdx         /* Write the index of a new slot here */
   69445 ){
   69446   char *z;
   69447   if( *pnEntry >= *pnAlloc ){
   69448     void *pNew;
   69449     int newSize;
   69450     newSize = (*pnAlloc)*2 + initSize;
   69451     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
   69452     if( pNew==0 ){
   69453       *pIdx = -1;
   69454       return pArray;
   69455     }
   69456     *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
   69457     pArray = pNew;
   69458   }
   69459   z = (char*)pArray;
   69460   memset(&z[*pnEntry * szEntry], 0, szEntry);
   69461   *pIdx = *pnEntry;
   69462   ++*pnEntry;
   69463   return pArray;
   69464 }
   69465 
   69466 /*
   69467 ** Append a new element to the given IdList.  Create a new IdList if
   69468 ** need be.
   69469 **
   69470 ** A new IdList is returned, or NULL if malloc() fails.
   69471 */
   69472 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
   69473   int i;
   69474   if( pList==0 ){
   69475     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
   69476     if( pList==0 ) return 0;
   69477     pList->nAlloc = 0;
   69478   }
   69479   pList->a = sqlite3ArrayAllocate(
   69480       db,
   69481       pList->a,
   69482       sizeof(pList->a[0]),
   69483       5,
   69484       &pList->nId,
   69485       &pList->nAlloc,
   69486       &i
   69487   );
   69488   if( i<0 ){
   69489     sqlite3IdListDelete(db, pList);
   69490     return 0;
   69491   }
   69492   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
   69493   return pList;
   69494 }
   69495 
   69496 /*
   69497 ** Delete an IdList.
   69498 */
   69499 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
   69500   int i;
   69501   if( pList==0 ) return;
   69502   for(i=0; i<pList->nId; i++){
   69503     sqlite3DbFree(db, pList->a[i].zName);
   69504   }
   69505   sqlite3DbFree(db, pList->a);
   69506   sqlite3DbFree(db, pList);
   69507 }
   69508 
   69509 /*
   69510 ** Return the index in pList of the identifier named zId.  Return -1
   69511 ** if not found.
   69512 */
   69513 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
   69514   int i;
   69515   if( pList==0 ) return -1;
   69516   for(i=0; i<pList->nId; i++){
   69517     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
   69518   }
   69519   return -1;
   69520 }
   69521 
   69522 /*
   69523 ** Expand the space allocated for the given SrcList object by
   69524 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
   69525 ** New slots are zeroed.
   69526 **
   69527 ** For example, suppose a SrcList initially contains two entries: A,B.
   69528 ** To append 3 new entries onto the end, do this:
   69529 **
   69530 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
   69531 **
   69532 ** After the call above it would contain:  A, B, nil, nil, nil.
   69533 ** If the iStart argument had been 1 instead of 2, then the result
   69534 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
   69535 ** the iStart value would be 0.  The result then would
   69536 ** be: nil, nil, nil, A, B.
   69537 **
   69538 ** If a memory allocation fails the SrcList is unchanged.  The
   69539 ** db->mallocFailed flag will be set to true.
   69540 */
   69541 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
   69542   sqlite3 *db,       /* Database connection to notify of OOM errors */
   69543   SrcList *pSrc,     /* The SrcList to be enlarged */
   69544   int nExtra,        /* Number of new slots to add to pSrc->a[] */
   69545   int iStart         /* Index in pSrc->a[] of first new slot */
   69546 ){
   69547   int i;
   69548 
   69549   /* Sanity checking on calling parameters */
   69550   assert( iStart>=0 );
   69551   assert( nExtra>=1 );
   69552   assert( pSrc!=0 );
   69553   assert( iStart<=pSrc->nSrc );
   69554 
   69555   /* Allocate additional space if needed */
   69556   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
   69557     SrcList *pNew;
   69558     int nAlloc = pSrc->nSrc+nExtra;
   69559     int nGot;
   69560     pNew = sqlite3DbRealloc(db, pSrc,
   69561                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
   69562     if( pNew==0 ){
   69563       assert( db->mallocFailed );
   69564       return pSrc;
   69565     }
   69566     pSrc = pNew;
   69567     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
   69568     pSrc->nAlloc = (u16)nGot;
   69569   }
   69570 
   69571   /* Move existing slots that come after the newly inserted slots
   69572   ** out of the way */
   69573   for(i=pSrc->nSrc-1; i>=iStart; i--){
   69574     pSrc->a[i+nExtra] = pSrc->a[i];
   69575   }
   69576   pSrc->nSrc += (i16)nExtra;
   69577 
   69578   /* Zero the newly allocated slots */
   69579   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
   69580   for(i=iStart; i<iStart+nExtra; i++){
   69581     pSrc->a[i].iCursor = -1;
   69582   }
   69583 
   69584   /* Return a pointer to the enlarged SrcList */
   69585   return pSrc;
   69586 }
   69587 
   69588 
   69589 /*
   69590 ** Append a new table name to the given SrcList.  Create a new SrcList if
   69591 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
   69592 **
   69593 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
   69594 ** SrcList might be the same as the SrcList that was input or it might be
   69595 ** a new one.  If an OOM error does occurs, then the prior value of pList
   69596 ** that is input to this routine is automatically freed.
   69597 **
   69598 ** If pDatabase is not null, it means that the table has an optional
   69599 ** database name prefix.  Like this:  "database.table".  The pDatabase
   69600 ** points to the table name and the pTable points to the database name.
   69601 ** The SrcList.a[].zName field is filled with the table name which might
   69602 ** come from pTable (if pDatabase is NULL) or from pDatabase.
   69603 ** SrcList.a[].zDatabase is filled with the database name from pTable,
   69604 ** or with NULL if no database is specified.
   69605 **
   69606 ** In other words, if call like this:
   69607 **
   69608 **         sqlite3SrcListAppend(D,A,B,0);
   69609 **
   69610 ** Then B is a table name and the database name is unspecified.  If called
   69611 ** like this:
   69612 **
   69613 **         sqlite3SrcListAppend(D,A,B,C);
   69614 **
   69615 ** Then C is the table name and B is the database name.  If C is defined
   69616 ** then so is B.  In other words, we never have a case where:
   69617 **
   69618 **         sqlite3SrcListAppend(D,A,0,C);
   69619 **
   69620 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
   69621 ** before being added to the SrcList.
   69622 */
   69623 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
   69624   sqlite3 *db,        /* Connection to notify of malloc failures */
   69625   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
   69626   Token *pTable,      /* Table to append */
   69627   Token *pDatabase    /* Database of the table */
   69628 ){
   69629   struct SrcList_item *pItem;
   69630   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
   69631   if( pList==0 ){
   69632     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
   69633     if( pList==0 ) return 0;
   69634     pList->nAlloc = 1;
   69635   }
   69636   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
   69637   if( db->mallocFailed ){
   69638     sqlite3SrcListDelete(db, pList);
   69639     return 0;
   69640   }
   69641   pItem = &pList->a[pList->nSrc-1];
   69642   if( pDatabase && pDatabase->z==0 ){
   69643     pDatabase = 0;
   69644   }
   69645   if( pDatabase ){
   69646     Token *pTemp = pDatabase;
   69647     pDatabase = pTable;
   69648     pTable = pTemp;
   69649   }
   69650   pItem->zName = sqlite3NameFromToken(db, pTable);
   69651   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
   69652   return pList;
   69653 }
   69654 
   69655 /*
   69656 ** Assign VdbeCursor index numbers to all tables in a SrcList
   69657 */
   69658 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
   69659   int i;
   69660   struct SrcList_item *pItem;
   69661   assert(pList || pParse->db->mallocFailed );
   69662   if( pList ){
   69663     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
   69664       if( pItem->iCursor>=0 ) break;
   69665       pItem->iCursor = pParse->nTab++;
   69666       if( pItem->pSelect ){
   69667         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
   69668       }
   69669     }
   69670   }
   69671 }
   69672 
   69673 /*
   69674 ** Delete an entire SrcList including all its substructure.
   69675 */
   69676 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
   69677   int i;
   69678   struct SrcList_item *pItem;
   69679   if( pList==0 ) return;
   69680   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
   69681     sqlite3DbFree(db, pItem->zDatabase);
   69682     sqlite3DbFree(db, pItem->zName);
   69683     sqlite3DbFree(db, pItem->zAlias);
   69684     sqlite3DbFree(db, pItem->zIndex);
   69685     sqlite3DeleteTable(pItem->pTab);
   69686     sqlite3SelectDelete(db, pItem->pSelect);
   69687     sqlite3ExprDelete(db, pItem->pOn);
   69688     sqlite3IdListDelete(db, pItem->pUsing);
   69689   }
   69690   sqlite3DbFree(db, pList);
   69691 }
   69692 
   69693 /*
   69694 ** This routine is called by the parser to add a new term to the
   69695 ** end of a growing FROM clause.  The "p" parameter is the part of
   69696 ** the FROM clause that has already been constructed.  "p" is NULL
   69697 ** if this is the first term of the FROM clause.  pTable and pDatabase
   69698 ** are the name of the table and database named in the FROM clause term.
   69699 ** pDatabase is NULL if the database name qualifier is missing - the
   69700 ** usual case.  If the term has a alias, then pAlias points to the
   69701 ** alias token.  If the term is a subquery, then pSubquery is the
   69702 ** SELECT statement that the subquery encodes.  The pTable and
   69703 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
   69704 ** parameters are the content of the ON and USING clauses.
   69705 **
   69706 ** Return a new SrcList which encodes is the FROM with the new
   69707 ** term added.
   69708 */
   69709 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
   69710   Parse *pParse,          /* Parsing context */
   69711   SrcList *p,             /* The left part of the FROM clause already seen */
   69712   Token *pTable,          /* Name of the table to add to the FROM clause */
   69713   Token *pDatabase,       /* Name of the database containing pTable */
   69714   Token *pAlias,          /* The right-hand side of the AS subexpression */
   69715   Select *pSubquery,      /* A subquery used in place of a table name */
   69716   Expr *pOn,              /* The ON clause of a join */
   69717   IdList *pUsing          /* The USING clause of a join */
   69718 ){
   69719   struct SrcList_item *pItem;
   69720   sqlite3 *db = pParse->db;
   69721   if( !p && (pOn || pUsing) ){
   69722     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
   69723       (pOn ? "ON" : "USING")
   69724     );
   69725     goto append_from_error;
   69726   }
   69727   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
   69728   if( p==0 || NEVER(p->nSrc==0) ){
   69729     goto append_from_error;
   69730   }
   69731   pItem = &p->a[p->nSrc-1];
   69732   assert( pAlias!=0 );
   69733   if( pAlias->n ){
   69734     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
   69735   }
   69736   pItem->pSelect = pSubquery;
   69737   pItem->pOn = pOn;
   69738   pItem->pUsing = pUsing;
   69739   return p;
   69740 
   69741  append_from_error:
   69742   assert( p==0 );
   69743   sqlite3ExprDelete(db, pOn);
   69744   sqlite3IdListDelete(db, pUsing);
   69745   sqlite3SelectDelete(db, pSubquery);
   69746   return 0;
   69747 }
   69748 
   69749 /*
   69750 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
   69751 ** element of the source-list passed as the second argument.
   69752 */
   69753 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
   69754   assert( pIndexedBy!=0 );
   69755   if( p && ALWAYS(p->nSrc>0) ){
   69756     struct SrcList_item *pItem = &p->a[p->nSrc-1];
   69757     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
   69758     if( pIndexedBy->n==1 && !pIndexedBy->z ){
   69759       /* A "NOT INDEXED" clause was supplied. See parse.y
   69760       ** construct "indexed_opt" for details. */
   69761       pItem->notIndexed = 1;
   69762     }else{
   69763       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
   69764     }
   69765   }
   69766 }
   69767 
   69768 /*
   69769 ** When building up a FROM clause in the parser, the join operator
   69770 ** is initially attached to the left operand.  But the code generator
   69771 ** expects the join operator to be on the right operand.  This routine
   69772 ** Shifts all join operators from left to right for an entire FROM
   69773 ** clause.
   69774 **
   69775 ** Example: Suppose the join is like this:
   69776 **
   69777 **           A natural cross join B
   69778 **
   69779 ** The operator is "natural cross join".  The A and B operands are stored
   69780 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
   69781 ** operator with A.  This routine shifts that operator over to B.
   69782 */
   69783 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
   69784   if( p && p->a ){
   69785     int i;
   69786     for(i=p->nSrc-1; i>0; i--){
   69787       p->a[i].jointype = p->a[i-1].jointype;
   69788     }
   69789     p->a[0].jointype = 0;
   69790   }
   69791 }
   69792 
   69793 /*
   69794 ** Begin a transaction
   69795 */
   69796 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
   69797   sqlite3 *db;
   69798   Vdbe *v;
   69799   int i;
   69800 
   69801   assert( pParse!=0 );
   69802   db = pParse->db;
   69803   assert( db!=0 );
   69804 /*  if( db->aDb[0].pBt==0 ) return; */
   69805   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
   69806     return;
   69807   }
   69808   v = sqlite3GetVdbe(pParse);
   69809   if( !v ) return;
   69810   if( type!=TK_DEFERRED ){
   69811     for(i=0; i<db->nDb; i++){
   69812       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
   69813       sqlite3VdbeUsesBtree(v, i);
   69814     }
   69815   }
   69816   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
   69817 }
   69818 
   69819 /*
   69820 ** Commit a transaction
   69821 */
   69822 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
   69823   sqlite3 *db;
   69824   Vdbe *v;
   69825 
   69826   assert( pParse!=0 );
   69827   db = pParse->db;
   69828   assert( db!=0 );
   69829 /*  if( db->aDb[0].pBt==0 ) return; */
   69830   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
   69831     return;
   69832   }
   69833   v = sqlite3GetVdbe(pParse);
   69834   if( v ){
   69835     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
   69836   }
   69837 }
   69838 
   69839 /*
   69840 ** Rollback a transaction
   69841 */
   69842 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
   69843   sqlite3 *db;
   69844   Vdbe *v;
   69845 
   69846   assert( pParse!=0 );
   69847   db = pParse->db;
   69848   assert( db!=0 );
   69849 /*  if( db->aDb[0].pBt==0 ) return; */
   69850   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
   69851     return;
   69852   }
   69853   v = sqlite3GetVdbe(pParse);
   69854   if( v ){
   69855     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
   69856   }
   69857 }
   69858 
   69859 /*
   69860 ** This function is called by the parser when it parses a command to create,
   69861 ** release or rollback an SQL savepoint.
   69862 */
   69863 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
   69864   char *zName = sqlite3NameFromToken(pParse->db, pName);
   69865   if( zName ){
   69866     Vdbe *v = sqlite3GetVdbe(pParse);
   69867 #ifndef SQLITE_OMIT_AUTHORIZATION
   69868     static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
   69869     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
   69870 #endif
   69871     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
   69872       sqlite3DbFree(pParse->db, zName);
   69873       return;
   69874     }
   69875     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
   69876   }
   69877 }
   69878 
   69879 /*
   69880 ** Make sure the TEMP database is open and available for use.  Return
   69881 ** the number of errors.  Leave any error messages in the pParse structure.
   69882 */
   69883 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
   69884   sqlite3 *db = pParse->db;
   69885   if( db->aDb[1].pBt==0 && !pParse->explain ){
   69886     int rc;
   69887     static const int flags =
   69888           SQLITE_OPEN_READWRITE |
   69889           SQLITE_OPEN_CREATE |
   69890           SQLITE_OPEN_EXCLUSIVE |
   69891           SQLITE_OPEN_DELETEONCLOSE |
   69892           SQLITE_OPEN_TEMP_DB;
   69893 
   69894     rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
   69895                                  &db->aDb[1].pBt);
   69896     if( rc!=SQLITE_OK ){
   69897       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
   69898         "file for storing temporary tables");
   69899       pParse->rc = rc;
   69900       return 1;
   69901     }
   69902     assert( db->aDb[1].pSchema );
   69903     sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
   69904                             db->dfltJournalMode);
   69905   }
   69906   return 0;
   69907 }
   69908 
   69909 /*
   69910 ** Generate VDBE code that will verify the schema cookie and start
   69911 ** a read-transaction for all named database files.
   69912 **
   69913 ** It is important that all schema cookies be verified and all
   69914 ** read transactions be started before anything else happens in
   69915 ** the VDBE program.  But this routine can be called after much other
   69916 ** code has been generated.  So here is what we do:
   69917 **
   69918 ** The first time this routine is called, we code an OP_Goto that
   69919 ** will jump to a subroutine at the end of the program.  Then we
   69920 ** record every database that needs its schema verified in the
   69921 ** pParse->cookieMask field.  Later, after all other code has been
   69922 ** generated, the subroutine that does the cookie verifications and
   69923 ** starts the transactions will be coded and the OP_Goto P2 value
   69924 ** will be made to point to that subroutine.  The generation of the
   69925 ** cookie verification subroutine code happens in sqlite3FinishCoding().
   69926 **
   69927 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
   69928 ** schema on any databases.  This can be used to position the OP_Goto
   69929 ** early in the code, before we know if any database tables will be used.
   69930 */
   69931 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
   69932   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   69933 
   69934   if( pToplevel->cookieGoto==0 ){
   69935     Vdbe *v = sqlite3GetVdbe(pToplevel);
   69936     if( v==0 ) return;  /* This only happens if there was a prior error */
   69937     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
   69938   }
   69939   if( iDb>=0 ){
   69940     sqlite3 *db = pToplevel->db;
   69941     int mask;
   69942 
   69943     assert( iDb<db->nDb );
   69944     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
   69945     assert( iDb<SQLITE_MAX_ATTACHED+2 );
   69946     mask = 1<<iDb;
   69947     if( (pToplevel->cookieMask & mask)==0 ){
   69948       pToplevel->cookieMask |= mask;
   69949       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
   69950       if( !OMIT_TEMPDB && iDb==1 ){
   69951         sqlite3OpenTempDatabase(pToplevel);
   69952       }
   69953     }
   69954   }
   69955 }
   69956 
   69957 /*
   69958 ** Generate VDBE code that prepares for doing an operation that
   69959 ** might change the database.
   69960 **
   69961 ** This routine starts a new transaction if we are not already within
   69962 ** a transaction.  If we are already within a transaction, then a checkpoint
   69963 ** is set if the setStatement parameter is true.  A checkpoint should
   69964 ** be set for operations that might fail (due to a constraint) part of
   69965 ** the way through and which will need to undo some writes without having to
   69966 ** rollback the whole transaction.  For operations where all constraints
   69967 ** can be checked before any changes are made to the database, it is never
   69968 ** necessary to undo a write and the checkpoint should not be set.
   69969 */
   69970 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
   69971   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   69972   sqlite3CodeVerifySchema(pParse, iDb);
   69973   pToplevel->writeMask |= 1<<iDb;
   69974   pToplevel->isMultiWrite |= setStatement;
   69975 }
   69976 
   69977 /*
   69978 ** Indicate that the statement currently under construction might write
   69979 ** more than one entry (example: deleting one row then inserting another,
   69980 ** inserting multiple rows in a table, or inserting a row and index entries.)
   69981 ** If an abort occurs after some of these writes have completed, then it will
   69982 ** be necessary to undo the completed writes.
   69983 */
   69984 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
   69985   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   69986   pToplevel->isMultiWrite = 1;
   69987 }
   69988 
   69989 /*
   69990 ** The code generator calls this routine if is discovers that it is
   69991 ** possible to abort a statement prior to completion.  In order to
   69992 ** perform this abort without corrupting the database, we need to make
   69993 ** sure that the statement is protected by a statement transaction.
   69994 **
   69995 ** Technically, we only need to set the mayAbort flag if the
   69996 ** isMultiWrite flag was previously set.  There is a time dependency
   69997 ** such that the abort must occur after the multiwrite.  This makes
   69998 ** some statements involving the REPLACE conflict resolution algorithm
   69999 ** go a little faster.  But taking advantage of this time dependency
   70000 ** makes it more difficult to prove that the code is correct (in
   70001 ** particular, it prevents us from writing an effective
   70002 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
   70003 ** to take the safe route and skip the optimization.
   70004 */
   70005 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
   70006   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   70007   pToplevel->mayAbort = 1;
   70008 }
   70009 
   70010 /*
   70011 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
   70012 ** error. The onError parameter determines which (if any) of the statement
   70013 ** and/or current transaction is rolled back.
   70014 */
   70015 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
   70016   Vdbe *v = sqlite3GetVdbe(pParse);
   70017   if( onError==OE_Abort ){
   70018     sqlite3MayAbort(pParse);
   70019   }
   70020   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
   70021 }
   70022 
   70023 /*
   70024 ** Check to see if pIndex uses the collating sequence pColl.  Return
   70025 ** true if it does and false if it does not.
   70026 */
   70027 #ifndef SQLITE_OMIT_REINDEX
   70028 static int collationMatch(const char *zColl, Index *pIndex){
   70029   int i;
   70030   assert( zColl!=0 );
   70031   for(i=0; i<pIndex->nColumn; i++){
   70032     const char *z = pIndex->azColl[i];
   70033     assert( z!=0 );
   70034     if( 0==sqlite3StrICmp(z, zColl) ){
   70035       return 1;
   70036     }
   70037   }
   70038   return 0;
   70039 }
   70040 #endif
   70041 
   70042 /*
   70043 ** Recompute all indices of pTab that use the collating sequence pColl.
   70044 ** If pColl==0 then recompute all indices of pTab.
   70045 */
   70046 #ifndef SQLITE_OMIT_REINDEX
   70047 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
   70048   Index *pIndex;              /* An index associated with pTab */
   70049 
   70050   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
   70051     if( zColl==0 || collationMatch(zColl, pIndex) ){
   70052       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   70053       sqlite3BeginWriteOperation(pParse, 0, iDb);
   70054       sqlite3RefillIndex(pParse, pIndex, -1);
   70055     }
   70056   }
   70057 }
   70058 #endif
   70059 
   70060 /*
   70061 ** Recompute all indices of all tables in all databases where the
   70062 ** indices use the collating sequence pColl.  If pColl==0 then recompute
   70063 ** all indices everywhere.
   70064 */
   70065 #ifndef SQLITE_OMIT_REINDEX
   70066 static void reindexDatabases(Parse *pParse, char const *zColl){
   70067   Db *pDb;                    /* A single database */
   70068   int iDb;                    /* The database index number */
   70069   sqlite3 *db = pParse->db;   /* The database connection */
   70070   HashElem *k;                /* For looping over tables in pDb */
   70071   Table *pTab;                /* A table in the database */
   70072 
   70073   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
   70074     assert( pDb!=0 );
   70075     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
   70076       pTab = (Table*)sqliteHashData(k);
   70077       reindexTable(pParse, pTab, zColl);
   70078     }
   70079   }
   70080 }
   70081 #endif
   70082 
   70083 /*
   70084 ** Generate code for the REINDEX command.
   70085 **
   70086 **        REINDEX                            -- 1
   70087 **        REINDEX  <collation>               -- 2
   70088 **        REINDEX  ?<database>.?<tablename>  -- 3
   70089 **        REINDEX  ?<database>.?<indexname>  -- 4
   70090 **
   70091 ** Form 1 causes all indices in all attached databases to be rebuilt.
   70092 ** Form 2 rebuilds all indices in all databases that use the named
   70093 ** collating function.  Forms 3 and 4 rebuild the named index or all
   70094 ** indices associated with the named table.
   70095 */
   70096 #ifndef SQLITE_OMIT_REINDEX
   70097 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
   70098   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
   70099   char *z;                    /* Name of a table or index */
   70100   const char *zDb;            /* Name of the database */
   70101   Table *pTab;                /* A table in the database */
   70102   Index *pIndex;              /* An index associated with pTab */
   70103   int iDb;                    /* The database index number */
   70104   sqlite3 *db = pParse->db;   /* The database connection */
   70105   Token *pObjName;            /* Name of the table or index to be reindexed */
   70106 
   70107   /* Read the database schema. If an error occurs, leave an error message
   70108   ** and code in pParse and return NULL. */
   70109   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   70110     return;
   70111   }
   70112 
   70113   if( pName1==0 ){
   70114     reindexDatabases(pParse, 0);
   70115     return;
   70116   }else if( NEVER(pName2==0) || pName2->z==0 ){
   70117     char *zColl;
   70118     assert( pName1->z );
   70119     zColl = sqlite3NameFromToken(pParse->db, pName1);
   70120     if( !zColl ) return;
   70121     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
   70122     if( pColl ){
   70123       reindexDatabases(pParse, zColl);
   70124       sqlite3DbFree(db, zColl);
   70125       return;
   70126     }
   70127     sqlite3DbFree(db, zColl);
   70128   }
   70129   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
   70130   if( iDb<0 ) return;
   70131   z = sqlite3NameFromToken(db, pObjName);
   70132   if( z==0 ) return;
   70133   zDb = db->aDb[iDb].zName;
   70134   pTab = sqlite3FindTable(db, z, zDb);
   70135   if( pTab ){
   70136     reindexTable(pParse, pTab, 0);
   70137     sqlite3DbFree(db, z);
   70138     return;
   70139   }
   70140   pIndex = sqlite3FindIndex(db, z, zDb);
   70141   sqlite3DbFree(db, z);
   70142   if( pIndex ){
   70143     sqlite3BeginWriteOperation(pParse, 0, iDb);
   70144     sqlite3RefillIndex(pParse, pIndex, -1);
   70145     return;
   70146   }
   70147   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
   70148 }
   70149 #endif
   70150 
   70151 /*
   70152 ** Return a dynamicly allocated KeyInfo structure that can be used
   70153 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
   70154 **
   70155 ** If successful, a pointer to the new structure is returned. In this case
   70156 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
   70157 ** pointer. If an error occurs (out of memory or missing collation
   70158 ** sequence), NULL is returned and the state of pParse updated to reflect
   70159 ** the error.
   70160 */
   70161 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
   70162   int i;
   70163   int nCol = pIdx->nColumn;
   70164   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
   70165   sqlite3 *db = pParse->db;
   70166   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
   70167 
   70168   if( pKey ){
   70169     pKey->db = pParse->db;
   70170     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
   70171     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
   70172     for(i=0; i<nCol; i++){
   70173       char *zColl = pIdx->azColl[i];
   70174       assert( zColl );
   70175       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
   70176       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
   70177     }
   70178     pKey->nField = (u16)nCol;
   70179   }
   70180 
   70181   if( pParse->nErr ){
   70182     sqlite3DbFree(db, pKey);
   70183     pKey = 0;
   70184   }
   70185   return pKey;
   70186 }
   70187 
   70188 /************** End of build.c ***********************************************/
   70189 /************** Begin file callback.c ****************************************/
   70190 /*
   70191 ** 2005 May 23
   70192 **
   70193 ** The author disclaims copyright to this source code.  In place of
   70194 ** a legal notice, here is a blessing:
   70195 **
   70196 **    May you do good and not evil.
   70197 **    May you find forgiveness for yourself and forgive others.
   70198 **    May you share freely, never taking more than you give.
   70199 **
   70200 *************************************************************************
   70201 **
   70202 ** This file contains functions used to access the internal hash tables
   70203 ** of user defined functions and collation sequences.
   70204 */
   70205 
   70206 
   70207 /*
   70208 ** Invoke the 'collation needed' callback to request a collation sequence
   70209 ** in the encoding enc of name zName, length nName.
   70210 */
   70211 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
   70212   assert( !db->xCollNeeded || !db->xCollNeeded16 );
   70213   if( db->xCollNeeded ){
   70214     char *zExternal = sqlite3DbStrDup(db, zName);
   70215     if( !zExternal ) return;
   70216     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
   70217     sqlite3DbFree(db, zExternal);
   70218   }
   70219 #ifndef SQLITE_OMIT_UTF16
   70220   if( db->xCollNeeded16 ){
   70221     char const *zExternal;
   70222     sqlite3_value *pTmp = sqlite3ValueNew(db);
   70223     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
   70224     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
   70225     if( zExternal ){
   70226       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
   70227     }
   70228     sqlite3ValueFree(pTmp);
   70229   }
   70230 #endif
   70231 }
   70232 
   70233 /*
   70234 ** This routine is called if the collation factory fails to deliver a
   70235 ** collation function in the best encoding but there may be other versions
   70236 ** of this collation function (for other text encodings) available. Use one
   70237 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
   70238 ** possible.
   70239 */
   70240 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
   70241   CollSeq *pColl2;
   70242   char *z = pColl->zName;
   70243   int i;
   70244   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
   70245   for(i=0; i<3; i++){
   70246     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
   70247     if( pColl2->xCmp!=0 ){
   70248       memcpy(pColl, pColl2, sizeof(CollSeq));
   70249       pColl->xDel = 0;         /* Do not copy the destructor */
   70250       return SQLITE_OK;
   70251     }
   70252   }
   70253   return SQLITE_ERROR;
   70254 }
   70255 
   70256 /*
   70257 ** This function is responsible for invoking the collation factory callback
   70258 ** or substituting a collation sequence of a different encoding when the
   70259 ** requested collation sequence is not available in the desired encoding.
   70260 **
   70261 ** If it is not NULL, then pColl must point to the database native encoding
   70262 ** collation sequence with name zName, length nName.
   70263 **
   70264 ** The return value is either the collation sequence to be used in database
   70265 ** db for collation type name zName, length nName, or NULL, if no collation
   70266 ** sequence can be found.
   70267 **
   70268 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
   70269 */
   70270 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
   70271   sqlite3* db,          /* The database connection */
   70272   u8 enc,               /* The desired encoding for the collating sequence */
   70273   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
   70274   const char *zName     /* Collating sequence name */
   70275 ){
   70276   CollSeq *p;
   70277 
   70278   p = pColl;
   70279   if( !p ){
   70280     p = sqlite3FindCollSeq(db, enc, zName, 0);
   70281   }
   70282   if( !p || !p->xCmp ){
   70283     /* No collation sequence of this type for this encoding is registered.
   70284     ** Call the collation factory to see if it can supply us with one.
   70285     */
   70286     callCollNeeded(db, enc, zName);
   70287     p = sqlite3FindCollSeq(db, enc, zName, 0);
   70288   }
   70289   if( p && !p->xCmp && synthCollSeq(db, p) ){
   70290     p = 0;
   70291   }
   70292   assert( !p || p->xCmp );
   70293   return p;
   70294 }
   70295 
   70296 /*
   70297 ** This routine is called on a collation sequence before it is used to
   70298 ** check that it is defined. An undefined collation sequence exists when
   70299 ** a database is loaded that contains references to collation sequences
   70300 ** that have not been defined by sqlite3_create_collation() etc.
   70301 **
   70302 ** If required, this routine calls the 'collation needed' callback to
   70303 ** request a definition of the collating sequence. If this doesn't work,
   70304 ** an equivalent collating sequence that uses a text encoding different
   70305 ** from the main database is substituted, if one is available.
   70306 */
   70307 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
   70308   if( pColl ){
   70309     const char *zName = pColl->zName;
   70310     sqlite3 *db = pParse->db;
   70311     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
   70312     if( !p ){
   70313       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
   70314       pParse->nErr++;
   70315       return SQLITE_ERROR;
   70316     }
   70317     assert( p==pColl );
   70318   }
   70319   return SQLITE_OK;
   70320 }
   70321 
   70322 
   70323 
   70324 /*
   70325 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
   70326 ** specified by zName and nName is not found and parameter 'create' is
   70327 ** true, then create a new entry. Otherwise return NULL.
   70328 **
   70329 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
   70330 ** array of three CollSeq structures. The first is the collation sequence
   70331 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
   70332 **
   70333 ** Stored immediately after the three collation sequences is a copy of
   70334 ** the collation sequence name. A pointer to this string is stored in
   70335 ** each collation sequence structure.
   70336 */
   70337 static CollSeq *findCollSeqEntry(
   70338   sqlite3 *db,          /* Database connection */
   70339   const char *zName,    /* Name of the collating sequence */
   70340   int create            /* Create a new entry if true */
   70341 ){
   70342   CollSeq *pColl;
   70343   int nName = sqlite3Strlen30(zName);
   70344   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
   70345 
   70346   if( 0==pColl && create ){
   70347     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
   70348     if( pColl ){
   70349       CollSeq *pDel = 0;
   70350       pColl[0].zName = (char*)&pColl[3];
   70351       pColl[0].enc = SQLITE_UTF8;
   70352       pColl[1].zName = (char*)&pColl[3];
   70353       pColl[1].enc = SQLITE_UTF16LE;
   70354       pColl[2].zName = (char*)&pColl[3];
   70355       pColl[2].enc = SQLITE_UTF16BE;
   70356       memcpy(pColl[0].zName, zName, nName);
   70357       pColl[0].zName[nName] = 0;
   70358       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
   70359 
   70360       /* If a malloc() failure occurred in sqlite3HashInsert(), it will
   70361       ** return the pColl pointer to be deleted (because it wasn't added
   70362       ** to the hash table).
   70363       */
   70364       assert( pDel==0 || pDel==pColl );
   70365       if( pDel!=0 ){
   70366         db->mallocFailed = 1;
   70367         sqlite3DbFree(db, pDel);
   70368         pColl = 0;
   70369       }
   70370     }
   70371   }
   70372   return pColl;
   70373 }
   70374 
   70375 /*
   70376 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
   70377 ** Return the CollSeq* pointer for the collation sequence named zName
   70378 ** for the encoding 'enc' from the database 'db'.
   70379 **
   70380 ** If the entry specified is not found and 'create' is true, then create a
   70381 ** new entry.  Otherwise return NULL.
   70382 **
   70383 ** A separate function sqlite3LocateCollSeq() is a wrapper around
   70384 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
   70385 ** if necessary and generates an error message if the collating sequence
   70386 ** cannot be found.
   70387 **
   70388 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
   70389 */
   70390 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
   70391   sqlite3 *db,
   70392   u8 enc,
   70393   const char *zName,
   70394   int create
   70395 ){
   70396   CollSeq *pColl;
   70397   if( zName ){
   70398     pColl = findCollSeqEntry(db, zName, create);
   70399   }else{
   70400     pColl = db->pDfltColl;
   70401   }
   70402   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
   70403   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
   70404   if( pColl ) pColl += enc-1;
   70405   return pColl;
   70406 }
   70407 
   70408 /* During the search for the best function definition, this procedure
   70409 ** is called to test how well the function passed as the first argument
   70410 ** matches the request for a function with nArg arguments in a system
   70411 ** that uses encoding enc. The value returned indicates how well the
   70412 ** request is matched. A higher value indicates a better match.
   70413 **
   70414 ** The returned value is always between 0 and 6, as follows:
   70415 **
   70416 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
   70417 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
   70418 **    encoding is requested, or vice versa.
   70419 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
   70420 **    requested, or vice versa.
   70421 ** 3: A variable arguments function using the same text encoding.
   70422 ** 4: A function with the exact number of arguments requested that
   70423 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
   70424 ** 5: A function with the exact number of arguments requested that
   70425 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
   70426 ** 6: An exact match.
   70427 **
   70428 */
   70429 static int matchQuality(FuncDef *p, int nArg, u8 enc){
   70430   int match = 0;
   70431   if( p->nArg==-1 || p->nArg==nArg
   70432    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
   70433   ){
   70434     match = 1;
   70435     if( p->nArg==nArg || nArg==-1 ){
   70436       match = 4;
   70437     }
   70438     if( enc==p->iPrefEnc ){
   70439       match += 2;
   70440     }
   70441     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
   70442              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
   70443       match += 1;
   70444     }
   70445   }
   70446   return match;
   70447 }
   70448 
   70449 /*
   70450 ** Search a FuncDefHash for a function with the given name.  Return
   70451 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
   70452 */
   70453 static FuncDef *functionSearch(
   70454   FuncDefHash *pHash,  /* Hash table to search */
   70455   int h,               /* Hash of the name */
   70456   const char *zFunc,   /* Name of function */
   70457   int nFunc            /* Number of bytes in zFunc */
   70458 ){
   70459   FuncDef *p;
   70460   for(p=pHash->a[h]; p; p=p->pHash){
   70461     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
   70462       return p;
   70463     }
   70464   }
   70465   return 0;
   70466 }
   70467 
   70468 /*
   70469 ** Insert a new FuncDef into a FuncDefHash hash table.
   70470 */
   70471 SQLITE_PRIVATE void sqlite3FuncDefInsert(
   70472   FuncDefHash *pHash,  /* The hash table into which to insert */
   70473   FuncDef *pDef        /* The function definition to insert */
   70474 ){
   70475   FuncDef *pOther;
   70476   int nName = sqlite3Strlen30(pDef->zName);
   70477   u8 c1 = (u8)pDef->zName[0];
   70478   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
   70479   pOther = functionSearch(pHash, h, pDef->zName, nName);
   70480   if( pOther ){
   70481     assert( pOther!=pDef && pOther->pNext!=pDef );
   70482     pDef->pNext = pOther->pNext;
   70483     pOther->pNext = pDef;
   70484   }else{
   70485     pDef->pNext = 0;
   70486     pDef->pHash = pHash->a[h];
   70487     pHash->a[h] = pDef;
   70488   }
   70489 }
   70490 
   70491 
   70492 
   70493 /*
   70494 ** Locate a user function given a name, a number of arguments and a flag
   70495 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
   70496 ** pointer to the FuncDef structure that defines that function, or return
   70497 ** NULL if the function does not exist.
   70498 **
   70499 ** If the createFlag argument is true, then a new (blank) FuncDef
   70500 ** structure is created and liked into the "db" structure if a
   70501 ** no matching function previously existed.  When createFlag is true
   70502 ** and the nArg parameter is -1, then only a function that accepts
   70503 ** any number of arguments will be returned.
   70504 **
   70505 ** If createFlag is false and nArg is -1, then the first valid
   70506 ** function found is returned.  A function is valid if either xFunc
   70507 ** or xStep is non-zero.
   70508 **
   70509 ** If createFlag is false, then a function with the required name and
   70510 ** number of arguments may be returned even if the eTextRep flag does not
   70511 ** match that requested.
   70512 */
   70513 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
   70514   sqlite3 *db,       /* An open database */
   70515   const char *zName, /* Name of the function.  Not null-terminated */
   70516   int nName,         /* Number of characters in the name */
   70517   int nArg,          /* Number of arguments.  -1 means any number */
   70518   u8 enc,            /* Preferred text encoding */
   70519   int createFlag     /* Create new entry if true and does not otherwise exist */
   70520 ){
   70521   FuncDef *p;         /* Iterator variable */
   70522   FuncDef *pBest = 0; /* Best match found so far */
   70523   int bestScore = 0;  /* Score of best match */
   70524   int h;              /* Hash value */
   70525 
   70526 
   70527   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
   70528   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
   70529 
   70530   /* First search for a match amongst the application-defined functions.
   70531   */
   70532   p = functionSearch(&db->aFunc, h, zName, nName);
   70533   while( p ){
   70534     int score = matchQuality(p, nArg, enc);
   70535     if( score>bestScore ){
   70536       pBest = p;
   70537       bestScore = score;
   70538     }
   70539     p = p->pNext;
   70540   }
   70541 
   70542   /* If no match is found, search the built-in functions.
   70543   **
   70544   ** Except, if createFlag is true, that means that we are trying to
   70545   ** install a new function.  Whatever FuncDef structure is returned will
   70546   ** have fields overwritten with new information appropriate for the
   70547   ** new function.  But the FuncDefs for built-in functions are read-only.
   70548   ** So we must not search for built-ins when creating a new function.
   70549   */
   70550   if( !createFlag && !pBest ){
   70551     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   70552     p = functionSearch(pHash, h, zName, nName);
   70553     while( p ){
   70554       int score = matchQuality(p, nArg, enc);
   70555       if( score>bestScore ){
   70556         pBest = p;
   70557         bestScore = score;
   70558       }
   70559       p = p->pNext;
   70560     }
   70561   }
   70562 
   70563   /* If the createFlag parameter is true and the search did not reveal an
   70564   ** exact match for the name, number of arguments and encoding, then add a
   70565   ** new entry to the hash table and return it.
   70566   */
   70567   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
   70568       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
   70569     pBest->zName = (char *)&pBest[1];
   70570     pBest->nArg = (u16)nArg;
   70571     pBest->iPrefEnc = enc;
   70572     memcpy(pBest->zName, zName, nName);
   70573     pBest->zName[nName] = 0;
   70574     sqlite3FuncDefInsert(&db->aFunc, pBest);
   70575   }
   70576 
   70577   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
   70578     return pBest;
   70579   }
   70580   return 0;
   70581 }
   70582 
   70583 /*
   70584 ** Free all resources held by the schema structure. The void* argument points
   70585 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
   70586 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
   70587 ** of the schema hash tables).
   70588 **
   70589 ** The Schema.cache_size variable is not cleared.
   70590 */
   70591 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
   70592   Hash temp1;
   70593   Hash temp2;
   70594   HashElem *pElem;
   70595   Schema *pSchema = (Schema *)p;
   70596 
   70597   temp1 = pSchema->tblHash;
   70598   temp2 = pSchema->trigHash;
   70599   sqlite3HashInit(&pSchema->trigHash);
   70600   sqlite3HashClear(&pSchema->idxHash);
   70601   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
   70602     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
   70603   }
   70604   sqlite3HashClear(&temp2);
   70605   sqlite3HashInit(&pSchema->tblHash);
   70606   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
   70607     Table *pTab = sqliteHashData(pElem);
   70608     assert( pTab->dbMem==0 );
   70609     sqlite3DeleteTable(pTab);
   70610   }
   70611   sqlite3HashClear(&temp1);
   70612   sqlite3HashClear(&pSchema->fkeyHash);
   70613   pSchema->pSeqTab = 0;
   70614   pSchema->flags &= ~DB_SchemaLoaded;
   70615 }
   70616 
   70617 /*
   70618 ** Find and return the schema associated with a BTree.  Create
   70619 ** a new one if necessary.
   70620 */
   70621 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
   70622   Schema * p;
   70623   if( pBt ){
   70624     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
   70625   }else{
   70626     p = (Schema *)sqlite3MallocZero(sizeof(Schema));
   70627   }
   70628   if( !p ){
   70629     db->mallocFailed = 1;
   70630   }else if ( 0==p->file_format ){
   70631     sqlite3HashInit(&p->tblHash);
   70632     sqlite3HashInit(&p->idxHash);
   70633     sqlite3HashInit(&p->trigHash);
   70634     sqlite3HashInit(&p->fkeyHash);
   70635     p->enc = SQLITE_UTF8;
   70636   }
   70637   return p;
   70638 }
   70639 
   70640 /************** End of callback.c ********************************************/
   70641 /************** Begin file delete.c ******************************************/
   70642 /*
   70643 ** 2001 September 15
   70644 **
   70645 ** The author disclaims copyright to this source code.  In place of
   70646 ** a legal notice, here is a blessing:
   70647 **
   70648 **    May you do good and not evil.
   70649 **    May you find forgiveness for yourself and forgive others.
   70650 **    May you share freely, never taking more than you give.
   70651 **
   70652 *************************************************************************
   70653 ** This file contains C code routines that are called by the parser
   70654 ** in order to generate code for DELETE FROM statements.
   70655 */
   70656 
   70657 /*
   70658 ** Look up every table that is named in pSrc.  If any table is not found,
   70659 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
   70660 ** are found, return a pointer to the last table.
   70661 */
   70662 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
   70663   struct SrcList_item *pItem = pSrc->a;
   70664   Table *pTab;
   70665   assert( pItem && pSrc->nSrc==1 );
   70666   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
   70667   sqlite3DeleteTable(pItem->pTab);
   70668   pItem->pTab = pTab;
   70669   if( pTab ){
   70670     pTab->nRef++;
   70671   }
   70672   if( sqlite3IndexedByLookup(pParse, pItem) ){
   70673     pTab = 0;
   70674   }
   70675   return pTab;
   70676 }
   70677 
   70678 /*
   70679 ** Check to make sure the given table is writable.  If it is not
   70680 ** writable, generate an error message and return 1.  If it is
   70681 ** writable return 0;
   70682 */
   70683 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
   70684   /* A table is not writable under the following circumstances:
   70685   **
   70686   **   1) It is a virtual table and no implementation of the xUpdate method
   70687   **      has been provided, or
   70688   **   2) It is a system table (i.e. sqlite_master), this call is not
   70689   **      part of a nested parse and writable_schema pragma has not
   70690   **      been specified.
   70691   **
   70692   ** In either case leave an error message in pParse and return non-zero.
   70693   */
   70694   if( ( IsVirtual(pTab)
   70695      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
   70696    || ( (pTab->tabFlags & TF_Readonly)!=0
   70697      && (pParse->db->flags & SQLITE_WriteSchema)==0
   70698      && pParse->nested==0 )
   70699   ){
   70700     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
   70701     return 1;
   70702   }
   70703 
   70704 #ifndef SQLITE_OMIT_VIEW
   70705   if( !viewOk && pTab->pSelect ){
   70706     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
   70707     return 1;
   70708   }
   70709 #endif
   70710   return 0;
   70711 }
   70712 
   70713 
   70714 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   70715 /*
   70716 ** Evaluate a view and store its result in an ephemeral table.  The
   70717 ** pWhere argument is an optional WHERE clause that restricts the
   70718 ** set of rows in the view that are to be added to the ephemeral table.
   70719 */
   70720 SQLITE_PRIVATE void sqlite3MaterializeView(
   70721   Parse *pParse,       /* Parsing context */
   70722   Table *pView,        /* View definition */
   70723   Expr *pWhere,        /* Optional WHERE clause to be added */
   70724   int iCur             /* Cursor number for ephemerial table */
   70725 ){
   70726   SelectDest dest;
   70727   Select *pDup;
   70728   sqlite3 *db = pParse->db;
   70729 
   70730   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
   70731   if( pWhere ){
   70732     SrcList *pFrom;
   70733 
   70734     pWhere = sqlite3ExprDup(db, pWhere, 0);
   70735     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
   70736     if( pFrom ){
   70737       assert( pFrom->nSrc==1 );
   70738       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
   70739       pFrom->a[0].pSelect = pDup;
   70740       assert( pFrom->a[0].pOn==0 );
   70741       assert( pFrom->a[0].pUsing==0 );
   70742     }else{
   70743       sqlite3SelectDelete(db, pDup);
   70744     }
   70745     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
   70746   }
   70747   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
   70748   sqlite3Select(pParse, pDup, &dest);
   70749   sqlite3SelectDelete(db, pDup);
   70750 }
   70751 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
   70752 
   70753 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   70754 /*
   70755 ** Generate an expression tree to implement the WHERE, ORDER BY,
   70756 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
   70757 **
   70758 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
   70759 **                            \__________________________/
   70760 **                               pLimitWhere (pInClause)
   70761 */
   70762 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
   70763   Parse *pParse,               /* The parser context */
   70764   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
   70765   Expr *pWhere,                /* The WHERE clause.  May be null */
   70766   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
   70767   Expr *pLimit,                /* The LIMIT clause.  May be null */
   70768   Expr *pOffset,               /* The OFFSET clause.  May be null */
   70769   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
   70770 ){
   70771   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
   70772   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
   70773   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
   70774   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
   70775   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
   70776   Select *pSelect = NULL;      /* Complete SELECT tree */
   70777 
   70778   /* Check that there isn't an ORDER BY without a LIMIT clause.
   70779   */
   70780   if( pOrderBy && (pLimit == 0) ) {
   70781     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
   70782     pParse->parseError = 1;
   70783     goto limit_where_cleanup_2;
   70784   }
   70785 
   70786   /* We only need to generate a select expression if there
   70787   ** is a limit/offset term to enforce.
   70788   */
   70789   if( pLimit == 0 ) {
   70790     /* if pLimit is null, pOffset will always be null as well. */
   70791     assert( pOffset == 0 );
   70792     return pWhere;
   70793   }
   70794 
   70795   /* Generate a select expression tree to enforce the limit/offset
   70796   ** term for the DELETE or UPDATE statement.  For example:
   70797   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
   70798   ** becomes:
   70799   **   DELETE FROM table_a WHERE rowid IN (
   70800   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
   70801   **   );
   70802   */
   70803 
   70804   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
   70805   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
   70806   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
   70807   if( pEList == 0 ) goto limit_where_cleanup_2;
   70808 
   70809   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
   70810   ** and the SELECT subtree. */
   70811   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
   70812   if( pSelectSrc == 0 ) {
   70813     sqlite3ExprListDelete(pParse->db, pEList);
   70814     goto limit_where_cleanup_2;
   70815   }
   70816 
   70817   /* generate the SELECT expression tree. */
   70818   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
   70819                              pOrderBy,0,pLimit,pOffset);
   70820   if( pSelect == 0 ) return 0;
   70821 
   70822   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
   70823   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
   70824   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
   70825   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
   70826   if( pInClause == 0 ) goto limit_where_cleanup_1;
   70827 
   70828   pInClause->x.pSelect = pSelect;
   70829   pInClause->flags |= EP_xIsSelect;
   70830   sqlite3ExprSetHeight(pParse, pInClause);
   70831   return pInClause;
   70832 
   70833   /* something went wrong. clean up anything allocated. */
   70834 limit_where_cleanup_1:
   70835   sqlite3SelectDelete(pParse->db, pSelect);
   70836   return 0;
   70837 
   70838 limit_where_cleanup_2:
   70839   sqlite3ExprDelete(pParse->db, pWhere);
   70840   sqlite3ExprListDelete(pParse->db, pOrderBy);
   70841   sqlite3ExprDelete(pParse->db, pLimit);
   70842   sqlite3ExprDelete(pParse->db, pOffset);
   70843   return 0;
   70844 }
   70845 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
   70846 
   70847 /*
   70848 ** Generate code for a DELETE FROM statement.
   70849 **
   70850 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
   70851 **                 \________/       \________________/
   70852 **                  pTabList              pWhere
   70853 */
   70854 SQLITE_PRIVATE void sqlite3DeleteFrom(
   70855   Parse *pParse,         /* The parser context */
   70856   SrcList *pTabList,     /* The table from which we should delete things */
   70857   Expr *pWhere           /* The WHERE clause.  May be null */
   70858 ){
   70859   Vdbe *v;               /* The virtual database engine */
   70860   Table *pTab;           /* The table from which records will be deleted */
   70861   const char *zDb;       /* Name of database holding pTab */
   70862   int end, addr = 0;     /* A couple addresses of generated code */
   70863   int i;                 /* Loop counter */
   70864   WhereInfo *pWInfo;     /* Information about the WHERE clause */
   70865   Index *pIdx;           /* For looping over indices of the table */
   70866   int iCur;              /* VDBE Cursor number for pTab */
   70867   sqlite3 *db;           /* Main database structure */
   70868   AuthContext sContext;  /* Authorization context */
   70869   NameContext sNC;       /* Name context to resolve expressions in */
   70870   int iDb;               /* Database number */
   70871   int memCnt = -1;       /* Memory cell used for change counting */
   70872   int rcauth;            /* Value returned by authorization callback */
   70873 
   70874 #ifndef SQLITE_OMIT_TRIGGER
   70875   int isView;                  /* True if attempting to delete from a view */
   70876   Trigger *pTrigger;           /* List of table triggers, if required */
   70877 #endif
   70878 
   70879   memset(&sContext, 0, sizeof(sContext));
   70880   db = pParse->db;
   70881   if( pParse->nErr || db->mallocFailed ){
   70882     goto delete_from_cleanup;
   70883   }
   70884   assert( pTabList->nSrc==1 );
   70885 
   70886   /* Locate the table which we want to delete.  This table has to be
   70887   ** put in an SrcList structure because some of the subroutines we
   70888   ** will be calling are designed to work with multiple tables and expect
   70889   ** an SrcList* parameter instead of just a Table* parameter.
   70890   */
   70891   pTab = sqlite3SrcListLookup(pParse, pTabList);
   70892   if( pTab==0 )  goto delete_from_cleanup;
   70893 
   70894   /* Figure out if we have any triggers and if the table being
   70895   ** deleted from is a view
   70896   */
   70897 #ifndef SQLITE_OMIT_TRIGGER
   70898   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   70899   isView = pTab->pSelect!=0;
   70900 #else
   70901 # define pTrigger 0
   70902 # define isView 0
   70903 #endif
   70904 #ifdef SQLITE_OMIT_VIEW
   70905 # undef isView
   70906 # define isView 0
   70907 #endif
   70908 
   70909   /* If pTab is really a view, make sure it has been initialized.
   70910   */
   70911   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   70912     goto delete_from_cleanup;
   70913   }
   70914 
   70915   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
   70916     goto delete_from_cleanup;
   70917   }
   70918   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   70919   assert( iDb<db->nDb );
   70920   zDb = db->aDb[iDb].zName;
   70921   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
   70922   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
   70923   if( rcauth==SQLITE_DENY ){
   70924     goto delete_from_cleanup;
   70925   }
   70926   assert(!isView || pTrigger);
   70927 
   70928   /* Assign  cursor number to the table and all its indices.
   70929   */
   70930   assert( pTabList->nSrc==1 );
   70931   iCur = pTabList->a[0].iCursor = pParse->nTab++;
   70932   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   70933     pParse->nTab++;
   70934   }
   70935 
   70936   /* Start the view context
   70937   */
   70938   if( isView ){
   70939     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
   70940   }
   70941 
   70942   /* Begin generating code.
   70943   */
   70944   v = sqlite3GetVdbe(pParse);
   70945   if( v==0 ){
   70946     goto delete_from_cleanup;
   70947   }
   70948   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   70949   sqlite3BeginWriteOperation(pParse, 1, iDb);
   70950 
   70951   /* If we are trying to delete from a view, realize that view into
   70952   ** a ephemeral table.
   70953   */
   70954 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   70955   if( isView ){
   70956     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
   70957   }
   70958 #endif
   70959 
   70960   /* Resolve the column names in the WHERE clause.
   70961   */
   70962   memset(&sNC, 0, sizeof(sNC));
   70963   sNC.pParse = pParse;
   70964   sNC.pSrcList = pTabList;
   70965   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
   70966     goto delete_from_cleanup;
   70967   }
   70968 
   70969   /* Initialize the counter of the number of rows deleted, if
   70970   ** we are counting rows.
   70971   */
   70972   if( db->flags & SQLITE_CountRows ){
   70973     memCnt = ++pParse->nMem;
   70974     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
   70975   }
   70976 
   70977 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
   70978   /* Special case: A DELETE without a WHERE clause deletes everything.
   70979   ** It is easier just to erase the whole table. Prior to version 3.6.5,
   70980   ** this optimization caused the row change count (the value returned by
   70981   ** API function sqlite3_count_changes) to be set incorrectly.  */
   70982   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
   70983    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
   70984   ){
   70985     assert( !isView );
   70986     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
   70987                       pTab->zName, P4_STATIC);
   70988     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   70989       assert( pIdx->pSchema==pTab->pSchema );
   70990       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
   70991     }
   70992   }else
   70993 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
   70994   /* The usual case: There is a WHERE clause so we have to scan through
   70995   ** the table and pick which records to delete.
   70996   */
   70997   {
   70998     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
   70999     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
   71000     int regRowid;                   /* Actual register containing rowids */
   71001 
   71002     /* Collect rowids of every row to be deleted.
   71003     */
   71004     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
   71005     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
   71006     if( pWInfo==0 ) goto delete_from_cleanup;
   71007     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
   71008     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
   71009     if( db->flags & SQLITE_CountRows ){
   71010       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
   71011     }
   71012     sqlite3WhereEnd(pWInfo);
   71013 
   71014     /* Delete every item whose key was written to the list during the
   71015     ** database scan.  We have to delete items after the scan is complete
   71016     ** because deleting an item can change the scan order.  */
   71017     end = sqlite3VdbeMakeLabel(v);
   71018 
   71019     /* Unless this is a view, open cursors for the table we are
   71020     ** deleting from and all its indices. If this is a view, then the
   71021     ** only effect this statement has is to fire the INSTEAD OF
   71022     ** triggers.  */
   71023     if( !isView ){
   71024       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
   71025     }
   71026 
   71027     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
   71028 
   71029     /* Delete the row */
   71030 #ifndef SQLITE_OMIT_VIRTUALTABLE
   71031     if( IsVirtual(pTab) ){
   71032       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   71033       sqlite3VtabMakeWritable(pParse, pTab);
   71034       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
   71035       sqlite3MayAbort(pParse);
   71036     }else
   71037 #endif
   71038     {
   71039       int count = (pParse->nested==0);    /* True to count changes */
   71040       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
   71041     }
   71042 
   71043     /* End of the delete loop */
   71044     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
   71045     sqlite3VdbeResolveLabel(v, end);
   71046 
   71047     /* Close the cursors open on the table and its indexes. */
   71048     if( !isView && !IsVirtual(pTab) ){
   71049       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
   71050         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
   71051       }
   71052       sqlite3VdbeAddOp1(v, OP_Close, iCur);
   71053     }
   71054   }
   71055 
   71056   /* Update the sqlite_sequence table by storing the content of the
   71057   ** maximum rowid counter values recorded while inserting into
   71058   ** autoincrement tables.
   71059   */
   71060   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   71061     sqlite3AutoincrementEnd(pParse);
   71062   }
   71063 
   71064   /* Return the number of rows that were deleted. If this routine is
   71065   ** generating code because of a call to sqlite3NestedParse(), do not
   71066   ** invoke the callback function.
   71067   */
   71068   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
   71069     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
   71070     sqlite3VdbeSetNumCols(v, 1);
   71071     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
   71072   }
   71073 
   71074 delete_from_cleanup:
   71075   sqlite3AuthContextPop(&sContext);
   71076   sqlite3SrcListDelete(db, pTabList);
   71077   sqlite3ExprDelete(db, pWhere);
   71078   return;
   71079 }
   71080 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   71081 ** thely may interfere with compilation of other functions in this file
   71082 ** (or in another file, if this file becomes part of the amalgamation).  */
   71083 #ifdef isView
   71084  #undef isView
   71085 #endif
   71086 #ifdef pTrigger
   71087  #undef pTrigger
   71088 #endif
   71089 
   71090 /*
   71091 ** This routine generates VDBE code that causes a single row of a
   71092 ** single table to be deleted.
   71093 **
   71094 ** The VDBE must be in a particular state when this routine is called.
   71095 ** These are the requirements:
   71096 **
   71097 **   1.  A read/write cursor pointing to pTab, the table containing the row
   71098 **       to be deleted, must be opened as cursor number $iCur.
   71099 **
   71100 **   2.  Read/write cursors for all indices of pTab must be open as
   71101 **       cursor number base+i for the i-th index.
   71102 **
   71103 **   3.  The record number of the row to be deleted must be stored in
   71104 **       memory cell iRowid.
   71105 **
   71106 ** This routine generates code to remove both the table record and all
   71107 ** index entries that point to that record.
   71108 */
   71109 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
   71110   Parse *pParse,     /* Parsing context */
   71111   Table *pTab,       /* Table containing the row to be deleted */
   71112   int iCur,          /* Cursor number for the table */
   71113   int iRowid,        /* Memory cell that contains the rowid to delete */
   71114   int count,         /* If non-zero, increment the row change counter */
   71115   Trigger *pTrigger, /* List of triggers to (potentially) fire */
   71116   int onconf         /* Default ON CONFLICT policy for triggers */
   71117 ){
   71118   Vdbe *v = pParse->pVdbe;        /* Vdbe */
   71119   int iOld = 0;                   /* First register in OLD.* array */
   71120   int iLabel;                     /* Label resolved to end of generated code */
   71121 
   71122   /* Vdbe is guaranteed to have been allocated by this stage. */
   71123   assert( v );
   71124 
   71125   /* Seek cursor iCur to the row to delete. If this row no longer exists
   71126   ** (this can happen if a trigger program has already deleted it), do
   71127   ** not attempt to delete it or fire any DELETE triggers.  */
   71128   iLabel = sqlite3VdbeMakeLabel(v);
   71129   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
   71130 
   71131   /* If there are any triggers to fire, allocate a range of registers to
   71132   ** use for the old.* references in the triggers.  */
   71133   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
   71134     u32 mask;                     /* Mask of OLD.* columns in use */
   71135     int iCol;                     /* Iterator used while populating OLD.* */
   71136 
   71137     /* TODO: Could use temporary registers here. Also could attempt to
   71138     ** avoid copying the contents of the rowid register.  */
   71139     mask = sqlite3TriggerColmask(
   71140         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
   71141     );
   71142     mask |= sqlite3FkOldmask(pParse, pTab);
   71143     iOld = pParse->nMem+1;
   71144     pParse->nMem += (1 + pTab->nCol);
   71145 
   71146     /* Populate the OLD.* pseudo-table register array. These values will be
   71147     ** used by any BEFORE and AFTER triggers that exist.  */
   71148     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
   71149     for(iCol=0; iCol<pTab->nCol; iCol++){
   71150       if( mask==0xffffffff || mask&(1<<iCol) ){
   71151         int iTarget = iOld + iCol + 1;
   71152         sqlite3VdbeAddOp3(v, OP_Column, iCur, iCol, iTarget);
   71153         sqlite3ColumnDefault(v, pTab, iCol, iTarget);
   71154       }
   71155     }
   71156 
   71157     /* Invoke BEFORE DELETE trigger programs. */
   71158     sqlite3CodeRowTrigger(pParse, pTrigger,
   71159         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
   71160     );
   71161 
   71162     /* Seek the cursor to the row to be deleted again. It may be that
   71163     ** the BEFORE triggers coded above have already removed the row
   71164     ** being deleted. Do not attempt to delete the row a second time, and
   71165     ** do not fire AFTER triggers.  */
   71166     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
   71167 
   71168     /* Do FK processing. This call checks that any FK constraints that
   71169     ** refer to this table (i.e. constraints attached to other tables)
   71170     ** are not violated by deleting this row.  */
   71171     sqlite3FkCheck(pParse, pTab, iOld, 0);
   71172   }
   71173 
   71174   /* Delete the index and table entries. Skip this step if pTab is really
   71175   ** a view (in which case the only effect of the DELETE statement is to
   71176   ** fire the INSTEAD OF triggers).  */
   71177   if( pTab->pSelect==0 ){
   71178     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
   71179     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
   71180     if( count ){
   71181       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
   71182     }
   71183   }
   71184 
   71185   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
   71186   ** handle rows (possibly in other tables) that refer via a foreign key
   71187   ** to the row just deleted. */
   71188   sqlite3FkActions(pParse, pTab, 0, iOld);
   71189 
   71190   /* Invoke AFTER DELETE trigger programs. */
   71191   sqlite3CodeRowTrigger(pParse, pTrigger,
   71192       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
   71193   );
   71194 
   71195   /* Jump here if the row had already been deleted before any BEFORE
   71196   ** trigger programs were invoked. Or if a trigger program throws a
   71197   ** RAISE(IGNORE) exception.  */
   71198   sqlite3VdbeResolveLabel(v, iLabel);
   71199 }
   71200 
   71201 /*
   71202 ** This routine generates VDBE code that causes the deletion of all
   71203 ** index entries associated with a single row of a single table.
   71204 **
   71205 ** The VDBE must be in a particular state when this routine is called.
   71206 ** These are the requirements:
   71207 **
   71208 **   1.  A read/write cursor pointing to pTab, the table containing the row
   71209 **       to be deleted, must be opened as cursor number "iCur".
   71210 **
   71211 **   2.  Read/write cursors for all indices of pTab must be open as
   71212 **       cursor number iCur+i for the i-th index.
   71213 **
   71214 **   3.  The "iCur" cursor must be pointing to the row that is to be
   71215 **       deleted.
   71216 */
   71217 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
   71218   Parse *pParse,     /* Parsing and code generating context */
   71219   Table *pTab,       /* Table containing the row to be deleted */
   71220   int iCur,          /* Cursor number for the table */
   71221   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
   71222 ){
   71223   int i;
   71224   Index *pIdx;
   71225   int r1;
   71226 
   71227   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
   71228     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
   71229     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
   71230     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
   71231   }
   71232 }
   71233 
   71234 /*
   71235 ** Generate code that will assemble an index key and put it in register
   71236 ** regOut.  The key with be for index pIdx which is an index on pTab.
   71237 ** iCur is the index of a cursor open on the pTab table and pointing to
   71238 ** the entry that needs indexing.
   71239 **
   71240 ** Return a register number which is the first in a block of
   71241 ** registers that holds the elements of the index key.  The
   71242 ** block of registers has already been deallocated by the time
   71243 ** this routine returns.
   71244 */
   71245 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
   71246   Parse *pParse,     /* Parsing context */
   71247   Index *pIdx,       /* The index for which to generate a key */
   71248   int iCur,          /* Cursor number for the pIdx->pTable table */
   71249   int regOut,        /* Write the new index key to this register */
   71250   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
   71251 ){
   71252   Vdbe *v = pParse->pVdbe;
   71253   int j;
   71254   Table *pTab = pIdx->pTable;
   71255   int regBase;
   71256   int nCol;
   71257 
   71258   nCol = pIdx->nColumn;
   71259   regBase = sqlite3GetTempRange(pParse, nCol+1);
   71260   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
   71261   for(j=0; j<nCol; j++){
   71262     int idx = pIdx->aiColumn[j];
   71263     if( idx==pTab->iPKey ){
   71264       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
   71265     }else{
   71266       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
   71267       sqlite3ColumnDefault(v, pTab, idx, -1);
   71268     }
   71269   }
   71270   if( doMakeRec ){
   71271     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
   71272     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
   71273   }
   71274   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
   71275   return regBase;
   71276 }
   71277 
   71278 /************** End of delete.c **********************************************/
   71279 /************** Begin file func.c ********************************************/
   71280 /*
   71281 ** 2002 February 23
   71282 **
   71283 ** The author disclaims copyright to this source code.  In place of
   71284 ** a legal notice, here is a blessing:
   71285 **
   71286 **    May you do good and not evil.
   71287 **    May you find forgiveness for yourself and forgive others.
   71288 **    May you share freely, never taking more than you give.
   71289 **
   71290 *************************************************************************
   71291 ** This file contains the C functions that implement various SQL
   71292 ** functions of SQLite.
   71293 **
   71294 ** There is only one exported symbol in this file - the function
   71295 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
   71296 ** All other code has file scope.
   71297 */
   71298 
   71299 /*
   71300 ** Return the collating function associated with a function.
   71301 */
   71302 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
   71303   return context->pColl;
   71304 }
   71305 
   71306 /*
   71307 ** Implementation of the non-aggregate min() and max() functions
   71308 */
   71309 static void minmaxFunc(
   71310   sqlite3_context *context,
   71311   int argc,
   71312   sqlite3_value **argv
   71313 ){
   71314   int i;
   71315   int mask;    /* 0 for min() or 0xffffffff for max() */
   71316   int iBest;
   71317   CollSeq *pColl;
   71318 
   71319   assert( argc>1 );
   71320   mask = sqlite3_user_data(context)==0 ? 0 : -1;
   71321   pColl = sqlite3GetFuncCollSeq(context);
   71322   assert( pColl );
   71323   assert( mask==-1 || mask==0 );
   71324   iBest = 0;
   71325   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   71326   for(i=1; i<argc; i++){
   71327     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
   71328     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
   71329       testcase( mask==0 );
   71330       iBest = i;
   71331     }
   71332   }
   71333   sqlite3_result_value(context, argv[iBest]);
   71334 }
   71335 
   71336 /*
   71337 ** Return the type of the argument.
   71338 */
   71339 static void typeofFunc(
   71340   sqlite3_context *context,
   71341   int NotUsed,
   71342   sqlite3_value **argv
   71343 ){
   71344   const char *z = 0;
   71345   UNUSED_PARAMETER(NotUsed);
   71346   switch( sqlite3_value_type(argv[0]) ){
   71347     case SQLITE_INTEGER: z = "integer"; break;
   71348     case SQLITE_TEXT:    z = "text";    break;
   71349     case SQLITE_FLOAT:   z = "real";    break;
   71350     case SQLITE_BLOB:    z = "blob";    break;
   71351     default:             z = "null";    break;
   71352   }
   71353   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
   71354 }
   71355 
   71356 
   71357 /*
   71358 ** Implementation of the length() function
   71359 */
   71360 static void lengthFunc(
   71361   sqlite3_context *context,
   71362   int argc,
   71363   sqlite3_value **argv
   71364 ){
   71365   int len;
   71366 
   71367   assert( argc==1 );
   71368   UNUSED_PARAMETER(argc);
   71369   switch( sqlite3_value_type(argv[0]) ){
   71370     case SQLITE_BLOB:
   71371     case SQLITE_INTEGER:
   71372     case SQLITE_FLOAT: {
   71373       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
   71374       break;
   71375     }
   71376     case SQLITE_TEXT: {
   71377       const unsigned char *z = sqlite3_value_text(argv[0]);
   71378       if( z==0 ) return;
   71379       len = 0;
   71380       while( *z ){
   71381         len++;
   71382         SQLITE_SKIP_UTF8(z);
   71383       }
   71384       sqlite3_result_int(context, len);
   71385       break;
   71386     }
   71387     default: {
   71388       sqlite3_result_null(context);
   71389       break;
   71390     }
   71391   }
   71392 }
   71393 
   71394 /*
   71395 ** Implementation of the abs() function.
   71396 **
   71397 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
   71398 ** the numeric argument X.
   71399 */
   71400 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   71401   assert( argc==1 );
   71402   UNUSED_PARAMETER(argc);
   71403   switch( sqlite3_value_type(argv[0]) ){
   71404     case SQLITE_INTEGER: {
   71405       i64 iVal = sqlite3_value_int64(argv[0]);
   71406       if( iVal<0 ){
   71407         if( (iVal<<1)==0 ){
   71408           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
   71409           ** abs(X) throws an integer overflow error since there is no
   71410           ** equivalent positive 64-bit two complement value. */
   71411           sqlite3_result_error(context, "integer overflow", -1);
   71412           return;
   71413         }
   71414         iVal = -iVal;
   71415       }
   71416       sqlite3_result_int64(context, iVal);
   71417       break;
   71418     }
   71419     case SQLITE_NULL: {
   71420       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
   71421       sqlite3_result_null(context);
   71422       break;
   71423     }
   71424     default: {
   71425       /* Because sqlite3_value_double() returns 0.0 if the argument is not
   71426       ** something that can be converted into a number, we have:
   71427       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
   71428       ** cannot be converted to a numeric value.
   71429       */
   71430       double rVal = sqlite3_value_double(argv[0]);
   71431       if( rVal<0 ) rVal = -rVal;
   71432       sqlite3_result_double(context, rVal);
   71433       break;
   71434     }
   71435   }
   71436 }
   71437 
   71438 /*
   71439 ** Implementation of the substr() function.
   71440 **
   71441 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
   71442 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
   71443 ** of x.  If x is text, then we actually count UTF-8 characters.
   71444 ** If x is a blob, then we count bytes.
   71445 **
   71446 ** If p1 is negative, then we begin abs(p1) from the end of x[].
   71447 **
   71448 ** If p2 is negative, return the p2 characters preceeding p1.
   71449 */
   71450 static void substrFunc(
   71451   sqlite3_context *context,
   71452   int argc,
   71453   sqlite3_value **argv
   71454 ){
   71455   const unsigned char *z;
   71456   const unsigned char *z2;
   71457   int len;
   71458   int p0type;
   71459   i64 p1, p2;
   71460   int negP2 = 0;
   71461 
   71462   assert( argc==3 || argc==2 );
   71463   if( sqlite3_value_type(argv[1])==SQLITE_NULL
   71464    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
   71465   ){
   71466     return;
   71467   }
   71468   p0type = sqlite3_value_type(argv[0]);
   71469   p1 = sqlite3_value_int(argv[1]);
   71470   if( p0type==SQLITE_BLOB ){
   71471     len = sqlite3_value_bytes(argv[0]);
   71472     z = sqlite3_value_blob(argv[0]);
   71473     if( z==0 ) return;
   71474     assert( len==sqlite3_value_bytes(argv[0]) );
   71475   }else{
   71476     z = sqlite3_value_text(argv[0]);
   71477     if( z==0 ) return;
   71478     len = 0;
   71479     if( p1<0 ){
   71480       for(z2=z; *z2; len++){
   71481         SQLITE_SKIP_UTF8(z2);
   71482       }
   71483     }
   71484   }
   71485   if( argc==3 ){
   71486     p2 = sqlite3_value_int(argv[2]);
   71487     if( p2<0 ){
   71488       p2 = -p2;
   71489       negP2 = 1;
   71490     }
   71491   }else{
   71492     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
   71493   }
   71494   if( p1<0 ){
   71495     p1 += len;
   71496     if( p1<0 ){
   71497       p2 += p1;
   71498       if( p2<0 ) p2 = 0;
   71499       p1 = 0;
   71500     }
   71501   }else if( p1>0 ){
   71502     p1--;
   71503   }else if( p2>0 ){
   71504     p2--;
   71505   }
   71506   if( negP2 ){
   71507     p1 -= p2;
   71508     if( p1<0 ){
   71509       p2 += p1;
   71510       p1 = 0;
   71511     }
   71512   }
   71513   assert( p1>=0 && p2>=0 );
   71514   if( p0type!=SQLITE_BLOB ){
   71515     while( *z && p1 ){
   71516       SQLITE_SKIP_UTF8(z);
   71517       p1--;
   71518     }
   71519     for(z2=z; *z2 && p2; p2--){
   71520       SQLITE_SKIP_UTF8(z2);
   71521     }
   71522     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
   71523   }else{
   71524     if( p1+p2>len ){
   71525       p2 = len-p1;
   71526       if( p2<0 ) p2 = 0;
   71527     }
   71528     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
   71529   }
   71530 }
   71531 
   71532 /*
   71533 ** Implementation of the round() function
   71534 */
   71535 #ifndef SQLITE_OMIT_FLOATING_POINT
   71536 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   71537   int n = 0;
   71538   double r;
   71539   char *zBuf;
   71540   assert( argc==1 || argc==2 );
   71541   if( argc==2 ){
   71542     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
   71543     n = sqlite3_value_int(argv[1]);
   71544     if( n>30 ) n = 30;
   71545     if( n<0 ) n = 0;
   71546   }
   71547   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   71548   r = sqlite3_value_double(argv[0]);
   71549   zBuf = sqlite3_mprintf("%.*f",n,r);
   71550   if( zBuf==0 ){
   71551     sqlite3_result_error_nomem(context);
   71552   }else{
   71553     sqlite3AtoF(zBuf, &r);
   71554     sqlite3_free(zBuf);
   71555     sqlite3_result_double(context, r);
   71556   }
   71557 }
   71558 #endif
   71559 
   71560 /*
   71561 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
   71562 ** allocation fails, call sqlite3_result_error_nomem() to notify
   71563 ** the database handle that malloc() has failed and return NULL.
   71564 ** If nByte is larger than the maximum string or blob length, then
   71565 ** raise an SQLITE_TOOBIG exception and return NULL.
   71566 */
   71567 static void *contextMalloc(sqlite3_context *context, i64 nByte){
   71568   char *z;
   71569   sqlite3 *db = sqlite3_context_db_handle(context);
   71570   assert( nByte>0 );
   71571   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
   71572   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   71573   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   71574     sqlite3_result_error_toobig(context);
   71575     z = 0;
   71576   }else{
   71577     z = sqlite3Malloc((int)nByte);
   71578     if( !z ){
   71579       sqlite3_result_error_nomem(context);
   71580     }
   71581   }
   71582   return z;
   71583 }
   71584 
   71585 /*
   71586 ** Implementation of the upper() and lower() SQL functions.
   71587 */
   71588 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   71589   char *z1;
   71590   const char *z2;
   71591   int i, n;
   71592   UNUSED_PARAMETER(argc);
   71593   z2 = (char*)sqlite3_value_text(argv[0]);
   71594   n = sqlite3_value_bytes(argv[0]);
   71595   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   71596   assert( z2==(char*)sqlite3_value_text(argv[0]) );
   71597   if( z2 ){
   71598     z1 = contextMalloc(context, ((i64)n)+1);
   71599     if( z1 ){
   71600       memcpy(z1, z2, n+1);
   71601       for(i=0; z1[i]; i++){
   71602         z1[i] = (char)sqlite3Toupper(z1[i]);
   71603       }
   71604       sqlite3_result_text(context, z1, -1, sqlite3_free);
   71605     }
   71606   }
   71607 }
   71608 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   71609   u8 *z1;
   71610   const char *z2;
   71611   int i, n;
   71612   UNUSED_PARAMETER(argc);
   71613   z2 = (char*)sqlite3_value_text(argv[0]);
   71614   n = sqlite3_value_bytes(argv[0]);
   71615   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   71616   assert( z2==(char*)sqlite3_value_text(argv[0]) );
   71617   if( z2 ){
   71618     z1 = contextMalloc(context, ((i64)n)+1);
   71619     if( z1 ){
   71620       memcpy(z1, z2, n+1);
   71621       for(i=0; z1[i]; i++){
   71622         z1[i] = sqlite3Tolower(z1[i]);
   71623       }
   71624       sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
   71625     }
   71626   }
   71627 }
   71628 
   71629 
   71630 #if 0  /* This function is never used. */
   71631 /*
   71632 ** The COALESCE() and IFNULL() functions used to be implemented as shown
   71633 ** here.  But now they are implemented as VDBE code so that unused arguments
   71634 ** do not have to be computed.  This legacy implementation is retained as
   71635 ** comment.
   71636 */
   71637 /*
   71638 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
   71639 ** All three do the same thing.  They return the first non-NULL
   71640 ** argument.
   71641 */
   71642 static void ifnullFunc(
   71643   sqlite3_context *context,
   71644   int argc,
   71645   sqlite3_value **argv
   71646 ){
   71647   int i;
   71648   for(i=0; i<argc; i++){
   71649     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
   71650       sqlite3_result_value(context, argv[i]);
   71651       break;
   71652     }
   71653   }
   71654 }
   71655 #endif /* NOT USED */
   71656 #define ifnullFunc versionFunc   /* Substitute function - never called */
   71657 
   71658 /*
   71659 ** Implementation of random().  Return a random integer.
   71660 */
   71661 static void randomFunc(
   71662   sqlite3_context *context,
   71663   int NotUsed,
   71664   sqlite3_value **NotUsed2
   71665 ){
   71666   sqlite_int64 r;
   71667   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   71668   sqlite3_randomness(sizeof(r), &r);
   71669   if( r<0 ){
   71670     /* We need to prevent a random number of 0x8000000000000000
   71671     ** (or -9223372036854775808) since when you do abs() of that
   71672     ** number of you get the same value back again.  To do this
   71673     ** in a way that is testable, mask the sign bit off of negative
   71674     ** values, resulting in a positive value.  Then take the
   71675     ** 2s complement of that positive value.  The end result can
   71676     ** therefore be no less than -9223372036854775807.
   71677     */
   71678     r = -(r ^ (((sqlite3_int64)1)<<63));
   71679   }
   71680   sqlite3_result_int64(context, r);
   71681 }
   71682 
   71683 /*
   71684 ** Implementation of randomblob(N).  Return a random blob
   71685 ** that is N bytes long.
   71686 */
   71687 static void randomBlob(
   71688   sqlite3_context *context,
   71689   int argc,
   71690   sqlite3_value **argv
   71691 ){
   71692   int n;
   71693   unsigned char *p;
   71694   assert( argc==1 );
   71695   UNUSED_PARAMETER(argc);
   71696   n = sqlite3_value_int(argv[0]);
   71697   if( n<1 ){
   71698     n = 1;
   71699   }
   71700   p = contextMalloc(context, n);
   71701   if( p ){
   71702     sqlite3_randomness(n, p);
   71703     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
   71704   }
   71705 }
   71706 
   71707 /*
   71708 ** Implementation of the last_insert_rowid() SQL function.  The return
   71709 ** value is the same as the sqlite3_last_insert_rowid() API function.
   71710 */
   71711 static void last_insert_rowid(
   71712   sqlite3_context *context,
   71713   int NotUsed,
   71714   sqlite3_value **NotUsed2
   71715 ){
   71716   sqlite3 *db = sqlite3_context_db_handle(context);
   71717   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   71718   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
   71719 }
   71720 
   71721 /*
   71722 ** Implementation of the changes() SQL function.  The return value is the
   71723 ** same as the sqlite3_changes() API function.
   71724 */
   71725 static void changes(
   71726   sqlite3_context *context,
   71727   int NotUsed,
   71728   sqlite3_value **NotUsed2
   71729 ){
   71730   sqlite3 *db = sqlite3_context_db_handle(context);
   71731   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   71732   sqlite3_result_int(context, sqlite3_changes(db));
   71733 }
   71734 
   71735 /*
   71736 ** Implementation of the total_changes() SQL function.  The return value is
   71737 ** the same as the sqlite3_total_changes() API function.
   71738 */
   71739 static void total_changes(
   71740   sqlite3_context *context,
   71741   int NotUsed,
   71742   sqlite3_value **NotUsed2
   71743 ){
   71744   sqlite3 *db = sqlite3_context_db_handle(context);
   71745   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   71746   sqlite3_result_int(context, sqlite3_total_changes(db));
   71747 }
   71748 
   71749 /*
   71750 ** A structure defining how to do GLOB-style comparisons.
   71751 */
   71752 struct compareInfo {
   71753   u8 matchAll;
   71754   u8 matchOne;
   71755   u8 matchSet;
   71756   u8 noCase;
   71757 };
   71758 
   71759 /*
   71760 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
   71761 ** character is exactly one byte in size.  Also, all characters are
   71762 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
   71763 ** whereas only characters less than 0x80 do in ASCII.
   71764 */
   71765 #if defined(SQLITE_EBCDIC)
   71766 # define sqlite3Utf8Read(A,C)    (*(A++))
   71767 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
   71768 #else
   71769 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
   71770 #endif
   71771 
   71772 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
   71773 /* The correct SQL-92 behavior is for the LIKE operator to ignore
   71774 ** case.  Thus  'a' LIKE 'A' would be true. */
   71775 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
   71776 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
   71777 ** is case sensitive causing 'a' LIKE 'A' to be false */
   71778 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
   71779 
   71780 /*
   71781 ** Compare two UTF-8 strings for equality where the first string can
   71782 ** potentially be a "glob" expression.  Return true (1) if they
   71783 ** are the same and false (0) if they are different.
   71784 **
   71785 ** Globbing rules:
   71786 **
   71787 **      '*'       Matches any sequence of zero or more characters.
   71788 **
   71789 **      '?'       Matches exactly one character.
   71790 **
   71791 **     [...]      Matches one character from the enclosed list of
   71792 **                characters.
   71793 **
   71794 **     [^...]     Matches one character not in the enclosed list.
   71795 **
   71796 ** With the [...] and [^...] matching, a ']' character can be included
   71797 ** in the list by making it the first character after '[' or '^'.  A
   71798 ** range of characters can be specified using '-'.  Example:
   71799 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
   71800 ** it the last character in the list.
   71801 **
   71802 ** This routine is usually quick, but can be N**2 in the worst case.
   71803 **
   71804 ** Hints: to match '*' or '?', put them in "[]".  Like this:
   71805 **
   71806 **         abc[*]xyz        Matches "abc*xyz" only
   71807 */
   71808 static int patternCompare(
   71809   const u8 *zPattern,              /* The glob pattern */
   71810   const u8 *zString,               /* The string to compare against the glob */
   71811   const struct compareInfo *pInfo, /* Information about how to do the compare */
   71812   const int esc                    /* The escape character */
   71813 ){
   71814   int c, c2;
   71815   int invert;
   71816   int seen;
   71817   u8 matchOne = pInfo->matchOne;
   71818   u8 matchAll = pInfo->matchAll;
   71819   u8 matchSet = pInfo->matchSet;
   71820   u8 noCase = pInfo->noCase;
   71821   int prevEscape = 0;     /* True if the previous character was 'escape' */
   71822 
   71823   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
   71824     if( !prevEscape && c==matchAll ){
   71825       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
   71826                || c == matchOne ){
   71827         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
   71828           return 0;
   71829         }
   71830       }
   71831       if( c==0 ){
   71832         return 1;
   71833       }else if( c==esc ){
   71834         c = sqlite3Utf8Read(zPattern, &zPattern);
   71835         if( c==0 ){
   71836           return 0;
   71837         }
   71838       }else if( c==matchSet ){
   71839         assert( esc==0 );         /* This is GLOB, not LIKE */
   71840         assert( matchSet<0x80 );  /* '[' is a single-byte character */
   71841         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
   71842           SQLITE_SKIP_UTF8(zString);
   71843         }
   71844         return *zString!=0;
   71845       }
   71846       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
   71847         if( noCase ){
   71848           GlogUpperToLower(c2);
   71849           GlogUpperToLower(c);
   71850           while( c2 != 0 && c2 != c ){
   71851             c2 = sqlite3Utf8Read(zString, &zString);
   71852             GlogUpperToLower(c2);
   71853           }
   71854         }else{
   71855           while( c2 != 0 && c2 != c ){
   71856             c2 = sqlite3Utf8Read(zString, &zString);
   71857           }
   71858         }
   71859         if( c2==0 ) return 0;
   71860         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
   71861       }
   71862       return 0;
   71863     }else if( !prevEscape && c==matchOne ){
   71864       if( sqlite3Utf8Read(zString, &zString)==0 ){
   71865         return 0;
   71866       }
   71867     }else if( c==matchSet ){
   71868       int prior_c = 0;
   71869       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
   71870       seen = 0;
   71871       invert = 0;
   71872       c = sqlite3Utf8Read(zString, &zString);
   71873       if( c==0 ) return 0;
   71874       c2 = sqlite3Utf8Read(zPattern, &zPattern);
   71875       if( c2=='^' ){
   71876         invert = 1;
   71877         c2 = sqlite3Utf8Read(zPattern, &zPattern);
   71878       }
   71879       if( c2==']' ){
   71880         if( c==']' ) seen = 1;
   71881         c2 = sqlite3Utf8Read(zPattern, &zPattern);
   71882       }
   71883       while( c2 && c2!=']' ){
   71884         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
   71885           c2 = sqlite3Utf8Read(zPattern, &zPattern);
   71886           if( c>=prior_c && c<=c2 ) seen = 1;
   71887           prior_c = 0;
   71888         }else{
   71889           if( c==c2 ){
   71890             seen = 1;
   71891           }
   71892           prior_c = c2;
   71893         }
   71894         c2 = sqlite3Utf8Read(zPattern, &zPattern);
   71895       }
   71896       if( c2==0 || (seen ^ invert)==0 ){
   71897         return 0;
   71898       }
   71899     }else if( esc==c && !prevEscape ){
   71900       prevEscape = 1;
   71901     }else{
   71902       c2 = sqlite3Utf8Read(zString, &zString);
   71903       if( noCase ){
   71904         GlogUpperToLower(c);
   71905         GlogUpperToLower(c2);
   71906       }
   71907       if( c!=c2 ){
   71908         return 0;
   71909       }
   71910       prevEscape = 0;
   71911     }
   71912   }
   71913   return *zString==0;
   71914 }
   71915 
   71916 /*
   71917 ** Count the number of times that the LIKE operator (or GLOB which is
   71918 ** just a variation of LIKE) gets called.  This is used for testing
   71919 ** only.
   71920 */
   71921 #ifdef SQLITE_TEST
   71922 SQLITE_API int sqlite3_like_count = 0;
   71923 #endif
   71924 
   71925 
   71926 /*
   71927 ** Implementation of the like() SQL function.  This function implements
   71928 ** the build-in LIKE operator.  The first argument to the function is the
   71929 ** pattern and the second argument is the string.  So, the SQL statements:
   71930 **
   71931 **       A LIKE B
   71932 **
   71933 ** is implemented as like(B,A).
   71934 **
   71935 ** This same function (with a different compareInfo structure) computes
   71936 ** the GLOB operator.
   71937 */
   71938 static void likeFunc(
   71939   sqlite3_context *context,
   71940   int argc,
   71941   sqlite3_value **argv
   71942 ){
   71943   const unsigned char *zA, *zB;
   71944   int escape = 0;
   71945   int nPat;
   71946   sqlite3 *db = sqlite3_context_db_handle(context);
   71947 
   71948   zB = sqlite3_value_text(argv[0]);
   71949   zA = sqlite3_value_text(argv[1]);
   71950 
   71951   /* Limit the length of the LIKE or GLOB pattern to avoid problems
   71952   ** of deep recursion and N*N behavior in patternCompare().
   71953   */
   71954   nPat = sqlite3_value_bytes(argv[0]);
   71955   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
   71956   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
   71957   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
   71958     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
   71959     return;
   71960   }
   71961   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
   71962 
   71963   if( argc==3 ){
   71964     /* The escape character string must consist of a single UTF-8 character.
   71965     ** Otherwise, return an error.
   71966     */
   71967     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
   71968     if( zEsc==0 ) return;
   71969     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
   71970       sqlite3_result_error(context,
   71971           "ESCAPE expression must be a single character", -1);
   71972       return;
   71973     }
   71974     escape = sqlite3Utf8Read(zEsc, &zEsc);
   71975   }
   71976   if( zA && zB ){
   71977     struct compareInfo *pInfo = sqlite3_user_data(context);
   71978 #ifdef SQLITE_TEST
   71979     sqlite3_like_count++;
   71980 #endif
   71981 
   71982     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
   71983   }
   71984 }
   71985 
   71986 /*
   71987 ** Implementation of the NULLIF(x,y) function.  The result is the first
   71988 ** argument if the arguments are different.  The result is NULL if the
   71989 ** arguments are equal to each other.
   71990 */
   71991 static void nullifFunc(
   71992   sqlite3_context *context,
   71993   int NotUsed,
   71994   sqlite3_value **argv
   71995 ){
   71996   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
   71997   UNUSED_PARAMETER(NotUsed);
   71998   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
   71999     sqlite3_result_value(context, argv[0]);
   72000   }
   72001 }
   72002 
   72003 /*
   72004 ** Implementation of the sqlite_version() function.  The result is the version
   72005 ** of the SQLite library that is running.
   72006 */
   72007 static void versionFunc(
   72008   sqlite3_context *context,
   72009   int NotUsed,
   72010   sqlite3_value **NotUsed2
   72011 ){
   72012   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   72013   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
   72014 }
   72015 
   72016 /*
   72017 ** Implementation of the sqlite_source_id() function. The result is a string
   72018 ** that identifies the particular version of the source code used to build
   72019 ** SQLite.
   72020 */
   72021 static void sourceidFunc(
   72022   sqlite3_context *context,
   72023   int NotUsed,
   72024   sqlite3_value **NotUsed2
   72025 ){
   72026   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   72027   sqlite3_result_text(context, SQLITE_SOURCE_ID, -1, SQLITE_STATIC);
   72028 }
   72029 
   72030 /* Array for converting from half-bytes (nybbles) into ASCII hex
   72031 ** digits. */
   72032 static const char hexdigits[] = {
   72033   '0', '1', '2', '3', '4', '5', '6', '7',
   72034   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
   72035 };
   72036 
   72037 /*
   72038 ** EXPERIMENTAL - This is not an official function.  The interface may
   72039 ** change.  This function may disappear.  Do not write code that depends
   72040 ** on this function.
   72041 **
   72042 ** Implementation of the QUOTE() function.  This function takes a single
   72043 ** argument.  If the argument is numeric, the return value is the same as
   72044 ** the argument.  If the argument is NULL, the return value is the string
   72045 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
   72046 ** single-quote escapes.
   72047 */
   72048 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   72049   assert( argc==1 );
   72050   UNUSED_PARAMETER(argc);
   72051   switch( sqlite3_value_type(argv[0]) ){
   72052     case SQLITE_INTEGER:
   72053     case SQLITE_FLOAT: {
   72054       sqlite3_result_value(context, argv[0]);
   72055       break;
   72056     }
   72057     case SQLITE_BLOB: {
   72058       char *zText = 0;
   72059       char const *zBlob = sqlite3_value_blob(argv[0]);
   72060       int nBlob = sqlite3_value_bytes(argv[0]);
   72061       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
   72062       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
   72063       if( zText ){
   72064         int i;
   72065         for(i=0; i<nBlob; i++){
   72066           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
   72067           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
   72068         }
   72069         zText[(nBlob*2)+2] = '\'';
   72070         zText[(nBlob*2)+3] = '\0';
   72071         zText[0] = 'X';
   72072         zText[1] = '\'';
   72073         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
   72074         sqlite3_free(zText);
   72075       }
   72076       break;
   72077     }
   72078     case SQLITE_TEXT: {
   72079       int i,j;
   72080       u64 n;
   72081       const unsigned char *zArg = sqlite3_value_text(argv[0]);
   72082       char *z;
   72083 
   72084       if( zArg==0 ) return;
   72085       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
   72086       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
   72087       if( z ){
   72088         z[0] = '\'';
   72089         for(i=0, j=1; zArg[i]; i++){
   72090           z[j++] = zArg[i];
   72091           if( zArg[i]=='\'' ){
   72092             z[j++] = '\'';
   72093           }
   72094         }
   72095         z[j++] = '\'';
   72096         z[j] = 0;
   72097         sqlite3_result_text(context, z, j, sqlite3_free);
   72098       }
   72099       break;
   72100     }
   72101     default: {
   72102       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
   72103       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
   72104       break;
   72105     }
   72106   }
   72107 }
   72108 
   72109 /*
   72110 ** The hex() function.  Interpret the argument as a blob.  Return
   72111 ** a hexadecimal rendering as text.
   72112 */
   72113 static void hexFunc(
   72114   sqlite3_context *context,
   72115   int argc,
   72116   sqlite3_value **argv
   72117 ){
   72118   int i, n;
   72119   const unsigned char *pBlob;
   72120   char *zHex, *z;
   72121   assert( argc==1 );
   72122   UNUSED_PARAMETER(argc);
   72123   pBlob = sqlite3_value_blob(argv[0]);
   72124   n = sqlite3_value_bytes(argv[0]);
   72125   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
   72126   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
   72127   if( zHex ){
   72128     for(i=0; i<n; i++, pBlob++){
   72129       unsigned char c = *pBlob;
   72130       *(z++) = hexdigits[(c>>4)&0xf];
   72131       *(z++) = hexdigits[c&0xf];
   72132     }
   72133     *z = 0;
   72134     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
   72135   }
   72136 }
   72137 
   72138 /*
   72139 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
   72140 */
   72141 static void zeroblobFunc(
   72142   sqlite3_context *context,
   72143   int argc,
   72144   sqlite3_value **argv
   72145 ){
   72146   i64 n;
   72147   sqlite3 *db = sqlite3_context_db_handle(context);
   72148   assert( argc==1 );
   72149   UNUSED_PARAMETER(argc);
   72150   n = sqlite3_value_int64(argv[0]);
   72151   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
   72152   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   72153   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   72154     sqlite3_result_error_toobig(context);
   72155   }else{
   72156     sqlite3_result_zeroblob(context, (int)n);
   72157   }
   72158 }
   72159 
   72160 /*
   72161 ** The replace() function.  Three arguments are all strings: call
   72162 ** them A, B, and C. The result is also a string which is derived
   72163 ** from A by replacing every occurance of B with C.  The match
   72164 ** must be exact.  Collating sequences are not used.
   72165 */
   72166 static void replaceFunc(
   72167   sqlite3_context *context,
   72168   int argc,
   72169   sqlite3_value **argv
   72170 ){
   72171   const unsigned char *zStr;        /* The input string A */
   72172   const unsigned char *zPattern;    /* The pattern string B */
   72173   const unsigned char *zRep;        /* The replacement string C */
   72174   unsigned char *zOut;              /* The output */
   72175   int nStr;                /* Size of zStr */
   72176   int nPattern;            /* Size of zPattern */
   72177   int nRep;                /* Size of zRep */
   72178   i64 nOut;                /* Maximum size of zOut */
   72179   int loopLimit;           /* Last zStr[] that might match zPattern[] */
   72180   int i, j;                /* Loop counters */
   72181 
   72182   assert( argc==3 );
   72183   UNUSED_PARAMETER(argc);
   72184   zStr = sqlite3_value_text(argv[0]);
   72185   if( zStr==0 ) return;
   72186   nStr = sqlite3_value_bytes(argv[0]);
   72187   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
   72188   zPattern = sqlite3_value_text(argv[1]);
   72189   if( zPattern==0 ){
   72190     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
   72191             || sqlite3_context_db_handle(context)->mallocFailed );
   72192     return;
   72193   }
   72194   if( zPattern[0]==0 ){
   72195     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
   72196     sqlite3_result_value(context, argv[0]);
   72197     return;
   72198   }
   72199   nPattern = sqlite3_value_bytes(argv[1]);
   72200   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
   72201   zRep = sqlite3_value_text(argv[2]);
   72202   if( zRep==0 ) return;
   72203   nRep = sqlite3_value_bytes(argv[2]);
   72204   assert( zRep==sqlite3_value_text(argv[2]) );
   72205   nOut = nStr + 1;
   72206   assert( nOut<SQLITE_MAX_LENGTH );
   72207   zOut = contextMalloc(context, (i64)nOut);
   72208   if( zOut==0 ){
   72209     return;
   72210   }
   72211   loopLimit = nStr - nPattern;
   72212   for(i=j=0; i<=loopLimit; i++){
   72213     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
   72214       zOut[j++] = zStr[i];
   72215     }else{
   72216       u8 *zOld;
   72217       sqlite3 *db = sqlite3_context_db_handle(context);
   72218       nOut += nRep - nPattern;
   72219       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
   72220       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
   72221       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   72222         sqlite3_result_error_toobig(context);
   72223         sqlite3DbFree(db, zOut);
   72224         return;
   72225       }
   72226       zOld = zOut;
   72227       zOut = sqlite3_realloc(zOut, (int)nOut);
   72228       if( zOut==0 ){
   72229         sqlite3_result_error_nomem(context);
   72230         sqlite3DbFree(db, zOld);
   72231         return;
   72232       }
   72233       memcpy(&zOut[j], zRep, nRep);
   72234       j += nRep;
   72235       i += nPattern-1;
   72236     }
   72237   }
   72238   assert( j+nStr-i+1==nOut );
   72239   memcpy(&zOut[j], &zStr[i], nStr-i);
   72240   j += nStr - i;
   72241   assert( j<=nOut );
   72242   zOut[j] = 0;
   72243   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
   72244 }
   72245 
   72246 /*
   72247 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
   72248 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
   72249 */
   72250 static void trimFunc(
   72251   sqlite3_context *context,
   72252   int argc,
   72253   sqlite3_value **argv
   72254 ){
   72255   const unsigned char *zIn;         /* Input string */
   72256   const unsigned char *zCharSet;    /* Set of characters to trim */
   72257   int nIn;                          /* Number of bytes in input */
   72258   int flags;                        /* 1: trimleft  2: trimright  3: trim */
   72259   int i;                            /* Loop counter */
   72260   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
   72261   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
   72262   int nChar;                        /* Number of characters in zCharSet */
   72263 
   72264   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
   72265     return;
   72266   }
   72267   zIn = sqlite3_value_text(argv[0]);
   72268   if( zIn==0 ) return;
   72269   nIn = sqlite3_value_bytes(argv[0]);
   72270   assert( zIn==sqlite3_value_text(argv[0]) );
   72271   if( argc==1 ){
   72272     static const unsigned char lenOne[] = { 1 };
   72273     static unsigned char * const azOne[] = { (u8*)" " };
   72274     nChar = 1;
   72275     aLen = (u8*)lenOne;
   72276     azChar = (unsigned char **)azOne;
   72277     zCharSet = 0;
   72278   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
   72279     return;
   72280   }else{
   72281     const unsigned char *z;
   72282     for(z=zCharSet, nChar=0; *z; nChar++){
   72283       SQLITE_SKIP_UTF8(z);
   72284     }
   72285     if( nChar>0 ){
   72286       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
   72287       if( azChar==0 ){
   72288         return;
   72289       }
   72290       aLen = (unsigned char*)&azChar[nChar];
   72291       for(z=zCharSet, nChar=0; *z; nChar++){
   72292         azChar[nChar] = (unsigned char *)z;
   72293         SQLITE_SKIP_UTF8(z);
   72294         aLen[nChar] = (u8)(z - azChar[nChar]);
   72295       }
   72296     }
   72297   }
   72298   if( nChar>0 ){
   72299     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
   72300     if( flags & 1 ){
   72301       while( nIn>0 ){
   72302         int len = 0;
   72303         for(i=0; i<nChar; i++){
   72304           len = aLen[i];
   72305           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
   72306         }
   72307         if( i>=nChar ) break;
   72308         zIn += len;
   72309         nIn -= len;
   72310       }
   72311     }
   72312     if( flags & 2 ){
   72313       while( nIn>0 ){
   72314         int len = 0;
   72315         for(i=0; i<nChar; i++){
   72316           len = aLen[i];
   72317           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
   72318         }
   72319         if( i>=nChar ) break;
   72320         nIn -= len;
   72321       }
   72322     }
   72323     if( zCharSet ){
   72324       sqlite3_free(azChar);
   72325     }
   72326   }
   72327   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
   72328 }
   72329 
   72330 
   72331 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
   72332 ** is only available if the SQLITE_SOUNDEX compile-time option is used
   72333 ** when SQLite is built.
   72334 */
   72335 #ifdef SQLITE_SOUNDEX
   72336 /*
   72337 ** Compute the soundex encoding of a word.
   72338 **
   72339 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
   72340 ** soundex encoding of the string X.
   72341 */
   72342 static void soundexFunc(
   72343   sqlite3_context *context,
   72344   int argc,
   72345   sqlite3_value **argv
   72346 ){
   72347   char zResult[8];
   72348   const u8 *zIn;
   72349   int i, j;
   72350   static const unsigned char iCode[] = {
   72351     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   72352     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   72353     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   72354     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   72355     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
   72356     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
   72357     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
   72358     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
   72359   };
   72360   assert( argc==1 );
   72361   zIn = (u8*)sqlite3_value_text(argv[0]);
   72362   if( zIn==0 ) zIn = (u8*)"";
   72363   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
   72364   if( zIn[i] ){
   72365     u8 prevcode = iCode[zIn[i]&0x7f];
   72366     zResult[0] = sqlite3Toupper(zIn[i]);
   72367     for(j=1; j<4 && zIn[i]; i++){
   72368       int code = iCode[zIn[i]&0x7f];
   72369       if( code>0 ){
   72370         if( code!=prevcode ){
   72371           prevcode = code;
   72372           zResult[j++] = code + '0';
   72373         }
   72374       }else{
   72375         prevcode = 0;
   72376       }
   72377     }
   72378     while( j<4 ){
   72379       zResult[j++] = '0';
   72380     }
   72381     zResult[j] = 0;
   72382     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
   72383   }else{
   72384     /* IMP: R-64894-50321 The string "?000" is returned if the argument
   72385     ** is NULL or contains no ASCII alphabetic characters. */
   72386     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
   72387   }
   72388 }
   72389 #endif /* SQLITE_SOUNDEX */
   72390 
   72391 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   72392 /*
   72393 ** A function that loads a shared-library extension then returns NULL.
   72394 */
   72395 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
   72396   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
   72397   const char *zProc;
   72398   sqlite3 *db = sqlite3_context_db_handle(context);
   72399   char *zErrMsg = 0;
   72400 
   72401   if( argc==2 ){
   72402     zProc = (const char *)sqlite3_value_text(argv[1]);
   72403   }else{
   72404     zProc = 0;
   72405   }
   72406   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
   72407     sqlite3_result_error(context, zErrMsg, -1);
   72408     sqlite3_free(zErrMsg);
   72409   }
   72410 }
   72411 #endif
   72412 
   72413 
   72414 /*
   72415 ** An instance of the following structure holds the context of a
   72416 ** sum() or avg() aggregate computation.
   72417 */
   72418 typedef struct SumCtx SumCtx;
   72419 struct SumCtx {
   72420   double rSum;      /* Floating point sum */
   72421   i64 iSum;         /* Integer sum */
   72422   i64 cnt;          /* Number of elements summed */
   72423   u8 overflow;      /* True if integer overflow seen */
   72424   u8 approx;        /* True if non-integer value was input to the sum */
   72425 };
   72426 
   72427 /*
   72428 ** Routines used to compute the sum, average, and total.
   72429 **
   72430 ** The SUM() function follows the (broken) SQL standard which means
   72431 ** that it returns NULL if it sums over no inputs.  TOTAL returns
   72432 ** 0.0 in that case.  In addition, TOTAL always returns a float where
   72433 ** SUM might return an integer if it never encounters a floating point
   72434 ** value.  TOTAL never fails, but SUM might through an exception if
   72435 ** it overflows an integer.
   72436 */
   72437 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
   72438   SumCtx *p;
   72439   int type;
   72440   assert( argc==1 );
   72441   UNUSED_PARAMETER(argc);
   72442   p = sqlite3_aggregate_context(context, sizeof(*p));
   72443   type = sqlite3_value_numeric_type(argv[0]);
   72444   if( p && type!=SQLITE_NULL ){
   72445     p->cnt++;
   72446     if( type==SQLITE_INTEGER ){
   72447       i64 v = sqlite3_value_int64(argv[0]);
   72448       p->rSum += v;
   72449       if( (p->approx|p->overflow)==0 ){
   72450         i64 iNewSum = p->iSum + v;
   72451         int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
   72452         int s2 = (int)(v       >> (sizeof(i64)*8-1));
   72453         int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
   72454         p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
   72455         p->iSum = iNewSum;
   72456       }
   72457     }else{
   72458       p->rSum += sqlite3_value_double(argv[0]);
   72459       p->approx = 1;
   72460     }
   72461   }
   72462 }
   72463 static void sumFinalize(sqlite3_context *context){
   72464   SumCtx *p;
   72465   p = sqlite3_aggregate_context(context, 0);
   72466   if( p && p->cnt>0 ){
   72467     if( p->overflow ){
   72468       sqlite3_result_error(context,"integer overflow",-1);
   72469     }else if( p->approx ){
   72470       sqlite3_result_double(context, p->rSum);
   72471     }else{
   72472       sqlite3_result_int64(context, p->iSum);
   72473     }
   72474   }
   72475 }
   72476 static void avgFinalize(sqlite3_context *context){
   72477   SumCtx *p;
   72478   p = sqlite3_aggregate_context(context, 0);
   72479   if( p && p->cnt>0 ){
   72480     sqlite3_result_double(context, p->rSum/(double)p->cnt);
   72481   }
   72482 }
   72483 static void totalFinalize(sqlite3_context *context){
   72484   SumCtx *p;
   72485   p = sqlite3_aggregate_context(context, 0);
   72486   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   72487   sqlite3_result_double(context, p ? p->rSum : (double)0);
   72488 }
   72489 
   72490 /*
   72491 ** The following structure keeps track of state information for the
   72492 ** count() aggregate function.
   72493 */
   72494 typedef struct CountCtx CountCtx;
   72495 struct CountCtx {
   72496   i64 n;
   72497 };
   72498 
   72499 /*
   72500 ** Routines to implement the count() aggregate function.
   72501 */
   72502 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
   72503   CountCtx *p;
   72504   p = sqlite3_aggregate_context(context, sizeof(*p));
   72505   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
   72506     p->n++;
   72507   }
   72508 
   72509 #ifndef SQLITE_OMIT_DEPRECATED
   72510   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
   72511   ** sure it still operates correctly, verify that its count agrees with our
   72512   ** internal count when using count(*) and when the total count can be
   72513   ** expressed as a 32-bit integer. */
   72514   assert( argc==1 || p==0 || p->n>0x7fffffff
   72515           || p->n==sqlite3_aggregate_count(context) );
   72516 #endif
   72517 }
   72518 static void countFinalize(sqlite3_context *context){
   72519   CountCtx *p;
   72520   p = sqlite3_aggregate_context(context, 0);
   72521   sqlite3_result_int64(context, p ? p->n : 0);
   72522 }
   72523 
   72524 /*
   72525 ** Routines to implement min() and max() aggregate functions.
   72526 */
   72527 static void minmaxStep(
   72528   sqlite3_context *context,
   72529   int NotUsed,
   72530   sqlite3_value **argv
   72531 ){
   72532   Mem *pArg  = (Mem *)argv[0];
   72533   Mem *pBest;
   72534   UNUSED_PARAMETER(NotUsed);
   72535 
   72536   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   72537   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
   72538   if( !pBest ) return;
   72539 
   72540   if( pBest->flags ){
   72541     int max;
   72542     int cmp;
   72543     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
   72544     /* This step function is used for both the min() and max() aggregates,
   72545     ** the only difference between the two being that the sense of the
   72546     ** comparison is inverted. For the max() aggregate, the
   72547     ** sqlite3_user_data() function returns (void *)-1. For min() it
   72548     ** returns (void *)db, where db is the sqlite3* database pointer.
   72549     ** Therefore the next statement sets variable 'max' to 1 for the max()
   72550     ** aggregate, or 0 for min().
   72551     */
   72552     max = sqlite3_user_data(context)!=0;
   72553     cmp = sqlite3MemCompare(pBest, pArg, pColl);
   72554     if( (max && cmp<0) || (!max && cmp>0) ){
   72555       sqlite3VdbeMemCopy(pBest, pArg);
   72556     }
   72557   }else{
   72558     sqlite3VdbeMemCopy(pBest, pArg);
   72559   }
   72560 }
   72561 static void minMaxFinalize(sqlite3_context *context){
   72562   sqlite3_value *pRes;
   72563   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
   72564   if( pRes ){
   72565     if( ALWAYS(pRes->flags) ){
   72566       sqlite3_result_value(context, pRes);
   72567     }
   72568     sqlite3VdbeMemRelease(pRes);
   72569   }
   72570 }
   72571 
   72572 /*
   72573 ** group_concat(EXPR, ?SEPARATOR?)
   72574 */
   72575 static void groupConcatStep(
   72576   sqlite3_context *context,
   72577   int argc,
   72578   sqlite3_value **argv
   72579 ){
   72580   const char *zVal;
   72581   StrAccum *pAccum;
   72582   const char *zSep;
   72583   int nVal, nSep;
   72584   assert( argc==1 || argc==2 );
   72585   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   72586   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
   72587 
   72588   if( pAccum ){
   72589     sqlite3 *db = sqlite3_context_db_handle(context);
   72590     int firstTerm = pAccum->useMalloc==0;
   72591     pAccum->useMalloc = 1;
   72592     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
   72593     if( !firstTerm ){
   72594       if( argc==2 ){
   72595         zSep = (char*)sqlite3_value_text(argv[1]);
   72596         nSep = sqlite3_value_bytes(argv[1]);
   72597       }else{
   72598         zSep = ",";
   72599         nSep = 1;
   72600       }
   72601       sqlite3StrAccumAppend(pAccum, zSep, nSep);
   72602     }
   72603     zVal = (char*)sqlite3_value_text(argv[0]);
   72604     nVal = sqlite3_value_bytes(argv[0]);
   72605     sqlite3StrAccumAppend(pAccum, zVal, nVal);
   72606   }
   72607 }
   72608 static void groupConcatFinalize(sqlite3_context *context){
   72609   StrAccum *pAccum;
   72610   pAccum = sqlite3_aggregate_context(context, 0);
   72611   if( pAccum ){
   72612     if( pAccum->tooBig ){
   72613       sqlite3_result_error_toobig(context);
   72614     }else if( pAccum->mallocFailed ){
   72615       sqlite3_result_error_nomem(context);
   72616     }else{
   72617       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
   72618                           sqlite3_free);
   72619     }
   72620   }
   72621 }
   72622 
   72623 /*
   72624 ** This function registered all of the above C functions as SQL
   72625 ** functions.  This should be the only routine in this file with
   72626 ** external linkage.
   72627 */
   72628 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
   72629 #ifndef SQLITE_OMIT_ALTERTABLE
   72630   sqlite3AlterFunctions(db);
   72631 #endif
   72632   if( !db->mallocFailed ){
   72633     int rc = sqlite3_overload_function(db, "MATCH", 2);
   72634     assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
   72635     if( rc==SQLITE_NOMEM ){
   72636       db->mallocFailed = 1;
   72637     }
   72638   }
   72639 }
   72640 
   72641 /*
   72642 ** Set the LIKEOPT flag on the 2-argument function with the given name.
   72643 */
   72644 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
   72645   FuncDef *pDef;
   72646   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
   72647                              2, SQLITE_UTF8, 0);
   72648   if( ALWAYS(pDef) ){
   72649     pDef->flags = flagVal;
   72650   }
   72651 }
   72652 
   72653 /*
   72654 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
   72655 ** parameter determines whether or not the LIKE operator is case
   72656 ** sensitive.  GLOB is always case sensitive.
   72657 */
   72658 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
   72659   struct compareInfo *pInfo;
   72660   if( caseSensitive ){
   72661     pInfo = (struct compareInfo*)&likeInfoAlt;
   72662   }else{
   72663     pInfo = (struct compareInfo*)&likeInfoNorm;
   72664   }
   72665   sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0);
   72666   sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0);
   72667   sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY,
   72668       (struct compareInfo*)&globInfo, likeFunc, 0,0);
   72669   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
   72670   setLikeOptFlag(db, "like",
   72671       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
   72672 }
   72673 
   72674 /*
   72675 ** pExpr points to an expression which implements a function.  If
   72676 ** it is appropriate to apply the LIKE optimization to that function
   72677 ** then set aWc[0] through aWc[2] to the wildcard characters and
   72678 ** return TRUE.  If the function is not a LIKE-style function then
   72679 ** return FALSE.
   72680 */
   72681 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
   72682   FuncDef *pDef;
   72683   if( pExpr->op!=TK_FUNCTION
   72684    || !pExpr->x.pList
   72685    || pExpr->x.pList->nExpr!=2
   72686   ){
   72687     return 0;
   72688   }
   72689   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   72690   pDef = sqlite3FindFunction(db, pExpr->u.zToken,
   72691                              sqlite3Strlen30(pExpr->u.zToken),
   72692                              2, SQLITE_UTF8, 0);
   72693   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
   72694     return 0;
   72695   }
   72696 
   72697   /* The memcpy() statement assumes that the wildcard characters are
   72698   ** the first three statements in the compareInfo structure.  The
   72699   ** asserts() that follow verify that assumption
   72700   */
   72701   memcpy(aWc, pDef->pUserData, 3);
   72702   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
   72703   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
   72704   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
   72705   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
   72706   return 1;
   72707 }
   72708 
   72709 /*
   72710 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
   72711 ** to the global function hash table.  This occurs at start-time (as
   72712 ** a consequence of calling sqlite3_initialize()).
   72713 **
   72714 ** After this routine runs
   72715 */
   72716 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
   72717   /*
   72718   ** The following array holds FuncDef structures for all of the functions
   72719   ** defined in this file.
   72720   **
   72721   ** The array cannot be constant since changes are made to the
   72722   ** FuncDef.pHash elements at start-time.  The elements of this array
   72723   ** are read-only after initialization is complete.
   72724   */
   72725   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
   72726     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
   72727     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
   72728     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
   72729     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
   72730     FUNCTION(trim,               1, 3, 0, trimFunc         ),
   72731     FUNCTION(trim,               2, 3, 0, trimFunc         ),
   72732     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
   72733     FUNCTION(min,                0, 0, 1, 0                ),
   72734     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
   72735     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
   72736     FUNCTION(max,                0, 1, 1, 0                ),
   72737     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
   72738     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
   72739     FUNCTION(length,             1, 0, 0, lengthFunc       ),
   72740     FUNCTION(substr,             2, 0, 0, substrFunc       ),
   72741     FUNCTION(substr,             3, 0, 0, substrFunc       ),
   72742     FUNCTION(abs,                1, 0, 0, absFunc          ),
   72743 #ifndef SQLITE_OMIT_FLOATING_POINT
   72744     FUNCTION(round,              1, 0, 0, roundFunc        ),
   72745     FUNCTION(round,              2, 0, 0, roundFunc        ),
   72746 #endif
   72747     FUNCTION(upper,              1, 0, 0, upperFunc        ),
   72748     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
   72749     FUNCTION(coalesce,           1, 0, 0, 0                ),
   72750     FUNCTION(coalesce,           0, 0, 0, 0                ),
   72751 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
   72752     {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0},
   72753     FUNCTION(hex,                1, 0, 0, hexFunc          ),
   72754 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
   72755     {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0},
   72756     FUNCTION(random,             0, 0, 0, randomFunc       ),
   72757     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
   72758     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
   72759     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
   72760     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
   72761     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
   72762     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
   72763     FUNCTION(changes,            0, 0, 0, changes          ),
   72764     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
   72765     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
   72766     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
   72767   #ifdef SQLITE_SOUNDEX
   72768     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
   72769   #endif
   72770   #ifndef SQLITE_OMIT_LOAD_EXTENSION
   72771     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
   72772     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
   72773   #endif
   72774     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
   72775     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
   72776     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
   72777  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
   72778     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0},
   72779     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
   72780     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
   72781     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
   72782 
   72783     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   72784   #ifdef SQLITE_CASE_SENSITIVE_LIKE
   72785     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   72786     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   72787   #else
   72788     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
   72789     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
   72790   #endif
   72791   };
   72792 
   72793   int i;
   72794   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   72795   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
   72796 
   72797   for(i=0; i<ArraySize(aBuiltinFunc); i++){
   72798     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   72799   }
   72800   sqlite3RegisterDateTimeFunctions();
   72801 }
   72802 
   72803 /************** End of func.c ************************************************/
   72804 /************** Begin file fkey.c ********************************************/
   72805 /*
   72806 **
   72807 ** The author disclaims copyright to this source code.  In place of
   72808 ** a legal notice, here is a blessing:
   72809 **
   72810 **    May you do good and not evil.
   72811 **    May you find forgiveness for yourself and forgive others.
   72812 **    May you share freely, never taking more than you give.
   72813 **
   72814 *************************************************************************
   72815 ** This file contains code used by the compiler to add foreign key
   72816 ** support to compiled SQL statements.
   72817 */
   72818 
   72819 #ifndef SQLITE_OMIT_FOREIGN_KEY
   72820 #ifndef SQLITE_OMIT_TRIGGER
   72821 
   72822 /*
   72823 ** Deferred and Immediate FKs
   72824 ** --------------------------
   72825 **
   72826 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
   72827 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
   72828 ** is returned and the current statement transaction rolled back. If a
   72829 ** deferred foreign key constraint is violated, no action is taken
   72830 ** immediately. However if the application attempts to commit the
   72831 ** transaction before fixing the constraint violation, the attempt fails.
   72832 **
   72833 ** Deferred constraints are implemented using a simple counter associated
   72834 ** with the database handle. The counter is set to zero each time a
   72835 ** database transaction is opened. Each time a statement is executed
   72836 ** that causes a foreign key violation, the counter is incremented. Each
   72837 ** time a statement is executed that removes an existing violation from
   72838 ** the database, the counter is decremented. When the transaction is
   72839 ** committed, the commit fails if the current value of the counter is
   72840 ** greater than zero. This scheme has two big drawbacks:
   72841 **
   72842 **   * When a commit fails due to a deferred foreign key constraint,
   72843 **     there is no way to tell which foreign constraint is not satisfied,
   72844 **     or which row it is not satisfied for.
   72845 **
   72846 **   * If the database contains foreign key violations when the
   72847 **     transaction is opened, this may cause the mechanism to malfunction.
   72848 **
   72849 ** Despite these problems, this approach is adopted as it seems simpler
   72850 ** than the alternatives.
   72851 **
   72852 ** INSERT operations:
   72853 **
   72854 **   I.1) For each FK for which the table is the child table, search
   72855 **        the parent table for a match. If none is found increment the
   72856 **        constraint counter.
   72857 **
   72858 **   I.2) For each FK for which the table is the parent table,
   72859 **        search the child table for rows that correspond to the new
   72860 **        row in the parent table. Decrement the counter for each row
   72861 **        found (as the constraint is now satisfied).
   72862 **
   72863 ** DELETE operations:
   72864 **
   72865 **   D.1) For each FK for which the table is the child table,
   72866 **        search the parent table for a row that corresponds to the
   72867 **        deleted row in the child table. If such a row is not found,
   72868 **        decrement the counter.
   72869 **
   72870 **   D.2) For each FK for which the table is the parent table, search
   72871 **        the child table for rows that correspond to the deleted row
   72872 **        in the parent table. For each found increment the counter.
   72873 **
   72874 ** UPDATE operations:
   72875 **
   72876 **   An UPDATE command requires that all 4 steps above are taken, but only
   72877 **   for FK constraints for which the affected columns are actually
   72878 **   modified (values must be compared at runtime).
   72879 **
   72880 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
   72881 ** This simplifies the implementation a bit.
   72882 **
   72883 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
   72884 ** resolution is considered to delete rows before the new row is inserted.
   72885 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
   72886 ** is thrown, even if the FK constraint would be satisfied after the new
   72887 ** row is inserted.
   72888 **
   72889 ** Immediate constraints are usually handled similarly. The only difference
   72890 ** is that the counter used is stored as part of each individual statement
   72891 ** object (struct Vdbe). If, after the statement has run, its immediate
   72892 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
   72893 ** and the statement transaction is rolled back. An exception is an INSERT
   72894 ** statement that inserts a single row only (no triggers). In this case,
   72895 ** instead of using a counter, an exception is thrown immediately if the
   72896 ** INSERT violates a foreign key constraint. This is necessary as such
   72897 ** an INSERT does not open a statement transaction.
   72898 **
   72899 ** TODO: How should dropping a table be handled? How should renaming a
   72900 ** table be handled?
   72901 **
   72902 **
   72903 ** Query API Notes
   72904 ** ---------------
   72905 **
   72906 ** Before coding an UPDATE or DELETE row operation, the code-generator
   72907 ** for those two operations needs to know whether or not the operation
   72908 ** requires any FK processing and, if so, which columns of the original
   72909 ** row are required by the FK processing VDBE code (i.e. if FKs were
   72910 ** implemented using triggers, which of the old.* columns would be
   72911 ** accessed). No information is required by the code-generator before
   72912 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
   72913 ** generation code to query for this information are:
   72914 **
   72915 **   sqlite3FkRequired() - Test to see if FK processing is required.
   72916 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
   72917 **
   72918 **
   72919 ** Externally accessible module functions
   72920 ** --------------------------------------
   72921 **
   72922 **   sqlite3FkCheck()    - Check for foreign key violations.
   72923 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
   72924 **   sqlite3FkDelete()   - Delete an FKey structure.
   72925 */
   72926 
   72927 /*
   72928 ** VDBE Calling Convention
   72929 ** -----------------------
   72930 **
   72931 ** Example:
   72932 **
   72933 **   For the following INSERT statement:
   72934 **
   72935 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
   72936 **     INSERT INTO t1 VALUES(1, 2, 3.1);
   72937 **
   72938 **   Register (x):        2    (type integer)
   72939 **   Register (x+1):      1    (type integer)
   72940 **   Register (x+2):      NULL (type NULL)
   72941 **   Register (x+3):      3.1  (type real)
   72942 */
   72943 
   72944 /*
   72945 ** A foreign key constraint requires that the key columns in the parent
   72946 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
   72947 ** Given that pParent is the parent table for foreign key constraint pFKey,
   72948 ** search the schema a unique index on the parent key columns.
   72949 **
   72950 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
   72951 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
   72952 ** is set to point to the unique index.
   72953 **
   72954 ** If the parent key consists of a single column (the foreign key constraint
   72955 ** is not a composite foreign key), output variable *paiCol is set to NULL.
   72956 ** Otherwise, it is set to point to an allocated array of size N, where
   72957 ** N is the number of columns in the parent key. The first element of the
   72958 ** array is the index of the child table column that is mapped by the FK
   72959 ** constraint to the parent table column stored in the left-most column
   72960 ** of index *ppIdx. The second element of the array is the index of the
   72961 ** child table column that corresponds to the second left-most column of
   72962 ** *ppIdx, and so on.
   72963 **
   72964 ** If the required index cannot be found, either because:
   72965 **
   72966 **   1) The named parent key columns do not exist, or
   72967 **
   72968 **   2) The named parent key columns do exist, but are not subject to a
   72969 **      UNIQUE or PRIMARY KEY constraint, or
   72970 **
   72971 **   3) No parent key columns were provided explicitly as part of the
   72972 **      foreign key definition, and the parent table does not have a
   72973 **      PRIMARY KEY, or
   72974 **
   72975 **   4) No parent key columns were provided explicitly as part of the
   72976 **      foreign key definition, and the PRIMARY KEY of the parent table
   72977 **      consists of a a different number of columns to the child key in
   72978 **      the child table.
   72979 **
   72980 ** then non-zero is returned, and a "foreign key mismatch" error loaded
   72981 ** into pParse. If an OOM error occurs, non-zero is returned and the
   72982 ** pParse->db->mallocFailed flag is set.
   72983 */
   72984 static int locateFkeyIndex(
   72985   Parse *pParse,                  /* Parse context to store any error in */
   72986   Table *pParent,                 /* Parent table of FK constraint pFKey */
   72987   FKey *pFKey,                    /* Foreign key to find index for */
   72988   Index **ppIdx,                  /* OUT: Unique index on parent table */
   72989   int **paiCol                    /* OUT: Map of index columns in pFKey */
   72990 ){
   72991   Index *pIdx = 0;                    /* Value to return via *ppIdx */
   72992   int *aiCol = 0;                     /* Value to return via *paiCol */
   72993   int nCol = pFKey->nCol;             /* Number of columns in parent key */
   72994   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
   72995 
   72996   /* The caller is responsible for zeroing output parameters. */
   72997   assert( ppIdx && *ppIdx==0 );
   72998   assert( !paiCol || *paiCol==0 );
   72999   assert( pParse );
   73000 
   73001   /* If this is a non-composite (single column) foreign key, check if it
   73002   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
   73003   ** and *paiCol set to zero and return early.
   73004   **
   73005   ** Otherwise, for a composite foreign key (more than one column), allocate
   73006   ** space for the aiCol array (returned via output parameter *paiCol).
   73007   ** Non-composite foreign keys do not require the aiCol array.
   73008   */
   73009   if( nCol==1 ){
   73010     /* The FK maps to the IPK if any of the following are true:
   73011     **
   73012     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
   73013     **      mapped to the primary key of table pParent, or
   73014     **   2) The FK is explicitly mapped to a column declared as INTEGER
   73015     **      PRIMARY KEY.
   73016     */
   73017     if( pParent->iPKey>=0 ){
   73018       if( !zKey ) return 0;
   73019       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
   73020     }
   73021   }else if( paiCol ){
   73022     assert( nCol>1 );
   73023     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
   73024     if( !aiCol ) return 1;
   73025     *paiCol = aiCol;
   73026   }
   73027 
   73028   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
   73029     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
   73030       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
   73031       ** of columns. If each indexed column corresponds to a foreign key
   73032       ** column of pFKey, then this index is a winner.  */
   73033 
   73034       if( zKey==0 ){
   73035         /* If zKey is NULL, then this foreign key is implicitly mapped to
   73036         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
   73037         ** identified by the test (Index.autoIndex==2).  */
   73038         if( pIdx->autoIndex==2 ){
   73039           if( aiCol ){
   73040             int i;
   73041             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
   73042           }
   73043           break;
   73044         }
   73045       }else{
   73046         /* If zKey is non-NULL, then this foreign key was declared to
   73047         ** map to an explicit list of columns in table pParent. Check if this
   73048         ** index matches those columns. Also, check that the index uses
   73049         ** the default collation sequences for each column. */
   73050         int i, j;
   73051         for(i=0; i<nCol; i++){
   73052           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
   73053           char *zDfltColl;                  /* Def. collation for column */
   73054           char *zIdxCol;                    /* Name of indexed column */
   73055 
   73056           /* If the index uses a collation sequence that is different from
   73057           ** the default collation sequence for the column, this index is
   73058           ** unusable. Bail out early in this case.  */
   73059           zDfltColl = pParent->aCol[iCol].zColl;
   73060           if( !zDfltColl ){
   73061             zDfltColl = "BINARY";
   73062           }
   73063           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
   73064 
   73065           zIdxCol = pParent->aCol[iCol].zName;
   73066           for(j=0; j<nCol; j++){
   73067             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
   73068               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
   73069               break;
   73070             }
   73071           }
   73072           if( j==nCol ) break;
   73073         }
   73074         if( i==nCol ) break;      /* pIdx is usable */
   73075       }
   73076     }
   73077   }
   73078 
   73079   if( !pIdx ){
   73080     if( !pParse->disableTriggers ){
   73081       sqlite3ErrorMsg(pParse, "foreign key mismatch");
   73082     }
   73083     sqlite3DbFree(pParse->db, aiCol);
   73084     return 1;
   73085   }
   73086 
   73087   *ppIdx = pIdx;
   73088   return 0;
   73089 }
   73090 
   73091 /*
   73092 ** This function is called when a row is inserted into or deleted from the
   73093 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
   73094 ** on the child table of pFKey, this function is invoked twice for each row
   73095 ** affected - once to "delete" the old row, and then again to "insert" the
   73096 ** new row.
   73097 **
   73098 ** Each time it is called, this function generates VDBE code to locate the
   73099 ** row in the parent table that corresponds to the row being inserted into
   73100 ** or deleted from the child table. If the parent row can be found, no
   73101 ** special action is taken. Otherwise, if the parent row can *not* be
   73102 ** found in the parent table:
   73103 **
   73104 **   Operation | FK type   | Action taken
   73105 **   --------------------------------------------------------------------------
   73106 **   INSERT      immediate   Increment the "immediate constraint counter".
   73107 **
   73108 **   DELETE      immediate   Decrement the "immediate constraint counter".
   73109 **
   73110 **   INSERT      deferred    Increment the "deferred constraint counter".
   73111 **
   73112 **   DELETE      deferred    Decrement the "deferred constraint counter".
   73113 **
   73114 ** These operations are identified in the comment at the top of this file
   73115 ** (fkey.c) as "I.1" and "D.1".
   73116 */
   73117 static void fkLookupParent(
   73118   Parse *pParse,        /* Parse context */
   73119   int iDb,              /* Index of database housing pTab */
   73120   Table *pTab,          /* Parent table of FK pFKey */
   73121   Index *pIdx,          /* Unique index on parent key columns in pTab */
   73122   FKey *pFKey,          /* Foreign key constraint */
   73123   int *aiCol,           /* Map from parent key columns to child table columns */
   73124   int regData,          /* Address of array containing child table row */
   73125   int nIncr,            /* Increment constraint counter by this */
   73126   int isIgnore          /* If true, pretend pTab contains all NULL values */
   73127 ){
   73128   int i;                                    /* Iterator variable */
   73129   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
   73130   int iCur = pParse->nTab - 1;              /* Cursor number to use */
   73131   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
   73132 
   73133   /* If nIncr is less than zero, then check at runtime if there are any
   73134   ** outstanding constraints to resolve. If there are not, there is no need
   73135   ** to check if deleting this row resolves any outstanding violations.
   73136   **
   73137   ** Check if any of the key columns in the child table row are NULL. If
   73138   ** any are, then the constraint is considered satisfied. No need to
   73139   ** search for a matching row in the parent table.  */
   73140   if( nIncr<0 ){
   73141     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
   73142   }
   73143   for(i=0; i<pFKey->nCol; i++){
   73144     int iReg = aiCol[i] + regData + 1;
   73145     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
   73146   }
   73147 
   73148   if( isIgnore==0 ){
   73149     if( pIdx==0 ){
   73150       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
   73151       ** column of the parent table (table pTab).  */
   73152       int iMustBeInt;               /* Address of MustBeInt instruction */
   73153       int regTemp = sqlite3GetTempReg(pParse);
   73154 
   73155       /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
   73156       ** apply the affinity of the parent key). If this fails, then there
   73157       ** is no matching parent key. Before using MustBeInt, make a copy of
   73158       ** the value. Otherwise, the value inserted into the child key column
   73159       ** will have INTEGER affinity applied to it, which may not be correct.  */
   73160       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
   73161       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
   73162 
   73163       /* If the parent table is the same as the child table, and we are about
   73164       ** to increment the constraint-counter (i.e. this is an INSERT operation),
   73165       ** then check if the row being inserted matches itself. If so, do not
   73166       ** increment the constraint-counter.  */
   73167       if( pTab==pFKey->pFrom && nIncr==1 ){
   73168         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
   73169       }
   73170 
   73171       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
   73172       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
   73173       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
   73174       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
   73175       sqlite3VdbeJumpHere(v, iMustBeInt);
   73176       sqlite3ReleaseTempReg(pParse, regTemp);
   73177     }else{
   73178       int nCol = pFKey->nCol;
   73179       int regTemp = sqlite3GetTempRange(pParse, nCol);
   73180       int regRec = sqlite3GetTempReg(pParse);
   73181       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   73182 
   73183       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
   73184       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
   73185       for(i=0; i<nCol; i++){
   73186         sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
   73187       }
   73188 
   73189       /* If the parent table is the same as the child table, and we are about
   73190       ** to increment the constraint-counter (i.e. this is an INSERT operation),
   73191       ** then check if the row being inserted matches itself. If so, do not
   73192       ** increment the constraint-counter.  */
   73193       if( pTab==pFKey->pFrom && nIncr==1 ){
   73194         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
   73195         for(i=0; i<nCol; i++){
   73196           int iChild = aiCol[i]+1+regData;
   73197           int iParent = pIdx->aiColumn[i]+1+regData;
   73198           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
   73199         }
   73200         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
   73201       }
   73202 
   73203       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
   73204       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
   73205       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
   73206 
   73207       sqlite3ReleaseTempReg(pParse, regRec);
   73208       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
   73209     }
   73210   }
   73211 
   73212   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
   73213     /* Special case: If this is an INSERT statement that will insert exactly
   73214     ** one row into the table, raise a constraint immediately instead of
   73215     ** incrementing a counter. This is necessary as the VM code is being
   73216     ** generated for will not open a statement transaction.  */
   73217     assert( nIncr==1 );
   73218     sqlite3HaltConstraint(
   73219         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
   73220     );
   73221   }else{
   73222     if( nIncr>0 && pFKey->isDeferred==0 ){
   73223       sqlite3ParseToplevel(pParse)->mayAbort = 1;
   73224     }
   73225     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
   73226   }
   73227 
   73228   sqlite3VdbeResolveLabel(v, iOk);
   73229   sqlite3VdbeAddOp1(v, OP_Close, iCur);
   73230 }
   73231 
   73232 /*
   73233 ** This function is called to generate code executed when a row is deleted
   73234 ** from the parent table of foreign key constraint pFKey and, if pFKey is
   73235 ** deferred, when a row is inserted into the same table. When generating
   73236 ** code for an SQL UPDATE operation, this function may be called twice -
   73237 ** once to "delete" the old row and once to "insert" the new row.
   73238 **
   73239 ** The code generated by this function scans through the rows in the child
   73240 ** table that correspond to the parent table row being deleted or inserted.
   73241 ** For each child row found, one of the following actions is taken:
   73242 **
   73243 **   Operation | FK type   | Action taken
   73244 **   --------------------------------------------------------------------------
   73245 **   DELETE      immediate   Increment the "immediate constraint counter".
   73246 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
   73247 **                           throw a "foreign key constraint failed" exception.
   73248 **
   73249 **   INSERT      immediate   Decrement the "immediate constraint counter".
   73250 **
   73251 **   DELETE      deferred    Increment the "deferred constraint counter".
   73252 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
   73253 **                           throw a "foreign key constraint failed" exception.
   73254 **
   73255 **   INSERT      deferred    Decrement the "deferred constraint counter".
   73256 **
   73257 ** These operations are identified in the comment at the top of this file
   73258 ** (fkey.c) as "I.2" and "D.2".
   73259 */
   73260 static void fkScanChildren(
   73261   Parse *pParse,                  /* Parse context */
   73262   SrcList *pSrc,                  /* SrcList containing the table to scan */
   73263   Table *pTab,
   73264   Index *pIdx,                    /* Foreign key index */
   73265   FKey *pFKey,                    /* Foreign key relationship */
   73266   int *aiCol,                     /* Map from pIdx cols to child table cols */
   73267   int regData,                    /* Referenced table data starts here */
   73268   int nIncr                       /* Amount to increment deferred counter by */
   73269 ){
   73270   sqlite3 *db = pParse->db;       /* Database handle */
   73271   int i;                          /* Iterator variable */
   73272   Expr *pWhere = 0;               /* WHERE clause to scan with */
   73273   NameContext sNameContext;       /* Context used to resolve WHERE clause */
   73274   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
   73275   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
   73276   Vdbe *v = sqlite3GetVdbe(pParse);
   73277 
   73278   assert( !pIdx || pIdx->pTable==pTab );
   73279 
   73280   if( nIncr<0 ){
   73281     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
   73282   }
   73283 
   73284   /* Create an Expr object representing an SQL expression like:
   73285   **
   73286   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
   73287   **
   73288   ** The collation sequence used for the comparison should be that of
   73289   ** the parent key columns. The affinity of the parent key column should
   73290   ** be applied to each child key value before the comparison takes place.
   73291   */
   73292   for(i=0; i<pFKey->nCol; i++){
   73293     Expr *pLeft;                  /* Value from parent table row */
   73294     Expr *pRight;                 /* Column ref to child table */
   73295     Expr *pEq;                    /* Expression (pLeft = pRight) */
   73296     int iCol;                     /* Index of column in child table */
   73297     const char *zCol;             /* Name of column in child table */
   73298 
   73299     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
   73300     if( pLeft ){
   73301       /* Set the collation sequence and affinity of the LHS of each TK_EQ
   73302       ** expression to the parent key column defaults.  */
   73303       if( pIdx ){
   73304         Column *pCol;
   73305         iCol = pIdx->aiColumn[i];
   73306         pCol = &pIdx->pTable->aCol[iCol];
   73307         pLeft->iTable = regData+iCol+1;
   73308         pLeft->affinity = pCol->affinity;
   73309         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
   73310       }else{
   73311         pLeft->iTable = regData;
   73312         pLeft->affinity = SQLITE_AFF_INTEGER;
   73313       }
   73314     }
   73315     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
   73316     assert( iCol>=0 );
   73317     zCol = pFKey->pFrom->aCol[iCol].zName;
   73318     pRight = sqlite3Expr(db, TK_ID, zCol);
   73319     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
   73320     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   73321   }
   73322 
   73323   /* If the child table is the same as the parent table, and this scan
   73324   ** is taking place as part of a DELETE operation (operation D.2), omit the
   73325   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
   73326   ** clause, where $rowid is the rowid of the row being deleted.  */
   73327   if( pTab==pFKey->pFrom && nIncr>0 ){
   73328     Expr *pEq;                    /* Expression (pLeft = pRight) */
   73329     Expr *pLeft;                  /* Value from parent table row */
   73330     Expr *pRight;                 /* Column ref to child table */
   73331     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
   73332     pRight = sqlite3Expr(db, TK_COLUMN, 0);
   73333     if( pLeft && pRight ){
   73334       pLeft->iTable = regData;
   73335       pLeft->affinity = SQLITE_AFF_INTEGER;
   73336       pRight->iTable = pSrc->a[0].iCursor;
   73337       pRight->iColumn = -1;
   73338     }
   73339     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
   73340     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   73341   }
   73342 
   73343   /* Resolve the references in the WHERE clause. */
   73344   memset(&sNameContext, 0, sizeof(NameContext));
   73345   sNameContext.pSrcList = pSrc;
   73346   sNameContext.pParse = pParse;
   73347   sqlite3ResolveExprNames(&sNameContext, pWhere);
   73348 
   73349   /* Create VDBE to loop through the entries in pSrc that match the WHERE
   73350   ** clause. If the constraint is not deferred, throw an exception for
   73351   ** each row found. Otherwise, for deferred constraints, increment the
   73352   ** deferred constraint counter by nIncr for each row selected.  */
   73353   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
   73354   if( nIncr>0 && pFKey->isDeferred==0 ){
   73355     sqlite3ParseToplevel(pParse)->mayAbort = 1;
   73356   }
   73357   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
   73358   if( pWInfo ){
   73359     sqlite3WhereEnd(pWInfo);
   73360   }
   73361 
   73362   /* Clean up the WHERE clause constructed above. */
   73363   sqlite3ExprDelete(db, pWhere);
   73364   if( iFkIfZero ){
   73365     sqlite3VdbeJumpHere(v, iFkIfZero);
   73366   }
   73367 }
   73368 
   73369 /*
   73370 ** This function returns a pointer to the head of a linked list of FK
   73371 ** constraints for which table pTab is the parent table. For example,
   73372 ** given the following schema:
   73373 **
   73374 **   CREATE TABLE t1(a PRIMARY KEY);
   73375 **   CREATE TABLE t2(b REFERENCES t1(a);
   73376 **
   73377 ** Calling this function with table "t1" as an argument returns a pointer
   73378 ** to the FKey structure representing the foreign key constraint on table
   73379 ** "t2". Calling this function with "t2" as the argument would return a
   73380 ** NULL pointer (as there are no FK constraints for which t2 is the parent
   73381 ** table).
   73382 */
   73383 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
   73384   int nName = sqlite3Strlen30(pTab->zName);
   73385   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
   73386 }
   73387 
   73388 /*
   73389 ** The second argument is a Trigger structure allocated by the
   73390 ** fkActionTrigger() routine. This function deletes the Trigger structure
   73391 ** and all of its sub-components.
   73392 **
   73393 ** The Trigger structure or any of its sub-components may be allocated from
   73394 ** the lookaside buffer belonging to database handle dbMem.
   73395 */
   73396 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
   73397   if( p ){
   73398     TriggerStep *pStep = p->step_list;
   73399     sqlite3ExprDelete(dbMem, pStep->pWhere);
   73400     sqlite3ExprListDelete(dbMem, pStep->pExprList);
   73401     sqlite3SelectDelete(dbMem, pStep->pSelect);
   73402     sqlite3ExprDelete(dbMem, p->pWhen);
   73403     sqlite3DbFree(dbMem, p);
   73404   }
   73405 }
   73406 
   73407 /*
   73408 ** This function is called to generate code that runs when table pTab is
   73409 ** being dropped from the database. The SrcList passed as the second argument
   73410 ** to this function contains a single entry guaranteed to resolve to
   73411 ** table pTab.
   73412 **
   73413 ** Normally, no code is required. However, if either
   73414 **
   73415 **   (a) The table is the parent table of a FK constraint, or
   73416 **   (b) The table is the child table of a deferred FK constraint and it is
   73417 **       determined at runtime that there are outstanding deferred FK
   73418 **       constraint violations in the database,
   73419 **
   73420 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
   73421 ** the table from the database. Triggers are disabled while running this
   73422 ** DELETE, but foreign key actions are not.
   73423 */
   73424 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
   73425   sqlite3 *db = pParse->db;
   73426   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
   73427     int iSkip = 0;
   73428     Vdbe *v = sqlite3GetVdbe(pParse);
   73429 
   73430     assert( v );                  /* VDBE has already been allocated */
   73431     if( sqlite3FkReferences(pTab)==0 ){
   73432       /* Search for a deferred foreign key constraint for which this table
   73433       ** is the child table. If one cannot be found, return without
   73434       ** generating any VDBE code. If one can be found, then jump over
   73435       ** the entire DELETE if there are no outstanding deferred constraints
   73436       ** when this statement is run.  */
   73437       FKey *p;
   73438       for(p=pTab->pFKey; p; p=p->pNextFrom){
   73439         if( p->isDeferred ) break;
   73440       }
   73441       if( !p ) return;
   73442       iSkip = sqlite3VdbeMakeLabel(v);
   73443       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
   73444     }
   73445 
   73446     pParse->disableTriggers = 1;
   73447     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
   73448     pParse->disableTriggers = 0;
   73449 
   73450     /* If the DELETE has generated immediate foreign key constraint
   73451     ** violations, halt the VDBE and return an error at this point, before
   73452     ** any modifications to the schema are made. This is because statement
   73453     ** transactions are not able to rollback schema changes.  */
   73454     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
   73455     sqlite3HaltConstraint(
   73456         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
   73457     );
   73458 
   73459     if( iSkip ){
   73460       sqlite3VdbeResolveLabel(v, iSkip);
   73461     }
   73462   }
   73463 }
   73464 
   73465 /*
   73466 ** This function is called when inserting, deleting or updating a row of
   73467 ** table pTab to generate VDBE code to perform foreign key constraint
   73468 ** processing for the operation.
   73469 **
   73470 ** For a DELETE operation, parameter regOld is passed the index of the
   73471 ** first register in an array of (pTab->nCol+1) registers containing the
   73472 ** rowid of the row being deleted, followed by each of the column values
   73473 ** of the row being deleted, from left to right. Parameter regNew is passed
   73474 ** zero in this case.
   73475 **
   73476 ** For an INSERT operation, regOld is passed zero and regNew is passed the
   73477 ** first register of an array of (pTab->nCol+1) registers containing the new
   73478 ** row data.
   73479 **
   73480 ** For an UPDATE operation, this function is called twice. Once before
   73481 ** the original record is deleted from the table using the calling convention
   73482 ** described for DELETE. Then again after the original record is deleted
   73483 ** but before the new record is inserted using the INSERT convention.
   73484 */
   73485 SQLITE_PRIVATE void sqlite3FkCheck(
   73486   Parse *pParse,                  /* Parse context */
   73487   Table *pTab,                    /* Row is being deleted from this table */
   73488   int regOld,                     /* Previous row data is stored here */
   73489   int regNew                      /* New row data is stored here */
   73490 ){
   73491   sqlite3 *db = pParse->db;       /* Database handle */
   73492   Vdbe *v;                        /* VM to write code to */
   73493   FKey *pFKey;                    /* Used to iterate through FKs */
   73494   int iDb;                        /* Index of database containing pTab */
   73495   const char *zDb;                /* Name of database containing pTab */
   73496   int isIgnoreErrors = pParse->disableTriggers;
   73497 
   73498   /* Exactly one of regOld and regNew should be non-zero. */
   73499   assert( (regOld==0)!=(regNew==0) );
   73500 
   73501   /* If foreign-keys are disabled, this function is a no-op. */
   73502   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
   73503 
   73504   v = sqlite3GetVdbe(pParse);
   73505   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   73506   zDb = db->aDb[iDb].zName;
   73507 
   73508   /* Loop through all the foreign key constraints for which pTab is the
   73509   ** child table (the table that the foreign key definition is part of).  */
   73510   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
   73511     Table *pTo;                   /* Parent table of foreign key pFKey */
   73512     Index *pIdx = 0;              /* Index on key columns in pTo */
   73513     int *aiFree = 0;
   73514     int *aiCol;
   73515     int iCol;
   73516     int i;
   73517     int isIgnore = 0;
   73518 
   73519     /* Find the parent table of this foreign key. Also find a unique index
   73520     ** on the parent key columns in the parent table. If either of these
   73521     ** schema items cannot be located, set an error in pParse and return
   73522     ** early.  */
   73523     if( pParse->disableTriggers ){
   73524       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
   73525     }else{
   73526       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
   73527     }
   73528     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
   73529       if( !isIgnoreErrors || db->mallocFailed ) return;
   73530       continue;
   73531     }
   73532     assert( pFKey->nCol==1 || (aiFree && pIdx) );
   73533 
   73534     if( aiFree ){
   73535       aiCol = aiFree;
   73536     }else{
   73537       iCol = pFKey->aCol[0].iFrom;
   73538       aiCol = &iCol;
   73539     }
   73540     for(i=0; i<pFKey->nCol; i++){
   73541       if( aiCol[i]==pTab->iPKey ){
   73542         aiCol[i] = -1;
   73543       }
   73544 #ifndef SQLITE_OMIT_AUTHORIZATION
   73545       /* Request permission to read the parent key columns. If the
   73546       ** authorization callback returns SQLITE_IGNORE, behave as if any
   73547       ** values read from the parent table are NULL. */
   73548       if( db->xAuth ){
   73549         int rcauth;
   73550         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
   73551         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
   73552         isIgnore = (rcauth==SQLITE_IGNORE);
   73553       }
   73554 #endif
   73555     }
   73556 
   73557     /* Take a shared-cache advisory read-lock on the parent table. Allocate
   73558     ** a cursor to use to search the unique index on the parent key columns
   73559     ** in the parent table.  */
   73560     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
   73561     pParse->nTab++;
   73562 
   73563     if( regOld!=0 ){
   73564       /* A row is being removed from the child table. Search for the parent.
   73565       ** If the parent does not exist, removing the child row resolves an
   73566       ** outstanding foreign key constraint violation. */
   73567       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
   73568     }
   73569     if( regNew!=0 ){
   73570       /* A row is being added to the child table. If a parent row cannot
   73571       ** be found, adding the child row has violated the FK constraint. */
   73572       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
   73573     }
   73574 
   73575     sqlite3DbFree(db, aiFree);
   73576   }
   73577 
   73578   /* Loop through all the foreign key constraints that refer to this table */
   73579   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
   73580     Index *pIdx = 0;              /* Foreign key index for pFKey */
   73581     SrcList *pSrc;
   73582     int *aiCol = 0;
   73583 
   73584     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
   73585       assert( regOld==0 && regNew!=0 );
   73586       /* Inserting a single row into a parent table cannot cause an immediate
   73587       ** foreign key violation. So do nothing in this case.  */
   73588       continue;
   73589     }
   73590 
   73591     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
   73592       if( !isIgnoreErrors || db->mallocFailed ) return;
   73593       continue;
   73594     }
   73595     assert( aiCol || pFKey->nCol==1 );
   73596 
   73597     /* Create a SrcList structure containing a single table (the table
   73598     ** the foreign key that refers to this table is attached to). This
   73599     ** is required for the sqlite3WhereXXX() interface.  */
   73600     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   73601     if( pSrc ){
   73602       struct SrcList_item *pItem = pSrc->a;
   73603       pItem->pTab = pFKey->pFrom;
   73604       pItem->zName = pFKey->pFrom->zName;
   73605       pItem->pTab->nRef++;
   73606       pItem->iCursor = pParse->nTab++;
   73607 
   73608       if( regNew!=0 ){
   73609         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
   73610       }
   73611       if( regOld!=0 ){
   73612         /* If there is a RESTRICT action configured for the current operation
   73613         ** on the parent table of this FK, then throw an exception
   73614         ** immediately if the FK constraint is violated, even if this is a
   73615         ** deferred trigger. That's what RESTRICT means. To defer checking
   73616         ** the constraint, the FK should specify NO ACTION (represented
   73617         ** using OE_None). NO ACTION is the default.  */
   73618         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
   73619       }
   73620       pItem->zName = 0;
   73621       sqlite3SrcListDelete(db, pSrc);
   73622     }
   73623     sqlite3DbFree(db, aiCol);
   73624   }
   73625 }
   73626 
   73627 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
   73628 
   73629 /*
   73630 ** This function is called before generating code to update or delete a
   73631 ** row contained in table pTab.
   73632 */
   73633 SQLITE_PRIVATE u32 sqlite3FkOldmask(
   73634   Parse *pParse,                  /* Parse context */
   73635   Table *pTab                     /* Table being modified */
   73636 ){
   73637   u32 mask = 0;
   73638   if( pParse->db->flags&SQLITE_ForeignKeys ){
   73639     FKey *p;
   73640     int i;
   73641     for(p=pTab->pFKey; p; p=p->pNextFrom){
   73642       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
   73643     }
   73644     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   73645       Index *pIdx = 0;
   73646       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
   73647       if( pIdx ){
   73648         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
   73649       }
   73650     }
   73651   }
   73652   return mask;
   73653 }
   73654 
   73655 /*
   73656 ** This function is called before generating code to update or delete a
   73657 ** row contained in table pTab. If the operation is a DELETE, then
   73658 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
   73659 ** to an array of size N, where N is the number of columns in table pTab.
   73660 ** If the i'th column is not modified by the UPDATE, then the corresponding
   73661 ** entry in the aChange[] array is set to -1. If the column is modified,
   73662 ** the value is 0 or greater. Parameter chngRowid is set to true if the
   73663 ** UPDATE statement modifies the rowid fields of the table.
   73664 **
   73665 ** If any foreign key processing will be required, this function returns
   73666 ** true. If there is no foreign key related processing, this function
   73667 ** returns false.
   73668 */
   73669 SQLITE_PRIVATE int sqlite3FkRequired(
   73670   Parse *pParse,                  /* Parse context */
   73671   Table *pTab,                    /* Table being modified */
   73672   int *aChange,                   /* Non-NULL for UPDATE operations */
   73673   int chngRowid                   /* True for UPDATE that affects rowid */
   73674 ){
   73675   if( pParse->db->flags&SQLITE_ForeignKeys ){
   73676     if( !aChange ){
   73677       /* A DELETE operation. Foreign key processing is required if the
   73678       ** table in question is either the child or parent table for any
   73679       ** foreign key constraint.  */
   73680       return (sqlite3FkReferences(pTab) || pTab->pFKey);
   73681     }else{
   73682       /* This is an UPDATE. Foreign key processing is only required if the
   73683       ** operation modifies one or more child or parent key columns. */
   73684       int i;
   73685       FKey *p;
   73686 
   73687       /* Check if any child key columns are being modified. */
   73688       for(p=pTab->pFKey; p; p=p->pNextFrom){
   73689         for(i=0; i<p->nCol; i++){
   73690           int iChildKey = p->aCol[i].iFrom;
   73691           if( aChange[iChildKey]>=0 ) return 1;
   73692           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
   73693         }
   73694       }
   73695 
   73696       /* Check if any parent key columns are being modified. */
   73697       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   73698         for(i=0; i<p->nCol; i++){
   73699           char *zKey = p->aCol[i].zCol;
   73700           int iKey;
   73701           for(iKey=0; iKey<pTab->nCol; iKey++){
   73702             Column *pCol = &pTab->aCol[iKey];
   73703             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
   73704               if( aChange[iKey]>=0 ) return 1;
   73705               if( iKey==pTab->iPKey && chngRowid ) return 1;
   73706             }
   73707           }
   73708         }
   73709       }
   73710     }
   73711   }
   73712   return 0;
   73713 }
   73714 
   73715 /*
   73716 ** This function is called when an UPDATE or DELETE operation is being
   73717 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
   73718 ** If the current operation is an UPDATE, then the pChanges parameter is
   73719 ** passed a pointer to the list of columns being modified. If it is a
   73720 ** DELETE, pChanges is passed a NULL pointer.
   73721 **
   73722 ** It returns a pointer to a Trigger structure containing a trigger
   73723 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
   73724 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
   73725 ** returned (these actions require no special handling by the triggers
   73726 ** sub-system, code for them is created by fkScanChildren()).
   73727 **
   73728 ** For example, if pFKey is the foreign key and pTab is table "p" in
   73729 ** the following schema:
   73730 **
   73731 **   CREATE TABLE p(pk PRIMARY KEY);
   73732 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
   73733 **
   73734 ** then the returned trigger structure is equivalent to:
   73735 **
   73736 **   CREATE TRIGGER ... DELETE ON p BEGIN
   73737 **     DELETE FROM c WHERE ck = old.pk;
   73738 **   END;
   73739 **
   73740 ** The returned pointer is cached as part of the foreign key object. It
   73741 ** is eventually freed along with the rest of the foreign key object by
   73742 ** sqlite3FkDelete().
   73743 */
   73744 static Trigger *fkActionTrigger(
   73745   Parse *pParse,                  /* Parse context */
   73746   Table *pTab,                    /* Table being updated or deleted from */
   73747   FKey *pFKey,                    /* Foreign key to get action for */
   73748   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
   73749 ){
   73750   sqlite3 *db = pParse->db;       /* Database handle */
   73751   int action;                     /* One of OE_None, OE_Cascade etc. */
   73752   Trigger *pTrigger;              /* Trigger definition to return */
   73753   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
   73754 
   73755   action = pFKey->aAction[iAction];
   73756   pTrigger = pFKey->apTrigger[iAction];
   73757 
   73758   if( action!=OE_None && !pTrigger ){
   73759     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
   73760     char const *zFrom;            /* Name of child table */
   73761     int nFrom;                    /* Length in bytes of zFrom */
   73762     Index *pIdx = 0;              /* Parent key index for this FK */
   73763     int *aiCol = 0;               /* child table cols -> parent key cols */
   73764     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
   73765     Expr *pWhere = 0;             /* WHERE clause of trigger step */
   73766     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
   73767     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
   73768     int i;                        /* Iterator variable */
   73769     Expr *pWhen = 0;              /* WHEN clause for the trigger */
   73770 
   73771     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
   73772     assert( aiCol || pFKey->nCol==1 );
   73773 
   73774     for(i=0; i<pFKey->nCol; i++){
   73775       Token tOld = { "old", 3 };  /* Literal "old" token */
   73776       Token tNew = { "new", 3 };  /* Literal "new" token */
   73777       Token tFromCol;             /* Name of column in child table */
   73778       Token tToCol;               /* Name of column in parent table */
   73779       int iFromCol;               /* Idx of column in child table */
   73780       Expr *pEq;                  /* tFromCol = OLD.tToCol */
   73781 
   73782       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
   73783       assert( iFromCol>=0 );
   73784       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
   73785       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
   73786 
   73787       tToCol.n = sqlite3Strlen30(tToCol.z);
   73788       tFromCol.n = sqlite3Strlen30(tFromCol.z);
   73789 
   73790       /* Create the expression "OLD.zToCol = zFromCol". It is important
   73791       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
   73792       ** that the affinity and collation sequence associated with the
   73793       ** parent table are used for the comparison. */
   73794       pEq = sqlite3PExpr(pParse, TK_EQ,
   73795           sqlite3PExpr(pParse, TK_DOT,
   73796             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
   73797             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
   73798           , 0),
   73799           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
   73800       , 0);
   73801       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   73802 
   73803       /* For ON UPDATE, construct the next term of the WHEN clause.
   73804       ** The final WHEN clause will be like this:
   73805       **
   73806       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
   73807       */
   73808       if( pChanges ){
   73809         pEq = sqlite3PExpr(pParse, TK_IS,
   73810             sqlite3PExpr(pParse, TK_DOT,
   73811               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
   73812               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
   73813               0),
   73814             sqlite3PExpr(pParse, TK_DOT,
   73815               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
   73816               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
   73817               0),
   73818             0);
   73819         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
   73820       }
   73821 
   73822       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
   73823         Expr *pNew;
   73824         if( action==OE_Cascade ){
   73825           pNew = sqlite3PExpr(pParse, TK_DOT,
   73826             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
   73827             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
   73828           , 0);
   73829         }else if( action==OE_SetDflt ){
   73830           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
   73831           if( pDflt ){
   73832             pNew = sqlite3ExprDup(db, pDflt, 0);
   73833           }else{
   73834             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
   73835           }
   73836         }else{
   73837           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
   73838         }
   73839         pList = sqlite3ExprListAppend(pParse, pList, pNew);
   73840         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
   73841       }
   73842     }
   73843     sqlite3DbFree(db, aiCol);
   73844 
   73845     zFrom = pFKey->pFrom->zName;
   73846     nFrom = sqlite3Strlen30(zFrom);
   73847 
   73848     if( action==OE_Restrict ){
   73849       Token tFrom;
   73850       Expr *pRaise;
   73851 
   73852       tFrom.z = zFrom;
   73853       tFrom.n = nFrom;
   73854       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
   73855       if( pRaise ){
   73856         pRaise->affinity = OE_Abort;
   73857       }
   73858       pSelect = sqlite3SelectNew(pParse,
   73859           sqlite3ExprListAppend(pParse, 0, pRaise),
   73860           sqlite3SrcListAppend(db, 0, &tFrom, 0),
   73861           pWhere,
   73862           0, 0, 0, 0, 0, 0
   73863       );
   73864       pWhere = 0;
   73865     }
   73866 
   73867     /* In the current implementation, pTab->dbMem==0 for all tables except
   73868     ** for temporary tables used to describe subqueries.  And temporary
   73869     ** tables do not have foreign key constraints.  Hence, pTab->dbMem
   73870     ** should always be 0 there.
   73871     */
   73872     enableLookaside = db->lookaside.bEnabled;
   73873     db->lookaside.bEnabled = 0;
   73874 
   73875     pTrigger = (Trigger *)sqlite3DbMallocZero(db,
   73876         sizeof(Trigger) +         /* struct Trigger */
   73877         sizeof(TriggerStep) +     /* Single step in trigger program */
   73878         nFrom + 1                 /* Space for pStep->target.z */
   73879     );
   73880     if( pTrigger ){
   73881       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
   73882       pStep->target.z = (char *)&pStep[1];
   73883       pStep->target.n = nFrom;
   73884       memcpy((char *)pStep->target.z, zFrom, nFrom);
   73885 
   73886       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   73887       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
   73888       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   73889       if( pWhen ){
   73890         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
   73891         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
   73892       }
   73893     }
   73894 
   73895     /* Re-enable the lookaside buffer, if it was disabled earlier. */
   73896     db->lookaside.bEnabled = enableLookaside;
   73897 
   73898     sqlite3ExprDelete(db, pWhere);
   73899     sqlite3ExprDelete(db, pWhen);
   73900     sqlite3ExprListDelete(db, pList);
   73901     sqlite3SelectDelete(db, pSelect);
   73902     if( db->mallocFailed==1 ){
   73903       fkTriggerDelete(db, pTrigger);
   73904       return 0;
   73905     }
   73906 
   73907     switch( action ){
   73908       case OE_Restrict:
   73909         pStep->op = TK_SELECT;
   73910         break;
   73911       case OE_Cascade:
   73912         if( !pChanges ){
   73913           pStep->op = TK_DELETE;
   73914           break;
   73915         }
   73916       default:
   73917         pStep->op = TK_UPDATE;
   73918     }
   73919     pStep->pTrig = pTrigger;
   73920     pTrigger->pSchema = pTab->pSchema;
   73921     pTrigger->pTabSchema = pTab->pSchema;
   73922     pFKey->apTrigger[iAction] = pTrigger;
   73923     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
   73924   }
   73925 
   73926   return pTrigger;
   73927 }
   73928 
   73929 /*
   73930 ** This function is called when deleting or updating a row to implement
   73931 ** any required CASCADE, SET NULL or SET DEFAULT actions.
   73932 */
   73933 SQLITE_PRIVATE void sqlite3FkActions(
   73934   Parse *pParse,                  /* Parse context */
   73935   Table *pTab,                    /* Table being updated or deleted from */
   73936   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
   73937   int regOld                      /* Address of array containing old row */
   73938 ){
   73939   /* If foreign-key support is enabled, iterate through all FKs that
   73940   ** refer to table pTab. If there is an action associated with the FK
   73941   ** for this operation (either update or delete), invoke the associated
   73942   ** trigger sub-program.  */
   73943   if( pParse->db->flags&SQLITE_ForeignKeys ){
   73944     FKey *pFKey;                  /* Iterator variable */
   73945     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
   73946       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
   73947       if( pAction ){
   73948         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
   73949       }
   73950     }
   73951   }
   73952 }
   73953 
   73954 #endif /* ifndef SQLITE_OMIT_TRIGGER */
   73955 
   73956 /*
   73957 ** Free all memory associated with foreign key definitions attached to
   73958 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
   73959 ** hash table.
   73960 */
   73961 SQLITE_PRIVATE void sqlite3FkDelete(Table *pTab){
   73962   FKey *pFKey;                    /* Iterator variable */
   73963   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
   73964 
   73965   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
   73966 
   73967     /* Remove the FK from the fkeyHash hash table. */
   73968     if( pFKey->pPrevTo ){
   73969       pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
   73970     }else{
   73971       void *data = (void *)pFKey->pNextTo;
   73972       const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
   73973       sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
   73974     }
   73975     if( pFKey->pNextTo ){
   73976       pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
   73977     }
   73978 
   73979     /* Delete any triggers created to implement actions for this FK. */
   73980 #ifndef SQLITE_OMIT_TRIGGER
   73981     fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
   73982     fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
   73983 #endif
   73984 
   73985     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
   73986     ** classified as either immediate or deferred.
   73987     */
   73988     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
   73989 
   73990     pNext = pFKey->pNextFrom;
   73991     sqlite3DbFree(pTab->dbMem, pFKey);
   73992   }
   73993 }
   73994 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
   73995 
   73996 /************** End of fkey.c ************************************************/
   73997 /************** Begin file insert.c ******************************************/
   73998 /*
   73999 ** 2001 September 15
   74000 **
   74001 ** The author disclaims copyright to this source code.  In place of
   74002 ** a legal notice, here is a blessing:
   74003 **
   74004 **    May you do good and not evil.
   74005 **    May you find forgiveness for yourself and forgive others.
   74006 **    May you share freely, never taking more than you give.
   74007 **
   74008 *************************************************************************
   74009 ** This file contains C code routines that are called by the parser
   74010 ** to handle INSERT statements in SQLite.
   74011 */
   74012 
   74013 /*
   74014 ** Generate code that will open a table for reading.
   74015 */
   74016 SQLITE_PRIVATE void sqlite3OpenTable(
   74017   Parse *p,       /* Generate code into this VDBE */
   74018   int iCur,       /* The cursor number of the table */
   74019   int iDb,        /* The database index in sqlite3.aDb[] */
   74020   Table *pTab,    /* The table to be opened */
   74021   int opcode      /* OP_OpenRead or OP_OpenWrite */
   74022 ){
   74023   Vdbe *v;
   74024   if( IsVirtual(pTab) ) return;
   74025   v = sqlite3GetVdbe(p);
   74026   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
   74027   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
   74028   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
   74029   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
   74030   VdbeComment((v, "%s", pTab->zName));
   74031 }
   74032 
   74033 /*
   74034 ** Return a pointer to the column affinity string associated with index
   74035 ** pIdx. A column affinity string has one character for each column in
   74036 ** the table, according to the affinity of the column:
   74037 **
   74038 **  Character      Column affinity
   74039 **  ------------------------------
   74040 **  'a'            TEXT
   74041 **  'b'            NONE
   74042 **  'c'            NUMERIC
   74043 **  'd'            INTEGER
   74044 **  'e'            REAL
   74045 **
   74046 ** An extra 'b' is appended to the end of the string to cover the
   74047 ** rowid that appears as the last column in every index.
   74048 **
   74049 ** Memory for the buffer containing the column index affinity string
   74050 ** is managed along with the rest of the Index structure. It will be
   74051 ** released when sqlite3DeleteIndex() is called.
   74052 */
   74053 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
   74054   if( !pIdx->zColAff ){
   74055     /* The first time a column affinity string for a particular index is
   74056     ** required, it is allocated and populated here. It is then stored as
   74057     ** a member of the Index structure for subsequent use.
   74058     **
   74059     ** The column affinity string will eventually be deleted by
   74060     ** sqliteDeleteIndex() when the Index structure itself is cleaned
   74061     ** up.
   74062     */
   74063     int n;
   74064     Table *pTab = pIdx->pTable;
   74065     sqlite3 *db = sqlite3VdbeDb(v);
   74066     pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
   74067     if( !pIdx->zColAff ){
   74068       db->mallocFailed = 1;
   74069       return 0;
   74070     }
   74071     for(n=0; n<pIdx->nColumn; n++){
   74072       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
   74073     }
   74074     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
   74075     pIdx->zColAff[n] = 0;
   74076   }
   74077 
   74078   return pIdx->zColAff;
   74079 }
   74080 
   74081 /*
   74082 ** Set P4 of the most recently inserted opcode to a column affinity
   74083 ** string for table pTab. A column affinity string has one character
   74084 ** for each column indexed by the index, according to the affinity of the
   74085 ** column:
   74086 **
   74087 **  Character      Column affinity
   74088 **  ------------------------------
   74089 **  'a'            TEXT
   74090 **  'b'            NONE
   74091 **  'c'            NUMERIC
   74092 **  'd'            INTEGER
   74093 **  'e'            REAL
   74094 */
   74095 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
   74096   /* The first time a column affinity string for a particular table
   74097   ** is required, it is allocated and populated here. It is then
   74098   ** stored as a member of the Table structure for subsequent use.
   74099   **
   74100   ** The column affinity string will eventually be deleted by
   74101   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
   74102   */
   74103   if( !pTab->zColAff ){
   74104     char *zColAff;
   74105     int i;
   74106     sqlite3 *db = sqlite3VdbeDb(v);
   74107 
   74108     zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
   74109     if( !zColAff ){
   74110       db->mallocFailed = 1;
   74111       return;
   74112     }
   74113 
   74114     for(i=0; i<pTab->nCol; i++){
   74115       zColAff[i] = pTab->aCol[i].affinity;
   74116     }
   74117     zColAff[pTab->nCol] = '\0';
   74118 
   74119     pTab->zColAff = zColAff;
   74120   }
   74121 
   74122   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
   74123 }
   74124 
   74125 /*
   74126 ** Return non-zero if the table pTab in database iDb or any of its indices
   74127 ** have been opened at any point in the VDBE program beginning at location
   74128 ** iStartAddr throught the end of the program.  This is used to see if
   74129 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
   74130 ** run without using temporary table for the results of the SELECT.
   74131 */
   74132 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
   74133   Vdbe *v = sqlite3GetVdbe(p);
   74134   int i;
   74135   int iEnd = sqlite3VdbeCurrentAddr(v);
   74136 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74137   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
   74138 #endif
   74139 
   74140   for(i=iStartAddr; i<iEnd; i++){
   74141     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
   74142     assert( pOp!=0 );
   74143     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
   74144       Index *pIndex;
   74145       int tnum = pOp->p2;
   74146       if( tnum==pTab->tnum ){
   74147         return 1;
   74148       }
   74149       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
   74150         if( tnum==pIndex->tnum ){
   74151           return 1;
   74152         }
   74153       }
   74154     }
   74155 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74156     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
   74157       assert( pOp->p4.pVtab!=0 );
   74158       assert( pOp->p4type==P4_VTAB );
   74159       return 1;
   74160     }
   74161 #endif
   74162   }
   74163   return 0;
   74164 }
   74165 
   74166 #ifndef SQLITE_OMIT_AUTOINCREMENT
   74167 /*
   74168 ** Locate or create an AutoincInfo structure associated with table pTab
   74169 ** which is in database iDb.  Return the register number for the register
   74170 ** that holds the maximum rowid.
   74171 **
   74172 ** There is at most one AutoincInfo structure per table even if the
   74173 ** same table is autoincremented multiple times due to inserts within
   74174 ** triggers.  A new AutoincInfo structure is created if this is the
   74175 ** first use of table pTab.  On 2nd and subsequent uses, the original
   74176 ** AutoincInfo structure is used.
   74177 **
   74178 ** Three memory locations are allocated:
   74179 **
   74180 **   (1)  Register to hold the name of the pTab table.
   74181 **   (2)  Register to hold the maximum ROWID of pTab.
   74182 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
   74183 **
   74184 ** The 2nd register is the one that is returned.  That is all the
   74185 ** insert routine needs to know about.
   74186 */
   74187 static int autoIncBegin(
   74188   Parse *pParse,      /* Parsing context */
   74189   int iDb,            /* Index of the database holding pTab */
   74190   Table *pTab         /* The table we are writing to */
   74191 ){
   74192   int memId = 0;      /* Register holding maximum rowid */
   74193   if( pTab->tabFlags & TF_Autoincrement ){
   74194     Parse *pToplevel = sqlite3ParseToplevel(pParse);
   74195     AutoincInfo *pInfo;
   74196 
   74197     pInfo = pToplevel->pAinc;
   74198     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
   74199     if( pInfo==0 ){
   74200       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
   74201       if( pInfo==0 ) return 0;
   74202       pInfo->pNext = pToplevel->pAinc;
   74203       pToplevel->pAinc = pInfo;
   74204       pInfo->pTab = pTab;
   74205       pInfo->iDb = iDb;
   74206       pToplevel->nMem++;                  /* Register to hold name of table */
   74207       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
   74208       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
   74209     }
   74210     memId = pInfo->regCtr;
   74211   }
   74212   return memId;
   74213 }
   74214 
   74215 /*
   74216 ** This routine generates code that will initialize all of the
   74217 ** register used by the autoincrement tracker.
   74218 */
   74219 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
   74220   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
   74221   sqlite3 *db = pParse->db;  /* The database connection */
   74222   Db *pDb;                   /* Database only autoinc table */
   74223   int memId;                 /* Register holding max rowid */
   74224   int addr;                  /* A VDBE address */
   74225   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
   74226 
   74227   /* This routine is never called during trigger-generation.  It is
   74228   ** only called from the top-level */
   74229   assert( pParse->pTriggerTab==0 );
   74230   assert( pParse==sqlite3ParseToplevel(pParse) );
   74231 
   74232   assert( v );   /* We failed long ago if this is not so */
   74233   for(p = pParse->pAinc; p; p = p->pNext){
   74234     pDb = &db->aDb[p->iDb];
   74235     memId = p->regCtr;
   74236     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
   74237     addr = sqlite3VdbeCurrentAddr(v);
   74238     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
   74239     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
   74240     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
   74241     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
   74242     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   74243     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
   74244     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
   74245     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
   74246     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
   74247     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
   74248     sqlite3VdbeAddOp0(v, OP_Close);
   74249   }
   74250 }
   74251 
   74252 /*
   74253 ** Update the maximum rowid for an autoincrement calculation.
   74254 **
   74255 ** This routine should be called when the top of the stack holds a
   74256 ** new rowid that is about to be inserted.  If that new rowid is
   74257 ** larger than the maximum rowid in the memId memory cell, then the
   74258 ** memory cell is updated.  The stack is unchanged.
   74259 */
   74260 static void autoIncStep(Parse *pParse, int memId, int regRowid){
   74261   if( memId>0 ){
   74262     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
   74263   }
   74264 }
   74265 
   74266 /*
   74267 ** This routine generates the code needed to write autoincrement
   74268 ** maximum rowid values back into the sqlite_sequence register.
   74269 ** Every statement that might do an INSERT into an autoincrement
   74270 ** table (either directly or through triggers) needs to call this
   74271 ** routine just before the "exit" code.
   74272 */
   74273 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
   74274   AutoincInfo *p;
   74275   Vdbe *v = pParse->pVdbe;
   74276   sqlite3 *db = pParse->db;
   74277 
   74278   assert( v );
   74279   for(p = pParse->pAinc; p; p = p->pNext){
   74280     Db *pDb = &db->aDb[p->iDb];
   74281     int j1, j2, j3, j4, j5;
   74282     int iRec;
   74283     int memId = p->regCtr;
   74284 
   74285     iRec = sqlite3GetTempReg(pParse);
   74286     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
   74287     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
   74288     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
   74289     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
   74290     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
   74291     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
   74292     sqlite3VdbeJumpHere(v, j2);
   74293     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
   74294     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
   74295     sqlite3VdbeJumpHere(v, j4);
   74296     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
   74297     sqlite3VdbeJumpHere(v, j1);
   74298     sqlite3VdbeJumpHere(v, j5);
   74299     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
   74300     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
   74301     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   74302     sqlite3VdbeAddOp0(v, OP_Close);
   74303     sqlite3ReleaseTempReg(pParse, iRec);
   74304   }
   74305 }
   74306 #else
   74307 /*
   74308 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
   74309 ** above are all no-ops
   74310 */
   74311 # define autoIncBegin(A,B,C) (0)
   74312 # define autoIncStep(A,B,C)
   74313 #endif /* SQLITE_OMIT_AUTOINCREMENT */
   74314 
   74315 
   74316 /* Forward declaration */
   74317 static int xferOptimization(
   74318   Parse *pParse,        /* Parser context */
   74319   Table *pDest,         /* The table we are inserting into */
   74320   Select *pSelect,      /* A SELECT statement to use as the data source */
   74321   int onError,          /* How to handle constraint errors */
   74322   int iDbDest           /* The database of pDest */
   74323 );
   74324 
   74325 /*
   74326 ** This routine is call to handle SQL of the following forms:
   74327 **
   74328 **    insert into TABLE (IDLIST) values(EXPRLIST)
   74329 **    insert into TABLE (IDLIST) select
   74330 **
   74331 ** The IDLIST following the table name is always optional.  If omitted,
   74332 ** then a list of all columns for the table is substituted.  The IDLIST
   74333 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
   74334 **
   74335 ** The pList parameter holds EXPRLIST in the first form of the INSERT
   74336 ** statement above, and pSelect is NULL.  For the second form, pList is
   74337 ** NULL and pSelect is a pointer to the select statement used to generate
   74338 ** data for the insert.
   74339 **
   74340 ** The code generated follows one of four templates.  For a simple
   74341 ** select with data coming from a VALUES clause, the code executes
   74342 ** once straight down through.  Pseudo-code follows (we call this
   74343 ** the "1st template"):
   74344 **
   74345 **         open write cursor to <table> and its indices
   74346 **         puts VALUES clause expressions onto the stack
   74347 **         write the resulting record into <table>
   74348 **         cleanup
   74349 **
   74350 ** The three remaining templates assume the statement is of the form
   74351 **
   74352 **   INSERT INTO <table> SELECT ...
   74353 **
   74354 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
   74355 ** in other words if the SELECT pulls all columns from a single table
   74356 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
   74357 ** if <table2> and <table1> are distinct tables but have identical
   74358 ** schemas, including all the same indices, then a special optimization
   74359 ** is invoked that copies raw records from <table2> over to <table1>.
   74360 ** See the xferOptimization() function for the implementation of this
   74361 ** template.  This is the 2nd template.
   74362 **
   74363 **         open a write cursor to <table>
   74364 **         open read cursor on <table2>
   74365 **         transfer all records in <table2> over to <table>
   74366 **         close cursors
   74367 **         foreach index on <table>
   74368 **           open a write cursor on the <table> index
   74369 **           open a read cursor on the corresponding <table2> index
   74370 **           transfer all records from the read to the write cursors
   74371 **           close cursors
   74372 **         end foreach
   74373 **
   74374 ** The 3rd template is for when the second template does not apply
   74375 ** and the SELECT clause does not read from <table> at any time.
   74376 ** The generated code follows this template:
   74377 **
   74378 **         EOF <- 0
   74379 **         X <- A
   74380 **         goto B
   74381 **      A: setup for the SELECT
   74382 **         loop over the rows in the SELECT
   74383 **           load values into registers R..R+n
   74384 **           yield X
   74385 **         end loop
   74386 **         cleanup after the SELECT
   74387 **         EOF <- 1
   74388 **         yield X
   74389 **         goto A
   74390 **      B: open write cursor to <table> and its indices
   74391 **      C: yield X
   74392 **         if EOF goto D
   74393 **         insert the select result into <table> from R..R+n
   74394 **         goto C
   74395 **      D: cleanup
   74396 **
   74397 ** The 4th template is used if the insert statement takes its
   74398 ** values from a SELECT but the data is being inserted into a table
   74399 ** that is also read as part of the SELECT.  In the third form,
   74400 ** we have to use a intermediate table to store the results of
   74401 ** the select.  The template is like this:
   74402 **
   74403 **         EOF <- 0
   74404 **         X <- A
   74405 **         goto B
   74406 **      A: setup for the SELECT
   74407 **         loop over the tables in the SELECT
   74408 **           load value into register R..R+n
   74409 **           yield X
   74410 **         end loop
   74411 **         cleanup after the SELECT
   74412 **         EOF <- 1
   74413 **         yield X
   74414 **         halt-error
   74415 **      B: open temp table
   74416 **      L: yield X
   74417 **         if EOF goto M
   74418 **         insert row from R..R+n into temp table
   74419 **         goto L
   74420 **      M: open write cursor to <table> and its indices
   74421 **         rewind temp table
   74422 **      C: loop over rows of intermediate table
   74423 **           transfer values form intermediate table into <table>
   74424 **         end loop
   74425 **      D: cleanup
   74426 */
   74427 SQLITE_PRIVATE void sqlite3Insert(
   74428   Parse *pParse,        /* Parser context */
   74429   SrcList *pTabList,    /* Name of table into which we are inserting */
   74430   ExprList *pList,      /* List of values to be inserted */
   74431   Select *pSelect,      /* A SELECT statement to use as the data source */
   74432   IdList *pColumn,      /* Column names corresponding to IDLIST. */
   74433   int onError           /* How to handle constraint errors */
   74434 ){
   74435   sqlite3 *db;          /* The main database structure */
   74436   Table *pTab;          /* The table to insert into.  aka TABLE */
   74437   char *zTab;           /* Name of the table into which we are inserting */
   74438   const char *zDb;      /* Name of the database holding this table */
   74439   int i, j, idx;        /* Loop counters */
   74440   Vdbe *v;              /* Generate code into this virtual machine */
   74441   Index *pIdx;          /* For looping over indices of the table */
   74442   int nColumn;          /* Number of columns in the data */
   74443   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
   74444   int baseCur = 0;      /* VDBE Cursor number for pTab */
   74445   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
   74446   int endOfLoop;        /* Label for the end of the insertion loop */
   74447   int useTempTable = 0; /* Store SELECT results in intermediate table */
   74448   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
   74449   int addrInsTop = 0;   /* Jump to label "D" */
   74450   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
   74451   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
   74452   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
   74453   int iDb;              /* Index of database holding TABLE */
   74454   Db *pDb;              /* The database containing table being inserted into */
   74455   int appendFlag = 0;   /* True if the insert is likely to be an append */
   74456 
   74457   /* Register allocations */
   74458   int regFromSelect = 0;/* Base register for data coming from SELECT */
   74459   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
   74460   int regRowCount = 0;  /* Memory cell used for the row counter */
   74461   int regIns;           /* Block of regs holding rowid+data being inserted */
   74462   int regRowid;         /* registers holding insert rowid */
   74463   int regData;          /* register holding first column to insert */
   74464   int regRecord;        /* Holds the assemblied row record */
   74465   int regEof = 0;       /* Register recording end of SELECT data */
   74466   int *aRegIdx = 0;     /* One register allocated to each index */
   74467 
   74468 #ifndef SQLITE_OMIT_TRIGGER
   74469   int isView;                 /* True if attempting to insert into a view */
   74470   Trigger *pTrigger;          /* List of triggers on pTab, if required */
   74471   int tmask;                  /* Mask of trigger times */
   74472 #endif
   74473 
   74474   db = pParse->db;
   74475   memset(&dest, 0, sizeof(dest));
   74476   if( pParse->nErr || db->mallocFailed ){
   74477     goto insert_cleanup;
   74478   }
   74479 
   74480   /* Locate the table into which we will be inserting new information.
   74481   */
   74482   assert( pTabList->nSrc==1 );
   74483   zTab = pTabList->a[0].zName;
   74484   if( NEVER(zTab==0) ) goto insert_cleanup;
   74485   pTab = sqlite3SrcListLookup(pParse, pTabList);
   74486   if( pTab==0 ){
   74487     goto insert_cleanup;
   74488   }
   74489   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   74490   assert( iDb<db->nDb );
   74491   pDb = &db->aDb[iDb];
   74492   zDb = pDb->zName;
   74493   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
   74494     goto insert_cleanup;
   74495   }
   74496 
   74497   /* Figure out if we have any triggers and if the table being
   74498   ** inserted into is a view
   74499   */
   74500 #ifndef SQLITE_OMIT_TRIGGER
   74501   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
   74502   isView = pTab->pSelect!=0;
   74503 #else
   74504 # define pTrigger 0
   74505 # define tmask 0
   74506 # define isView 0
   74507 #endif
   74508 #ifdef SQLITE_OMIT_VIEW
   74509 # undef isView
   74510 # define isView 0
   74511 #endif
   74512   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
   74513 
   74514   /* If pTab is really a view, make sure it has been initialized.
   74515   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
   74516   ** module table).
   74517   */
   74518   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   74519     goto insert_cleanup;
   74520   }
   74521 
   74522   /* Ensure that:
   74523   *  (a) the table is not read-only,
   74524   *  (b) that if it is a view then ON INSERT triggers exist
   74525   */
   74526   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
   74527     goto insert_cleanup;
   74528   }
   74529 
   74530   /* Allocate a VDBE
   74531   */
   74532   v = sqlite3GetVdbe(pParse);
   74533   if( v==0 ) goto insert_cleanup;
   74534   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   74535   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
   74536 
   74537 #ifndef SQLITE_OMIT_XFER_OPT
   74538   /* If the statement is of the form
   74539   **
   74540   **       INSERT INTO <table1> SELECT * FROM <table2>;
   74541   **
   74542   ** Then special optimizations can be applied that make the transfer
   74543   ** very fast and which reduce fragmentation of indices.
   74544   **
   74545   ** This is the 2nd template.
   74546   */
   74547   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
   74548     assert( !pTrigger );
   74549     assert( pList==0 );
   74550     goto insert_end;
   74551   }
   74552 #endif /* SQLITE_OMIT_XFER_OPT */
   74553 
   74554   /* If this is an AUTOINCREMENT table, look up the sequence number in the
   74555   ** sqlite_sequence table and store it in memory cell regAutoinc.
   74556   */
   74557   regAutoinc = autoIncBegin(pParse, iDb, pTab);
   74558 
   74559   /* Figure out how many columns of data are supplied.  If the data
   74560   ** is coming from a SELECT statement, then generate a co-routine that
   74561   ** produces a single row of the SELECT on each invocation.  The
   74562   ** co-routine is the common header to the 3rd and 4th templates.
   74563   */
   74564   if( pSelect ){
   74565     /* Data is coming from a SELECT.  Generate code to implement that SELECT
   74566     ** as a co-routine.  The code is common to both the 3rd and 4th
   74567     ** templates:
   74568     **
   74569     **         EOF <- 0
   74570     **         X <- A
   74571     **         goto B
   74572     **      A: setup for the SELECT
   74573     **         loop over the tables in the SELECT
   74574     **           load value into register R..R+n
   74575     **           yield X
   74576     **         end loop
   74577     **         cleanup after the SELECT
   74578     **         EOF <- 1
   74579     **         yield X
   74580     **         halt-error
   74581     **
   74582     ** On each invocation of the co-routine, it puts a single row of the
   74583     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
   74584     ** (These output registers are allocated by sqlite3Select().)  When
   74585     ** the SELECT completes, it sets the EOF flag stored in regEof.
   74586     */
   74587     int rc, j1;
   74588 
   74589     regEof = ++pParse->nMem;
   74590     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
   74591     VdbeComment((v, "SELECT eof flag"));
   74592     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
   74593     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
   74594     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
   74595     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
   74596     VdbeComment((v, "Jump over SELECT coroutine"));
   74597 
   74598     /* Resolve the expressions in the SELECT statement and execute it. */
   74599     rc = sqlite3Select(pParse, pSelect, &dest);
   74600     assert( pParse->nErr==0 || rc );
   74601     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
   74602       goto insert_cleanup;
   74603     }
   74604     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
   74605     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
   74606     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
   74607     VdbeComment((v, "End of SELECT coroutine"));
   74608     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
   74609 
   74610     regFromSelect = dest.iMem;
   74611     assert( pSelect->pEList );
   74612     nColumn = pSelect->pEList->nExpr;
   74613     assert( dest.nMem==nColumn );
   74614 
   74615     /* Set useTempTable to TRUE if the result of the SELECT statement
   74616     ** should be written into a temporary table (template 4).  Set to
   74617     ** FALSE if each* row of the SELECT can be written directly into
   74618     ** the destination table (template 3).
   74619     **
   74620     ** A temp table must be used if the table being updated is also one
   74621     ** of the tables being read by the SELECT statement.  Also use a
   74622     ** temp table in the case of row triggers.
   74623     */
   74624     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
   74625       useTempTable = 1;
   74626     }
   74627 
   74628     if( useTempTable ){
   74629       /* Invoke the coroutine to extract information from the SELECT
   74630       ** and add it to a transient table srcTab.  The code generated
   74631       ** here is from the 4th template:
   74632       **
   74633       **      B: open temp table
   74634       **      L: yield X
   74635       **         if EOF goto M
   74636       **         insert row from R..R+n into temp table
   74637       **         goto L
   74638       **      M: ...
   74639       */
   74640       int regRec;          /* Register to hold packed record */
   74641       int regTempRowid;    /* Register to hold temp table ROWID */
   74642       int addrTop;         /* Label "L" */
   74643       int addrIf;          /* Address of jump to M */
   74644 
   74645       srcTab = pParse->nTab++;
   74646       regRec = sqlite3GetTempReg(pParse);
   74647       regTempRowid = sqlite3GetTempReg(pParse);
   74648       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
   74649       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
   74650       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
   74651       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
   74652       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
   74653       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
   74654       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
   74655       sqlite3VdbeJumpHere(v, addrIf);
   74656       sqlite3ReleaseTempReg(pParse, regRec);
   74657       sqlite3ReleaseTempReg(pParse, regTempRowid);
   74658     }
   74659   }else{
   74660     /* This is the case if the data for the INSERT is coming from a VALUES
   74661     ** clause
   74662     */
   74663     NameContext sNC;
   74664     memset(&sNC, 0, sizeof(sNC));
   74665     sNC.pParse = pParse;
   74666     srcTab = -1;
   74667     assert( useTempTable==0 );
   74668     nColumn = pList ? pList->nExpr : 0;
   74669     for(i=0; i<nColumn; i++){
   74670       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
   74671         goto insert_cleanup;
   74672       }
   74673     }
   74674   }
   74675 
   74676   /* Make sure the number of columns in the source data matches the number
   74677   ** of columns to be inserted into the table.
   74678   */
   74679   if( IsVirtual(pTab) ){
   74680     for(i=0; i<pTab->nCol; i++){
   74681       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
   74682     }
   74683   }
   74684   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
   74685     sqlite3ErrorMsg(pParse,
   74686        "table %S has %d columns but %d values were supplied",
   74687        pTabList, 0, pTab->nCol-nHidden, nColumn);
   74688     goto insert_cleanup;
   74689   }
   74690   if( pColumn!=0 && nColumn!=pColumn->nId ){
   74691     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
   74692     goto insert_cleanup;
   74693   }
   74694 
   74695   /* If the INSERT statement included an IDLIST term, then make sure
   74696   ** all elements of the IDLIST really are columns of the table and
   74697   ** remember the column indices.
   74698   **
   74699   ** If the table has an INTEGER PRIMARY KEY column and that column
   74700   ** is named in the IDLIST, then record in the keyColumn variable
   74701   ** the index into IDLIST of the primary key column.  keyColumn is
   74702   ** the index of the primary key as it appears in IDLIST, not as
   74703   ** is appears in the original table.  (The index of the primary
   74704   ** key in the original table is pTab->iPKey.)
   74705   */
   74706   if( pColumn ){
   74707     for(i=0; i<pColumn->nId; i++){
   74708       pColumn->a[i].idx = -1;
   74709     }
   74710     for(i=0; i<pColumn->nId; i++){
   74711       for(j=0; j<pTab->nCol; j++){
   74712         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
   74713           pColumn->a[i].idx = j;
   74714           if( j==pTab->iPKey ){
   74715             keyColumn = i;
   74716           }
   74717           break;
   74718         }
   74719       }
   74720       if( j>=pTab->nCol ){
   74721         if( sqlite3IsRowid(pColumn->a[i].zName) ){
   74722           keyColumn = i;
   74723         }else{
   74724           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
   74725               pTabList, 0, pColumn->a[i].zName);
   74726           pParse->nErr++;
   74727           goto insert_cleanup;
   74728         }
   74729       }
   74730     }
   74731   }
   74732 
   74733   /* If there is no IDLIST term but the table has an integer primary
   74734   ** key, the set the keyColumn variable to the primary key column index
   74735   ** in the original table definition.
   74736   */
   74737   if( pColumn==0 && nColumn>0 ){
   74738     keyColumn = pTab->iPKey;
   74739   }
   74740 
   74741   /* Initialize the count of rows to be inserted
   74742   */
   74743   if( db->flags & SQLITE_CountRows ){
   74744     regRowCount = ++pParse->nMem;
   74745     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   74746   }
   74747 
   74748   /* If this is not a view, open the table and and all indices */
   74749   if( !isView ){
   74750     int nIdx;
   74751 
   74752     baseCur = pParse->nTab;
   74753     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
   74754     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
   74755     if( aRegIdx==0 ){
   74756       goto insert_cleanup;
   74757     }
   74758     for(i=0; i<nIdx; i++){
   74759       aRegIdx[i] = ++pParse->nMem;
   74760     }
   74761   }
   74762 
   74763   /* This is the top of the main insertion loop */
   74764   if( useTempTable ){
   74765     /* This block codes the top of loop only.  The complete loop is the
   74766     ** following pseudocode (template 4):
   74767     **
   74768     **         rewind temp table
   74769     **      C: loop over rows of intermediate table
   74770     **           transfer values form intermediate table into <table>
   74771     **         end loop
   74772     **      D: ...
   74773     */
   74774     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
   74775     addrCont = sqlite3VdbeCurrentAddr(v);
   74776   }else if( pSelect ){
   74777     /* This block codes the top of loop only.  The complete loop is the
   74778     ** following pseudocode (template 3):
   74779     **
   74780     **      C: yield X
   74781     **         if EOF goto D
   74782     **         insert the select result into <table> from R..R+n
   74783     **         goto C
   74784     **      D: ...
   74785     */
   74786     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
   74787     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
   74788   }
   74789 
   74790   /* Allocate registers for holding the rowid of the new row,
   74791   ** the content of the new row, and the assemblied row record.
   74792   */
   74793   regRecord = ++pParse->nMem;
   74794   regRowid = regIns = pParse->nMem+1;
   74795   pParse->nMem += pTab->nCol + 1;
   74796   if( IsVirtual(pTab) ){
   74797     regRowid++;
   74798     pParse->nMem++;
   74799   }
   74800   regData = regRowid+1;
   74801 
   74802   /* Run the BEFORE and INSTEAD OF triggers, if there are any
   74803   */
   74804   endOfLoop = sqlite3VdbeMakeLabel(v);
   74805   if( tmask & TRIGGER_BEFORE ){
   74806     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
   74807 
   74808     /* build the NEW.* reference row.  Note that if there is an INTEGER
   74809     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
   74810     ** translated into a unique ID for the row.  But on a BEFORE trigger,
   74811     ** we do not know what the unique ID will be (because the insert has
   74812     ** not happened yet) so we substitute a rowid of -1
   74813     */
   74814     if( keyColumn<0 ){
   74815       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   74816     }else{
   74817       int j1;
   74818       if( useTempTable ){
   74819         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
   74820       }else{
   74821         assert( pSelect==0 );  /* Otherwise useTempTable is true */
   74822         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
   74823       }
   74824       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
   74825       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   74826       sqlite3VdbeJumpHere(v, j1);
   74827       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
   74828     }
   74829 
   74830     /* Cannot have triggers on a virtual table. If it were possible,
   74831     ** this block would have to account for hidden column.
   74832     */
   74833     assert( !IsVirtual(pTab) );
   74834 
   74835     /* Create the new column data
   74836     */
   74837     for(i=0; i<pTab->nCol; i++){
   74838       if( pColumn==0 ){
   74839         j = i;
   74840       }else{
   74841         for(j=0; j<pColumn->nId; j++){
   74842           if( pColumn->a[j].idx==i ) break;
   74843         }
   74844       }
   74845       if( pColumn && j>=pColumn->nId ){
   74846         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
   74847       }else if( useTempTable ){
   74848         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
   74849       }else{
   74850         assert( pSelect==0 ); /* Otherwise useTempTable is true */
   74851         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
   74852       }
   74853     }
   74854 
   74855     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
   74856     ** do not attempt any conversions before assembling the record.
   74857     ** If this is a real table, attempt conversions as required by the
   74858     ** table column affinities.
   74859     */
   74860     if( !isView ){
   74861       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
   74862       sqlite3TableAffinityStr(v, pTab);
   74863     }
   74864 
   74865     /* Fire BEFORE or INSTEAD OF triggers */
   74866     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
   74867         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
   74868 
   74869     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
   74870   }
   74871 
   74872   /* Push the record number for the new entry onto the stack.  The
   74873   ** record number is a randomly generate integer created by NewRowid
   74874   ** except when the table has an INTEGER PRIMARY KEY column, in which
   74875   ** case the record number is the same as that column.
   74876   */
   74877   if( !isView ){
   74878     if( IsVirtual(pTab) ){
   74879       /* The row that the VUpdate opcode will delete: none */
   74880       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
   74881     }
   74882     if( keyColumn>=0 ){
   74883       if( useTempTable ){
   74884         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
   74885       }else if( pSelect ){
   74886         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
   74887       }else{
   74888         VdbeOp *pOp;
   74889         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
   74890         pOp = sqlite3VdbeGetOp(v, -1);
   74891         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
   74892           appendFlag = 1;
   74893           pOp->opcode = OP_NewRowid;
   74894           pOp->p1 = baseCur;
   74895           pOp->p2 = regRowid;
   74896           pOp->p3 = regAutoinc;
   74897         }
   74898       }
   74899       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
   74900       ** to generate a unique primary key value.
   74901       */
   74902       if( !appendFlag ){
   74903         int j1;
   74904         if( !IsVirtual(pTab) ){
   74905           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
   74906           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
   74907           sqlite3VdbeJumpHere(v, j1);
   74908         }else{
   74909           j1 = sqlite3VdbeCurrentAddr(v);
   74910           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
   74911         }
   74912         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
   74913       }
   74914     }else if( IsVirtual(pTab) ){
   74915       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
   74916     }else{
   74917       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
   74918       appendFlag = 1;
   74919     }
   74920     autoIncStep(pParse, regAutoinc, regRowid);
   74921 
   74922     /* Push onto the stack, data for all columns of the new entry, beginning
   74923     ** with the first column.
   74924     */
   74925     nHidden = 0;
   74926     for(i=0; i<pTab->nCol; i++){
   74927       int iRegStore = regRowid+1+i;
   74928       if( i==pTab->iPKey ){
   74929         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
   74930         ** Whenever this column is read, the record number will be substituted
   74931         ** in its place.  So will fill this column with a NULL to avoid
   74932         ** taking up data space with information that will never be used. */
   74933         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
   74934         continue;
   74935       }
   74936       if( pColumn==0 ){
   74937         if( IsHiddenColumn(&pTab->aCol[i]) ){
   74938           assert( IsVirtual(pTab) );
   74939           j = -1;
   74940           nHidden++;
   74941         }else{
   74942           j = i - nHidden;
   74943         }
   74944       }else{
   74945         for(j=0; j<pColumn->nId; j++){
   74946           if( pColumn->a[j].idx==i ) break;
   74947         }
   74948       }
   74949       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
   74950         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
   74951       }else if( useTempTable ){
   74952         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
   74953       }else if( pSelect ){
   74954         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
   74955       }else{
   74956         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
   74957       }
   74958     }
   74959 
   74960     /* Generate code to check constraints and generate index keys and
   74961     ** do the insertion.
   74962     */
   74963 #ifndef SQLITE_OMIT_VIRTUALTABLE
   74964     if( IsVirtual(pTab) ){
   74965       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   74966       sqlite3VtabMakeWritable(pParse, pTab);
   74967       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
   74968       sqlite3MayAbort(pParse);
   74969     }else
   74970 #endif
   74971     {
   74972       int isReplace;    /* Set to true if constraints may cause a replace */
   74973       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
   74974           keyColumn>=0, 0, onError, endOfLoop, &isReplace
   74975       );
   74976       sqlite3FkCheck(pParse, pTab, 0, regIns);
   74977       sqlite3CompleteInsertion(
   74978           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
   74979       );
   74980     }
   74981   }
   74982 
   74983   /* Update the count of rows that are inserted
   74984   */
   74985   if( (db->flags & SQLITE_CountRows)!=0 ){
   74986     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
   74987   }
   74988 
   74989   if( pTrigger ){
   74990     /* Code AFTER triggers */
   74991     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
   74992         pTab, regData-2-pTab->nCol, onError, endOfLoop);
   74993   }
   74994 
   74995   /* The bottom of the main insertion loop, if the data source
   74996   ** is a SELECT statement.
   74997   */
   74998   sqlite3VdbeResolveLabel(v, endOfLoop);
   74999   if( useTempTable ){
   75000     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
   75001     sqlite3VdbeJumpHere(v, addrInsTop);
   75002     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
   75003   }else if( pSelect ){
   75004     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
   75005     sqlite3VdbeJumpHere(v, addrInsTop);
   75006   }
   75007 
   75008   if( !IsVirtual(pTab) && !isView ){
   75009     /* Close all tables opened */
   75010     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
   75011     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
   75012       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
   75013     }
   75014   }
   75015 
   75016 insert_end:
   75017   /* Update the sqlite_sequence table by storing the content of the
   75018   ** maximum rowid counter values recorded while inserting into
   75019   ** autoincrement tables.
   75020   */
   75021   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   75022     sqlite3AutoincrementEnd(pParse);
   75023   }
   75024 
   75025   /*
   75026   ** Return the number of rows inserted. If this routine is
   75027   ** generating code because of a call to sqlite3NestedParse(), do not
   75028   ** invoke the callback function.
   75029   */
   75030   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
   75031     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
   75032     sqlite3VdbeSetNumCols(v, 1);
   75033     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
   75034   }
   75035 
   75036 insert_cleanup:
   75037   sqlite3SrcListDelete(db, pTabList);
   75038   sqlite3ExprListDelete(db, pList);
   75039   sqlite3SelectDelete(db, pSelect);
   75040   sqlite3IdListDelete(db, pColumn);
   75041   sqlite3DbFree(db, aRegIdx);
   75042 }
   75043 
   75044 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   75045 ** thely may interfere with compilation of other functions in this file
   75046 ** (or in another file, if this file becomes part of the amalgamation).  */
   75047 #ifdef isView
   75048  #undef isView
   75049 #endif
   75050 #ifdef pTrigger
   75051  #undef pTrigger
   75052 #endif
   75053 #ifdef tmask
   75054  #undef tmask
   75055 #endif
   75056 
   75057 
   75058 /*
   75059 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
   75060 **
   75061 ** The input is a range of consecutive registers as follows:
   75062 **
   75063 **    1.  The rowid of the row after the update.
   75064 **
   75065 **    2.  The data in the first column of the entry after the update.
   75066 **
   75067 **    i.  Data from middle columns...
   75068 **
   75069 **    N.  The data in the last column of the entry after the update.
   75070 **
   75071 ** The regRowid parameter is the index of the register containing (1).
   75072 **
   75073 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
   75074 ** the address of a register containing the rowid before the update takes
   75075 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
   75076 ** is false, indicating an INSERT statement, then a non-zero rowidChng
   75077 ** indicates that the rowid was explicitly specified as part of the
   75078 ** INSERT statement. If rowidChng is false, it means that  the rowid is
   75079 ** computed automatically in an insert or that the rowid value is not
   75080 ** modified by an update.
   75081 **
   75082 ** The code generated by this routine store new index entries into
   75083 ** registers identified by aRegIdx[].  No index entry is created for
   75084 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
   75085 ** the same as the order of indices on the linked list of indices
   75086 ** attached to the table.
   75087 **
   75088 ** This routine also generates code to check constraints.  NOT NULL,
   75089 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
   75090 ** then the appropriate action is performed.  There are five possible
   75091 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
   75092 **
   75093 **  Constraint type  Action       What Happens
   75094 **  ---------------  ----------   ----------------------------------------
   75095 **  any              ROLLBACK     The current transaction is rolled back and
   75096 **                                sqlite3_exec() returns immediately with a
   75097 **                                return code of SQLITE_CONSTRAINT.
   75098 **
   75099 **  any              ABORT        Back out changes from the current command
   75100 **                                only (do not do a complete rollback) then
   75101 **                                cause sqlite3_exec() to return immediately
   75102 **                                with SQLITE_CONSTRAINT.
   75103 **
   75104 **  any              FAIL         Sqlite_exec() returns immediately with a
   75105 **                                return code of SQLITE_CONSTRAINT.  The
   75106 **                                transaction is not rolled back and any
   75107 **                                prior changes are retained.
   75108 **
   75109 **  any              IGNORE       The record number and data is popped from
   75110 **                                the stack and there is an immediate jump
   75111 **                                to label ignoreDest.
   75112 **
   75113 **  NOT NULL         REPLACE      The NULL value is replace by the default
   75114 **                                value for that column.  If the default value
   75115 **                                is NULL, the action is the same as ABORT.
   75116 **
   75117 **  UNIQUE           REPLACE      The other row that conflicts with the row
   75118 **                                being inserted is removed.
   75119 **
   75120 **  CHECK            REPLACE      Illegal.  The results in an exception.
   75121 **
   75122 ** Which action to take is determined by the overrideError parameter.
   75123 ** Or if overrideError==OE_Default, then the pParse->onError parameter
   75124 ** is used.  Or if pParse->onError==OE_Default then the onError value
   75125 ** for the constraint is used.
   75126 **
   75127 ** The calling routine must open a read/write cursor for pTab with
   75128 ** cursor number "baseCur".  All indices of pTab must also have open
   75129 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
   75130 ** Except, if there is no possibility of a REPLACE action then
   75131 ** cursors do not need to be open for indices where aRegIdx[i]==0.
   75132 */
   75133 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
   75134   Parse *pParse,      /* The parser context */
   75135   Table *pTab,        /* the table into which we are inserting */
   75136   int baseCur,        /* Index of a read/write cursor pointing at pTab */
   75137   int regRowid,       /* Index of the range of input registers */
   75138   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
   75139   int rowidChng,      /* True if the rowid might collide with existing entry */
   75140   int isUpdate,       /* True for UPDATE, False for INSERT */
   75141   int overrideError,  /* Override onError to this if not OE_Default */
   75142   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
   75143   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
   75144 ){
   75145   int i;              /* loop counter */
   75146   Vdbe *v;            /* VDBE under constrution */
   75147   int nCol;           /* Number of columns */
   75148   int onError;        /* Conflict resolution strategy */
   75149   int j1;             /* Addresss of jump instruction */
   75150   int j2 = 0, j3;     /* Addresses of jump instructions */
   75151   int regData;        /* Register containing first data column */
   75152   int iCur;           /* Table cursor number */
   75153   Index *pIdx;         /* Pointer to one of the indices */
   75154   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
   75155   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
   75156 
   75157   v = sqlite3GetVdbe(pParse);
   75158   assert( v!=0 );
   75159   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   75160   nCol = pTab->nCol;
   75161   regData = regRowid + 1;
   75162 
   75163   /* Test all NOT NULL constraints.
   75164   */
   75165   for(i=0; i<nCol; i++){
   75166     if( i==pTab->iPKey ){
   75167       continue;
   75168     }
   75169     onError = pTab->aCol[i].notNull;
   75170     if( onError==OE_None ) continue;
   75171     if( overrideError!=OE_Default ){
   75172       onError = overrideError;
   75173     }else if( onError==OE_Default ){
   75174       onError = OE_Abort;
   75175     }
   75176     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
   75177       onError = OE_Abort;
   75178     }
   75179     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
   75180         || onError==OE_Ignore || onError==OE_Replace );
   75181     switch( onError ){
   75182       case OE_Abort:
   75183         sqlite3MayAbort(pParse);
   75184       case OE_Rollback:
   75185       case OE_Fail: {
   75186         char *zMsg;
   75187         j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
   75188                                   SQLITE_CONSTRAINT, onError, regData+i);
   75189         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
   75190                               pTab->zName, pTab->aCol[i].zName);
   75191         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
   75192         break;
   75193       }
   75194       case OE_Ignore: {
   75195         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
   75196         break;
   75197       }
   75198       default: {
   75199         assert( onError==OE_Replace );
   75200         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
   75201         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
   75202         sqlite3VdbeJumpHere(v, j1);
   75203         break;
   75204       }
   75205     }
   75206   }
   75207 
   75208   /* Test all CHECK constraints
   75209   */
   75210 #ifndef SQLITE_OMIT_CHECK
   75211   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
   75212     int allOk = sqlite3VdbeMakeLabel(v);
   75213     pParse->ckBase = regData;
   75214     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
   75215     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
   75216     if( onError==OE_Ignore ){
   75217       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   75218     }else{
   75219       sqlite3HaltConstraint(pParse, onError, 0, 0);
   75220     }
   75221     sqlite3VdbeResolveLabel(v, allOk);
   75222   }
   75223 #endif /* !defined(SQLITE_OMIT_CHECK) */
   75224 
   75225   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
   75226   ** of the new record does not previously exist.  Except, if this
   75227   ** is an UPDATE and the primary key is not changing, that is OK.
   75228   */
   75229   if( rowidChng ){
   75230     onError = pTab->keyConf;
   75231     if( overrideError!=OE_Default ){
   75232       onError = overrideError;
   75233     }else if( onError==OE_Default ){
   75234       onError = OE_Abort;
   75235     }
   75236 
   75237     if( isUpdate ){
   75238       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
   75239     }
   75240     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
   75241     switch( onError ){
   75242       default: {
   75243         onError = OE_Abort;
   75244         /* Fall thru into the next case */
   75245       }
   75246       case OE_Rollback:
   75247       case OE_Abort:
   75248       case OE_Fail: {
   75249         sqlite3HaltConstraint(
   75250           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
   75251         break;
   75252       }
   75253       case OE_Replace: {
   75254         /* If there are DELETE triggers on this table and the
   75255         ** recursive-triggers flag is set, call GenerateRowDelete() to
   75256         ** remove the conflicting row from the the table. This will fire
   75257         ** the triggers and remove both the table and index b-tree entries.
   75258         **
   75259         ** Otherwise, if there are no triggers or the recursive-triggers
   75260         ** flag is not set, call GenerateRowIndexDelete(). This removes
   75261         ** the index b-tree entries only. The table b-tree entry will be
   75262         ** replaced by the new entry when it is inserted.  */
   75263         Trigger *pTrigger = 0;
   75264         if( pParse->db->flags&SQLITE_RecTriggers ){
   75265           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   75266         }
   75267         sqlite3MultiWrite(pParse);
   75268         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
   75269           sqlite3GenerateRowDelete(
   75270               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
   75271           );
   75272         }else{
   75273           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
   75274         }
   75275         seenReplace = 1;
   75276         break;
   75277       }
   75278       case OE_Ignore: {
   75279         assert( seenReplace==0 );
   75280         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   75281         break;
   75282       }
   75283     }
   75284     sqlite3VdbeJumpHere(v, j3);
   75285     if( isUpdate ){
   75286       sqlite3VdbeJumpHere(v, j2);
   75287     }
   75288   }
   75289 
   75290   /* Test all UNIQUE constraints by creating entries for each UNIQUE
   75291   ** index and making sure that duplicate entries do not already exist.
   75292   ** Add the new records to the indices as we go.
   75293   */
   75294   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
   75295     int regIdx;
   75296     int regR;
   75297 
   75298     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
   75299 
   75300     /* Create a key for accessing the index entry */
   75301     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
   75302     for(i=0; i<pIdx->nColumn; i++){
   75303       int idx = pIdx->aiColumn[i];
   75304       if( idx==pTab->iPKey ){
   75305         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
   75306       }else{
   75307         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
   75308       }
   75309     }
   75310     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
   75311     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
   75312     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
   75313     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
   75314 
   75315     /* Find out what action to take in case there is an indexing conflict */
   75316     onError = pIdx->onError;
   75317     if( onError==OE_None ){
   75318       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
   75319       continue;  /* pIdx is not a UNIQUE index */
   75320     }
   75321     if( overrideError!=OE_Default ){
   75322       onError = overrideError;
   75323     }else if( onError==OE_Default ){
   75324       onError = OE_Abort;
   75325     }
   75326     if( seenReplace ){
   75327       if( onError==OE_Ignore ) onError = OE_Replace;
   75328       else if( onError==OE_Fail ) onError = OE_Abort;
   75329     }
   75330 
   75331     /* Check to see if the new index entry will be unique */
   75332     regR = sqlite3GetTempReg(pParse);
   75333     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
   75334     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
   75335                            regR, SQLITE_INT_TO_PTR(regIdx),
   75336                            P4_INT32);
   75337     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
   75338 
   75339     /* Generate code that executes if the new index entry is not unique */
   75340     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
   75341         || onError==OE_Ignore || onError==OE_Replace );
   75342     switch( onError ){
   75343       case OE_Rollback:
   75344       case OE_Abort:
   75345       case OE_Fail: {
   75346         int j;
   75347         StrAccum errMsg;
   75348         const char *zSep;
   75349         char *zErr;
   75350 
   75351         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
   75352         errMsg.db = pParse->db;
   75353         zSep = pIdx->nColumn>1 ? "columns " : "column ";
   75354         for(j=0; j<pIdx->nColumn; j++){
   75355           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
   75356           sqlite3StrAccumAppend(&errMsg, zSep, -1);
   75357           zSep = ", ";
   75358           sqlite3StrAccumAppend(&errMsg, zCol, -1);
   75359         }
   75360         sqlite3StrAccumAppend(&errMsg,
   75361             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
   75362         zErr = sqlite3StrAccumFinish(&errMsg);
   75363         sqlite3HaltConstraint(pParse, onError, zErr, 0);
   75364         sqlite3DbFree(errMsg.db, zErr);
   75365         break;
   75366       }
   75367       case OE_Ignore: {
   75368         assert( seenReplace==0 );
   75369         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   75370         break;
   75371       }
   75372       default: {
   75373         Trigger *pTrigger = 0;
   75374         assert( onError==OE_Replace );
   75375         sqlite3MultiWrite(pParse);
   75376         if( pParse->db->flags&SQLITE_RecTriggers ){
   75377           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   75378         }
   75379         sqlite3GenerateRowDelete(
   75380             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
   75381         );
   75382         seenReplace = 1;
   75383         break;
   75384       }
   75385     }
   75386     sqlite3VdbeJumpHere(v, j3);
   75387     sqlite3ReleaseTempReg(pParse, regR);
   75388   }
   75389 
   75390   if( pbMayReplace ){
   75391     *pbMayReplace = seenReplace;
   75392   }
   75393 }
   75394 
   75395 /*
   75396 ** This routine generates code to finish the INSERT or UPDATE operation
   75397 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
   75398 ** A consecutive range of registers starting at regRowid contains the
   75399 ** rowid and the content to be inserted.
   75400 **
   75401 ** The arguments to this routine should be the same as the first six
   75402 ** arguments to sqlite3GenerateConstraintChecks.
   75403 */
   75404 SQLITE_PRIVATE void sqlite3CompleteInsertion(
   75405   Parse *pParse,      /* The parser context */
   75406   Table *pTab,        /* the table into which we are inserting */
   75407   int baseCur,        /* Index of a read/write cursor pointing at pTab */
   75408   int regRowid,       /* Range of content */
   75409   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
   75410   int isUpdate,       /* True for UPDATE, False for INSERT */
   75411   int appendBias,     /* True if this is likely to be an append */
   75412   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
   75413 ){
   75414   int i;
   75415   Vdbe *v;
   75416   int nIdx;
   75417   Index *pIdx;
   75418   u8 pik_flags;
   75419   int regData;
   75420   int regRec;
   75421 
   75422   v = sqlite3GetVdbe(pParse);
   75423   assert( v!=0 );
   75424   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   75425   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
   75426   for(i=nIdx-1; i>=0; i--){
   75427     if( aRegIdx[i]==0 ) continue;
   75428     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
   75429     if( useSeekResult ){
   75430       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   75431     }
   75432   }
   75433   regData = regRowid + 1;
   75434   regRec = sqlite3GetTempReg(pParse);
   75435   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
   75436   sqlite3TableAffinityStr(v, pTab);
   75437   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
   75438   if( pParse->nested ){
   75439     pik_flags = 0;
   75440   }else{
   75441     pik_flags = OPFLAG_NCHANGE;
   75442     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
   75443   }
   75444   if( appendBias ){
   75445     pik_flags |= OPFLAG_APPEND;
   75446   }
   75447   if( useSeekResult ){
   75448     pik_flags |= OPFLAG_USESEEKRESULT;
   75449   }
   75450   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
   75451   if( !pParse->nested ){
   75452     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
   75453   }
   75454   sqlite3VdbeChangeP5(v, pik_flags);
   75455 }
   75456 
   75457 /*
   75458 ** Generate code that will open cursors for a table and for all
   75459 ** indices of that table.  The "baseCur" parameter is the cursor number used
   75460 ** for the table.  Indices are opened on subsequent cursors.
   75461 **
   75462 ** Return the number of indices on the table.
   75463 */
   75464 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
   75465   Parse *pParse,   /* Parsing context */
   75466   Table *pTab,     /* Table to be opened */
   75467   int baseCur,     /* Cursor number assigned to the table */
   75468   int op           /* OP_OpenRead or OP_OpenWrite */
   75469 ){
   75470   int i;
   75471   int iDb;
   75472   Index *pIdx;
   75473   Vdbe *v;
   75474 
   75475   if( IsVirtual(pTab) ) return 0;
   75476   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   75477   v = sqlite3GetVdbe(pParse);
   75478   assert( v!=0 );
   75479   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
   75480   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   75481     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   75482     assert( pIdx->pSchema==pTab->pSchema );
   75483     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
   75484                       (char*)pKey, P4_KEYINFO_HANDOFF);
   75485     VdbeComment((v, "%s", pIdx->zName));
   75486   }
   75487   if( pParse->nTab<baseCur+i ){
   75488     pParse->nTab = baseCur+i;
   75489   }
   75490   return i-1;
   75491 }
   75492 
   75493 
   75494 #ifdef SQLITE_TEST
   75495 /*
   75496 ** The following global variable is incremented whenever the
   75497 ** transfer optimization is used.  This is used for testing
   75498 ** purposes only - to make sure the transfer optimization really
   75499 ** is happening when it is suppose to.
   75500 */
   75501 SQLITE_API int sqlite3_xferopt_count;
   75502 #endif /* SQLITE_TEST */
   75503 
   75504 
   75505 #ifndef SQLITE_OMIT_XFER_OPT
   75506 /*
   75507 ** Check to collation names to see if they are compatible.
   75508 */
   75509 static int xferCompatibleCollation(const char *z1, const char *z2){
   75510   if( z1==0 ){
   75511     return z2==0;
   75512   }
   75513   if( z2==0 ){
   75514     return 0;
   75515   }
   75516   return sqlite3StrICmp(z1, z2)==0;
   75517 }
   75518 
   75519 
   75520 /*
   75521 ** Check to see if index pSrc is compatible as a source of data
   75522 ** for index pDest in an insert transfer optimization.  The rules
   75523 ** for a compatible index:
   75524 **
   75525 **    *   The index is over the same set of columns
   75526 **    *   The same DESC and ASC markings occurs on all columns
   75527 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
   75528 **    *   The same collating sequence on each column
   75529 */
   75530 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
   75531   int i;
   75532   assert( pDest && pSrc );
   75533   assert( pDest->pTable!=pSrc->pTable );
   75534   if( pDest->nColumn!=pSrc->nColumn ){
   75535     return 0;   /* Different number of columns */
   75536   }
   75537   if( pDest->onError!=pSrc->onError ){
   75538     return 0;   /* Different conflict resolution strategies */
   75539   }
   75540   for(i=0; i<pSrc->nColumn; i++){
   75541     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
   75542       return 0;   /* Different columns indexed */
   75543     }
   75544     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
   75545       return 0;   /* Different sort orders */
   75546     }
   75547     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
   75548       return 0;   /* Different collating sequences */
   75549     }
   75550   }
   75551 
   75552   /* If no test above fails then the indices must be compatible */
   75553   return 1;
   75554 }
   75555 
   75556 /*
   75557 ** Attempt the transfer optimization on INSERTs of the form
   75558 **
   75559 **     INSERT INTO tab1 SELECT * FROM tab2;
   75560 **
   75561 ** This optimization is only attempted if
   75562 **
   75563 **    (1)  tab1 and tab2 have identical schemas including all the
   75564 **         same indices and constraints
   75565 **
   75566 **    (2)  tab1 and tab2 are different tables
   75567 **
   75568 **    (3)  There must be no triggers on tab1
   75569 **
   75570 **    (4)  The result set of the SELECT statement is "*"
   75571 **
   75572 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
   75573 **         or LIMIT clause.
   75574 **
   75575 **    (6)  The SELECT statement is a simple (not a compound) select that
   75576 **         contains only tab2 in its FROM clause
   75577 **
   75578 ** This method for implementing the INSERT transfers raw records from
   75579 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
   75580 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
   75581 ** the resulting tab1 has much less fragmentation.
   75582 **
   75583 ** This routine returns TRUE if the optimization is attempted.  If any
   75584 ** of the conditions above fail so that the optimization should not
   75585 ** be attempted, then this routine returns FALSE.
   75586 */
   75587 static int xferOptimization(
   75588   Parse *pParse,        /* Parser context */
   75589   Table *pDest,         /* The table we are inserting into */
   75590   Select *pSelect,      /* A SELECT statement to use as the data source */
   75591   int onError,          /* How to handle constraint errors */
   75592   int iDbDest           /* The database of pDest */
   75593 ){
   75594   ExprList *pEList;                /* The result set of the SELECT */
   75595   Table *pSrc;                     /* The table in the FROM clause of SELECT */
   75596   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
   75597   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
   75598   int i;                           /* Loop counter */
   75599   int iDbSrc;                      /* The database of pSrc */
   75600   int iSrc, iDest;                 /* Cursors from source and destination */
   75601   int addr1, addr2;                /* Loop addresses */
   75602   int emptyDestTest;               /* Address of test for empty pDest */
   75603   int emptySrcTest;                /* Address of test for empty pSrc */
   75604   Vdbe *v;                         /* The VDBE we are building */
   75605   KeyInfo *pKey;                   /* Key information for an index */
   75606   int regAutoinc;                  /* Memory register used by AUTOINC */
   75607   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
   75608   int regData, regRowid;           /* Registers holding data and rowid */
   75609 
   75610   if( pSelect==0 ){
   75611     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
   75612   }
   75613   if( sqlite3TriggerList(pParse, pDest) ){
   75614     return 0;   /* tab1 must not have triggers */
   75615   }
   75616 #ifndef SQLITE_OMIT_VIRTUALTABLE
   75617   if( pDest->tabFlags & TF_Virtual ){
   75618     return 0;   /* tab1 must not be a virtual table */
   75619   }
   75620 #endif
   75621   if( onError==OE_Default ){
   75622     onError = OE_Abort;
   75623   }
   75624   if( onError!=OE_Abort && onError!=OE_Rollback ){
   75625     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
   75626   }
   75627   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
   75628   if( pSelect->pSrc->nSrc!=1 ){
   75629     return 0;   /* FROM clause must have exactly one term */
   75630   }
   75631   if( pSelect->pSrc->a[0].pSelect ){
   75632     return 0;   /* FROM clause cannot contain a subquery */
   75633   }
   75634   if( pSelect->pWhere ){
   75635     return 0;   /* SELECT may not have a WHERE clause */
   75636   }
   75637   if( pSelect->pOrderBy ){
   75638     return 0;   /* SELECT may not have an ORDER BY clause */
   75639   }
   75640   /* Do not need to test for a HAVING clause.  If HAVING is present but
   75641   ** there is no ORDER BY, we will get an error. */
   75642   if( pSelect->pGroupBy ){
   75643     return 0;   /* SELECT may not have a GROUP BY clause */
   75644   }
   75645   if( pSelect->pLimit ){
   75646     return 0;   /* SELECT may not have a LIMIT clause */
   75647   }
   75648   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
   75649   if( pSelect->pPrior ){
   75650     return 0;   /* SELECT may not be a compound query */
   75651   }
   75652   if( pSelect->selFlags & SF_Distinct ){
   75653     return 0;   /* SELECT may not be DISTINCT */
   75654   }
   75655   pEList = pSelect->pEList;
   75656   assert( pEList!=0 );
   75657   if( pEList->nExpr!=1 ){
   75658     return 0;   /* The result set must have exactly one column */
   75659   }
   75660   assert( pEList->a[0].pExpr );
   75661   if( pEList->a[0].pExpr->op!=TK_ALL ){
   75662     return 0;   /* The result set must be the special operator "*" */
   75663   }
   75664 
   75665   /* At this point we have established that the statement is of the
   75666   ** correct syntactic form to participate in this optimization.  Now
   75667   ** we have to check the semantics.
   75668   */
   75669   pItem = pSelect->pSrc->a;
   75670   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
   75671   if( pSrc==0 ){
   75672     return 0;   /* FROM clause does not contain a real table */
   75673   }
   75674   if( pSrc==pDest ){
   75675     return 0;   /* tab1 and tab2 may not be the same table */
   75676   }
   75677 #ifndef SQLITE_OMIT_VIRTUALTABLE
   75678   if( pSrc->tabFlags & TF_Virtual ){
   75679     return 0;   /* tab2 must not be a virtual table */
   75680   }
   75681 #endif
   75682   if( pSrc->pSelect ){
   75683     return 0;   /* tab2 may not be a view */
   75684   }
   75685   if( pDest->nCol!=pSrc->nCol ){
   75686     return 0;   /* Number of columns must be the same in tab1 and tab2 */
   75687   }
   75688   if( pDest->iPKey!=pSrc->iPKey ){
   75689     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
   75690   }
   75691   for(i=0; i<pDest->nCol; i++){
   75692     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
   75693       return 0;    /* Affinity must be the same on all columns */
   75694     }
   75695     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
   75696       return 0;    /* Collating sequence must be the same on all columns */
   75697     }
   75698     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
   75699       return 0;    /* tab2 must be NOT NULL if tab1 is */
   75700     }
   75701   }
   75702   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
   75703     if( pDestIdx->onError!=OE_None ){
   75704       destHasUniqueIdx = 1;
   75705     }
   75706     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
   75707       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
   75708     }
   75709     if( pSrcIdx==0 ){
   75710       return 0;    /* pDestIdx has no corresponding index in pSrc */
   75711     }
   75712   }
   75713 #ifndef SQLITE_OMIT_CHECK
   75714   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
   75715     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
   75716   }
   75717 #endif
   75718 
   75719   /* If we get this far, it means either:
   75720   **
   75721   **    *   We can always do the transfer if the table contains an
   75722   **        an integer primary key
   75723   **
   75724   **    *   We can conditionally do the transfer if the destination
   75725   **        table is empty.
   75726   */
   75727 #ifdef SQLITE_TEST
   75728   sqlite3_xferopt_count++;
   75729 #endif
   75730   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
   75731   v = sqlite3GetVdbe(pParse);
   75732   sqlite3CodeVerifySchema(pParse, iDbSrc);
   75733   iSrc = pParse->nTab++;
   75734   iDest = pParse->nTab++;
   75735   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
   75736   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
   75737   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
   75738     /* If tables do not have an INTEGER PRIMARY KEY and there
   75739     ** are indices to be copied and the destination is not empty,
   75740     ** we have to disallow the transfer optimization because the
   75741     ** the rowids might change which will mess up indexing.
   75742     **
   75743     ** Or if the destination has a UNIQUE index and is not empty,
   75744     ** we also disallow the transfer optimization because we cannot
   75745     ** insure that all entries in the union of DEST and SRC will be
   75746     ** unique.
   75747     */
   75748     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
   75749     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
   75750     sqlite3VdbeJumpHere(v, addr1);
   75751   }else{
   75752     emptyDestTest = 0;
   75753   }
   75754   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
   75755   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
   75756   regData = sqlite3GetTempReg(pParse);
   75757   regRowid = sqlite3GetTempReg(pParse);
   75758   if( pDest->iPKey>=0 ){
   75759     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
   75760     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
   75761     sqlite3HaltConstraint(
   75762         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
   75763     sqlite3VdbeJumpHere(v, addr2);
   75764     autoIncStep(pParse, regAutoinc, regRowid);
   75765   }else if( pDest->pIndex==0 ){
   75766     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
   75767   }else{
   75768     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
   75769     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
   75770   }
   75771   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
   75772   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
   75773   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
   75774   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
   75775   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
   75776   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
   75777     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
   75778       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
   75779     }
   75780     assert( pSrcIdx );
   75781     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
   75782     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   75783     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
   75784     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
   75785                       (char*)pKey, P4_KEYINFO_HANDOFF);
   75786     VdbeComment((v, "%s", pSrcIdx->zName));
   75787     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
   75788     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
   75789                       (char*)pKey, P4_KEYINFO_HANDOFF);
   75790     VdbeComment((v, "%s", pDestIdx->zName));
   75791     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
   75792     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
   75793     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
   75794     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
   75795     sqlite3VdbeJumpHere(v, addr1);
   75796   }
   75797   sqlite3VdbeJumpHere(v, emptySrcTest);
   75798   sqlite3ReleaseTempReg(pParse, regRowid);
   75799   sqlite3ReleaseTempReg(pParse, regData);
   75800   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
   75801   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   75802   if( emptyDestTest ){
   75803     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
   75804     sqlite3VdbeJumpHere(v, emptyDestTest);
   75805     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   75806     return 0;
   75807   }else{
   75808     return 1;
   75809   }
   75810 }
   75811 #endif /* SQLITE_OMIT_XFER_OPT */
   75812 
   75813 /************** End of insert.c **********************************************/
   75814 /************** Begin file legacy.c ******************************************/
   75815 /*
   75816 ** 2001 September 15
   75817 **
   75818 ** The author disclaims copyright to this source code.  In place of
   75819 ** a legal notice, here is a blessing:
   75820 **
   75821 **    May you do good and not evil.
   75822 **    May you find forgiveness for yourself and forgive others.
   75823 **    May you share freely, never taking more than you give.
   75824 **
   75825 *************************************************************************
   75826 ** Main file for the SQLite library.  The routines in this file
   75827 ** implement the programmer interface to the library.  Routines in
   75828 ** other files are for internal use by SQLite and should not be
   75829 ** accessed by users of the library.
   75830 */
   75831 
   75832 
   75833 /*
   75834 ** Execute SQL code.  Return one of the SQLITE_ success/failure
   75835 ** codes.  Also write an error message into memory obtained from
   75836 ** malloc() and make *pzErrMsg point to that message.
   75837 **
   75838 ** If the SQL is a query, then for each row in the query result
   75839 ** the xCallback() function is called.  pArg becomes the first
   75840 ** argument to xCallback().  If xCallback=NULL then no callback
   75841 ** is invoked, even for queries.
   75842 */
   75843 SQLITE_API int sqlite3_exec(
   75844   sqlite3 *db,                /* The database on which the SQL executes */
   75845   const char *zSql,           /* The SQL to be executed */
   75846   sqlite3_callback xCallback, /* Invoke this callback routine */
   75847   void *pArg,                 /* First argument to xCallback() */
   75848   char **pzErrMsg             /* Write error messages here */
   75849 ){
   75850   int rc = SQLITE_OK;         /* Return code */
   75851   const char *zLeftover;      /* Tail of unprocessed SQL */
   75852   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
   75853   char **azCols = 0;          /* Names of result columns */
   75854   int nRetry = 0;             /* Number of retry attempts */
   75855   int callbackIsInit;         /* True if callback data is initialized */
   75856 
   75857   if( zSql==0 ) zSql = "";
   75858 
   75859   sqlite3_mutex_enter(db->mutex);
   75860   sqlite3Error(db, SQLITE_OK, 0);
   75861   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
   75862     int nCol;
   75863     char **azVals = 0;
   75864 
   75865     pStmt = 0;
   75866     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
   75867     assert( rc==SQLITE_OK || pStmt==0 );
   75868     if( rc!=SQLITE_OK ){
   75869       continue;
   75870     }
   75871     if( !pStmt ){
   75872       /* this happens for a comment or white-space */
   75873       zSql = zLeftover;
   75874       continue;
   75875     }
   75876 
   75877     callbackIsInit = 0;
   75878     nCol = sqlite3_column_count(pStmt);
   75879 
   75880     while( 1 ){
   75881       int i;
   75882       rc = sqlite3_step(pStmt);
   75883 
   75884       /* Invoke the callback function if required */
   75885       if( xCallback && (SQLITE_ROW==rc ||
   75886           (SQLITE_DONE==rc && !callbackIsInit
   75887                            && db->flags&SQLITE_NullCallback)) ){
   75888         if( !callbackIsInit ){
   75889           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
   75890           if( azCols==0 ){
   75891             goto exec_out;
   75892           }
   75893           for(i=0; i<nCol; i++){
   75894             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
   75895             /* sqlite3VdbeSetColName() installs column names as UTF8
   75896             ** strings so there is no way for sqlite3_column_name() to fail. */
   75897             assert( azCols[i]!=0 );
   75898           }
   75899           callbackIsInit = 1;
   75900         }
   75901         if( rc==SQLITE_ROW ){
   75902           azVals = &azCols[nCol];
   75903           for(i=0; i<nCol; i++){
   75904             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
   75905             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
   75906               db->mallocFailed = 1;
   75907               goto exec_out;
   75908             }
   75909           }
   75910         }
   75911         if( xCallback(pArg, nCol, azVals, azCols) ){
   75912           rc = SQLITE_ABORT;
   75913           sqlite3VdbeFinalize((Vdbe *)pStmt);
   75914           pStmt = 0;
   75915           sqlite3Error(db, SQLITE_ABORT, 0);
   75916           goto exec_out;
   75917         }
   75918       }
   75919 
   75920       if( rc!=SQLITE_ROW ){
   75921         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
   75922         pStmt = 0;
   75923         if( rc!=SQLITE_SCHEMA ){
   75924           nRetry = 0;
   75925           zSql = zLeftover;
   75926           while( sqlite3Isspace(zSql[0]) ) zSql++;
   75927         }
   75928         break;
   75929       }
   75930     }
   75931 
   75932     sqlite3DbFree(db, azCols);
   75933     azCols = 0;
   75934   }
   75935 
   75936 exec_out:
   75937   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
   75938   sqlite3DbFree(db, azCols);
   75939 
   75940   rc = sqlite3ApiExit(db, rc);
   75941   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
   75942     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
   75943     *pzErrMsg = sqlite3Malloc(nErrMsg);
   75944     if( *pzErrMsg ){
   75945       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
   75946     }else{
   75947       rc = SQLITE_NOMEM;
   75948       sqlite3Error(db, SQLITE_NOMEM, 0);
   75949     }
   75950   }else if( pzErrMsg ){
   75951     *pzErrMsg = 0;
   75952   }
   75953 
   75954   assert( (rc&db->errMask)==rc );
   75955   sqlite3_mutex_leave(db->mutex);
   75956   return rc;
   75957 }
   75958 
   75959 /************** End of legacy.c **********************************************/
   75960 /************** Begin file loadext.c *****************************************/
   75961 /*
   75962 ** 2006 June 7
   75963 **
   75964 ** The author disclaims copyright to this source code.  In place of
   75965 ** a legal notice, here is a blessing:
   75966 **
   75967 **    May you do good and not evil.
   75968 **    May you find forgiveness for yourself and forgive others.
   75969 **    May you share freely, never taking more than you give.
   75970 **
   75971 *************************************************************************
   75972 ** This file contains code used to dynamically load extensions into
   75973 ** the SQLite library.
   75974 */
   75975 
   75976 #ifndef SQLITE_CORE
   75977   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
   75978 #endif
   75979 /************** Include sqlite3ext.h in the middle of loadext.c **************/
   75980 /************** Begin file sqlite3ext.h **************************************/
   75981 /*
   75982 ** 2006 June 7
   75983 **
   75984 ** The author disclaims copyright to this source code.  In place of
   75985 ** a legal notice, here is a blessing:
   75986 **
   75987 **    May you do good and not evil.
   75988 **    May you find forgiveness for yourself and forgive others.
   75989 **    May you share freely, never taking more than you give.
   75990 **
   75991 *************************************************************************
   75992 ** This header file defines the SQLite interface for use by
   75993 ** shared libraries that want to be imported as extensions into
   75994 ** an SQLite instance.  Shared libraries that intend to be loaded
   75995 ** as extensions by SQLite should #include this file instead of
   75996 ** sqlite3.h.
   75997 */
   75998 #ifndef _SQLITE3EXT_H_
   75999 #define _SQLITE3EXT_H_
   76000 
   76001 typedef struct sqlite3_api_routines sqlite3_api_routines;
   76002 
   76003 /*
   76004 ** The following structure holds pointers to all of the SQLite API
   76005 ** routines.
   76006 **
   76007 ** WARNING:  In order to maintain backwards compatibility, add new
   76008 ** interfaces to the end of this structure only.  If you insert new
   76009 ** interfaces in the middle of this structure, then older different
   76010 ** versions of SQLite will not be able to load each others' shared
   76011 ** libraries!
   76012 */
   76013 struct sqlite3_api_routines {
   76014   void * (*aggregate_context)(sqlite3_context*,int nBytes);
   76015   int  (*aggregate_count)(sqlite3_context*);
   76016   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
   76017   int  (*bind_double)(sqlite3_stmt*,int,double);
   76018   int  (*bind_int)(sqlite3_stmt*,int,int);
   76019   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
   76020   int  (*bind_null)(sqlite3_stmt*,int);
   76021   int  (*bind_parameter_count)(sqlite3_stmt*);
   76022   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
   76023   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
   76024   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
   76025   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
   76026   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
   76027   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
   76028   int  (*busy_timeout)(sqlite3*,int ms);
   76029   int  (*changes)(sqlite3*);
   76030   int  (*close)(sqlite3*);
   76031   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
   76032   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
   76033   const void * (*column_blob)(sqlite3_stmt*,int iCol);
   76034   int  (*column_bytes)(sqlite3_stmt*,int iCol);
   76035   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
   76036   int  (*column_count)(sqlite3_stmt*pStmt);
   76037   const char * (*column_database_name)(sqlite3_stmt*,int);
   76038   const void * (*column_database_name16)(sqlite3_stmt*,int);
   76039   const char * (*column_decltype)(sqlite3_stmt*,int i);
   76040   const void * (*column_decltype16)(sqlite3_stmt*,int);
   76041   double  (*column_double)(sqlite3_stmt*,int iCol);
   76042   int  (*column_int)(sqlite3_stmt*,int iCol);
   76043   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
   76044   const char * (*column_name)(sqlite3_stmt*,int);
   76045   const void * (*column_name16)(sqlite3_stmt*,int);
   76046   const char * (*column_origin_name)(sqlite3_stmt*,int);
   76047   const void * (*column_origin_name16)(sqlite3_stmt*,int);
   76048   const char * (*column_table_name)(sqlite3_stmt*,int);
   76049   const void * (*column_table_name16)(sqlite3_stmt*,int);
   76050   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
   76051   const void * (*column_text16)(sqlite3_stmt*,int iCol);
   76052   int  (*column_type)(sqlite3_stmt*,int iCol);
   76053   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
   76054   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
   76055   int  (*complete)(const char*sql);
   76056   int  (*complete16)(const void*sql);
   76057   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
   76058   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
   76059   int  (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
   76060   int  (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
   76061   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
   76062   int  (*data_count)(sqlite3_stmt*pStmt);
   76063   sqlite3 * (*db_handle)(sqlite3_stmt*);
   76064   int (*declare_vtab)(sqlite3*,const char*);
   76065   int  (*enable_shared_cache)(int);
   76066   int  (*errcode)(sqlite3*db);
   76067   const char * (*errmsg)(sqlite3*);
   76068   const void * (*errmsg16)(sqlite3*);
   76069   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
   76070   int  (*expired)(sqlite3_stmt*);
   76071   int  (*finalize)(sqlite3_stmt*pStmt);
   76072   void  (*free)(void*);
   76073   void  (*free_table)(char**result);
   76074   int  (*get_autocommit)(sqlite3*);
   76075   void * (*get_auxdata)(sqlite3_context*,int);
   76076   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
   76077   int  (*global_recover)(void);
   76078   void  (*interruptx)(sqlite3*);
   76079   sqlite_int64  (*last_insert_rowid)(sqlite3*);
   76080   const char * (*libversion)(void);
   76081   int  (*libversion_number)(void);
   76082   void *(*malloc)(int);
   76083   char * (*mprintf)(const char*,...);
   76084   int  (*open)(const char*,sqlite3**);
   76085   int  (*open16)(const void*,sqlite3**);
   76086   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
   76087   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
   76088   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
   76089   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
   76090   void *(*realloc)(void*,int);
   76091   int  (*reset)(sqlite3_stmt*pStmt);
   76092   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
   76093   void  (*result_double)(sqlite3_context*,double);
   76094   void  (*result_error)(sqlite3_context*,const char*,int);
   76095   void  (*result_error16)(sqlite3_context*,const void*,int);
   76096   void  (*result_int)(sqlite3_context*,int);
   76097   void  (*result_int64)(sqlite3_context*,sqlite_int64);
   76098   void  (*result_null)(sqlite3_context*);
   76099   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
   76100   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
   76101   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
   76102   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
   76103   void  (*result_value)(sqlite3_context*,sqlite3_value*);
   76104   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
   76105   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
   76106   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
   76107   char * (*snprintf)(int,char*,const char*,...);
   76108   int  (*step)(sqlite3_stmt*);
   76109   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
   76110   void  (*thread_cleanup)(void);
   76111   int  (*total_changes)(sqlite3*);
   76112   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
   76113   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
   76114   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
   76115   void * (*user_data)(sqlite3_context*);
   76116   const void * (*value_blob)(sqlite3_value*);
   76117   int  (*value_bytes)(sqlite3_value*);
   76118   int  (*value_bytes16)(sqlite3_value*);
   76119   double  (*value_double)(sqlite3_value*);
   76120   int  (*value_int)(sqlite3_value*);
   76121   sqlite_int64  (*value_int64)(sqlite3_value*);
   76122   int  (*value_numeric_type)(sqlite3_value*);
   76123   const unsigned char * (*value_text)(sqlite3_value*);
   76124   const void * (*value_text16)(sqlite3_value*);
   76125   const void * (*value_text16be)(sqlite3_value*);
   76126   const void * (*value_text16le)(sqlite3_value*);
   76127   int  (*value_type)(sqlite3_value*);
   76128   char *(*vmprintf)(const char*,va_list);
   76129   /* Added ??? */
   76130   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
   76131   /* Added by 3.3.13 */
   76132   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
   76133   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
   76134   int (*clear_bindings)(sqlite3_stmt*);
   76135   /* Added by 3.4.1 */
   76136   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
   76137   /* Added by 3.5.0 */
   76138   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
   76139   int (*blob_bytes)(sqlite3_blob*);
   76140   int (*blob_close)(sqlite3_blob*);
   76141   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
   76142   int (*blob_read)(sqlite3_blob*,void*,int,int);
   76143   int (*blob_write)(sqlite3_blob*,const void*,int,int);
   76144   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
   76145   int (*file_control)(sqlite3*,const char*,int,void*);
   76146   sqlite3_int64 (*memory_highwater)(int);
   76147   sqlite3_int64 (*memory_used)(void);
   76148   sqlite3_mutex *(*mutex_alloc)(int);
   76149   void (*mutex_enter)(sqlite3_mutex*);
   76150   void (*mutex_free)(sqlite3_mutex*);
   76151   void (*mutex_leave)(sqlite3_mutex*);
   76152   int (*mutex_try)(sqlite3_mutex*);
   76153   int (*open_v2)(const char*,sqlite3**,int,const char*);
   76154   int (*release_memory)(int);
   76155   void (*result_error_nomem)(sqlite3_context*);
   76156   void (*result_error_toobig)(sqlite3_context*);
   76157   int (*sleep)(int);
   76158   void (*soft_heap_limit)(int);
   76159   sqlite3_vfs *(*vfs_find)(const char*);
   76160   int (*vfs_register)(sqlite3_vfs*,int);
   76161   int (*vfs_unregister)(sqlite3_vfs*);
   76162   int (*xthreadsafe)(void);
   76163   void (*result_zeroblob)(sqlite3_context*,int);
   76164   void (*result_error_code)(sqlite3_context*,int);
   76165   int (*test_control)(int, ...);
   76166   void (*randomness)(int,void*);
   76167   sqlite3 *(*context_db_handle)(sqlite3_context*);
   76168   int (*extended_result_codes)(sqlite3*,int);
   76169   int (*limit)(sqlite3*,int,int);
   76170   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
   76171   const char *(*sql)(sqlite3_stmt*);
   76172   int (*status)(int,int*,int*,int);
   76173 };
   76174 
   76175 /*
   76176 ** The following macros redefine the API routines so that they are
   76177 ** redirected throught the global sqlite3_api structure.
   76178 **
   76179 ** This header file is also used by the loadext.c source file
   76180 ** (part of the main SQLite library - not an extension) so that
   76181 ** it can get access to the sqlite3_api_routines structure
   76182 ** definition.  But the main library does not want to redefine
   76183 ** the API.  So the redefinition macros are only valid if the
   76184 ** SQLITE_CORE macros is undefined.
   76185 */
   76186 #ifndef SQLITE_CORE
   76187 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
   76188 #ifndef SQLITE_OMIT_DEPRECATED
   76189 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
   76190 #endif
   76191 #define sqlite3_bind_blob              sqlite3_api->bind_blob
   76192 #define sqlite3_bind_double            sqlite3_api->bind_double
   76193 #define sqlite3_bind_int               sqlite3_api->bind_int
   76194 #define sqlite3_bind_int64             sqlite3_api->bind_int64
   76195 #define sqlite3_bind_null              sqlite3_api->bind_null
   76196 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
   76197 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
   76198 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
   76199 #define sqlite3_bind_text              sqlite3_api->bind_text
   76200 #define sqlite3_bind_text16            sqlite3_api->bind_text16
   76201 #define sqlite3_bind_value             sqlite3_api->bind_value
   76202 #define sqlite3_busy_handler           sqlite3_api->busy_handler
   76203 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
   76204 #define sqlite3_changes                sqlite3_api->changes
   76205 #define sqlite3_close                  sqlite3_api->close
   76206 #define sqlite3_collation_needed       sqlite3_api->collation_needed
   76207 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
   76208 #define sqlite3_column_blob            sqlite3_api->column_blob
   76209 #define sqlite3_column_bytes           sqlite3_api->column_bytes
   76210 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
   76211 #define sqlite3_column_count           sqlite3_api->column_count
   76212 #define sqlite3_column_database_name   sqlite3_api->column_database_name
   76213 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
   76214 #define sqlite3_column_decltype        sqlite3_api->column_decltype
   76215 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
   76216 #define sqlite3_column_double          sqlite3_api->column_double
   76217 #define sqlite3_column_int             sqlite3_api->column_int
   76218 #define sqlite3_column_int64           sqlite3_api->column_int64
   76219 #define sqlite3_column_name            sqlite3_api->column_name
   76220 #define sqlite3_column_name16          sqlite3_api->column_name16
   76221 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
   76222 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
   76223 #define sqlite3_column_table_name      sqlite3_api->column_table_name
   76224 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
   76225 #define sqlite3_column_text            sqlite3_api->column_text
   76226 #define sqlite3_column_text16          sqlite3_api->column_text16
   76227 #define sqlite3_column_type            sqlite3_api->column_type
   76228 #define sqlite3_column_value           sqlite3_api->column_value
   76229 #define sqlite3_commit_hook            sqlite3_api->commit_hook
   76230 #define sqlite3_complete               sqlite3_api->complete
   76231 #define sqlite3_complete16             sqlite3_api->complete16
   76232 #define sqlite3_create_collation       sqlite3_api->create_collation
   76233 #define sqlite3_create_collation16     sqlite3_api->create_collation16
   76234 #define sqlite3_create_function        sqlite3_api->create_function
   76235 #define sqlite3_create_function16      sqlite3_api->create_function16
   76236 #define sqlite3_create_module          sqlite3_api->create_module
   76237 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
   76238 #define sqlite3_data_count             sqlite3_api->data_count
   76239 #define sqlite3_db_handle              sqlite3_api->db_handle
   76240 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
   76241 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
   76242 #define sqlite3_errcode                sqlite3_api->errcode
   76243 #define sqlite3_errmsg                 sqlite3_api->errmsg
   76244 #define sqlite3_errmsg16               sqlite3_api->errmsg16
   76245 #define sqlite3_exec                   sqlite3_api->exec
   76246 #ifndef SQLITE_OMIT_DEPRECATED
   76247 #define sqlite3_expired                sqlite3_api->expired
   76248 #endif
   76249 #define sqlite3_finalize               sqlite3_api->finalize
   76250 #define sqlite3_free                   sqlite3_api->free
   76251 #define sqlite3_free_table             sqlite3_api->free_table
   76252 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
   76253 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
   76254 #define sqlite3_get_table              sqlite3_api->get_table
   76255 #ifndef SQLITE_OMIT_DEPRECATED
   76256 #define sqlite3_global_recover         sqlite3_api->global_recover
   76257 #endif
   76258 #define sqlite3_interrupt              sqlite3_api->interruptx
   76259 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
   76260 #define sqlite3_libversion             sqlite3_api->libversion
   76261 #define sqlite3_libversion_number      sqlite3_api->libversion_number
   76262 #define sqlite3_malloc                 sqlite3_api->malloc
   76263 #define sqlite3_mprintf                sqlite3_api->mprintf
   76264 #define sqlite3_open                   sqlite3_api->open
   76265 #define sqlite3_open16                 sqlite3_api->open16
   76266 #define sqlite3_prepare                sqlite3_api->prepare
   76267 #define sqlite3_prepare16              sqlite3_api->prepare16
   76268 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
   76269 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
   76270 #define sqlite3_profile                sqlite3_api->profile
   76271 #define sqlite3_progress_handler       sqlite3_api->progress_handler
   76272 #define sqlite3_realloc                sqlite3_api->realloc
   76273 #define sqlite3_reset                  sqlite3_api->reset
   76274 #define sqlite3_result_blob            sqlite3_api->result_blob
   76275 #define sqlite3_result_double          sqlite3_api->result_double
   76276 #define sqlite3_result_error           sqlite3_api->result_error
   76277 #define sqlite3_result_error16         sqlite3_api->result_error16
   76278 #define sqlite3_result_int             sqlite3_api->result_int
   76279 #define sqlite3_result_int64           sqlite3_api->result_int64
   76280 #define sqlite3_result_null            sqlite3_api->result_null
   76281 #define sqlite3_result_text            sqlite3_api->result_text
   76282 #define sqlite3_result_text16          sqlite3_api->result_text16
   76283 #define sqlite3_result_text16be        sqlite3_api->result_text16be
   76284 #define sqlite3_result_text16le        sqlite3_api->result_text16le
   76285 #define sqlite3_result_value           sqlite3_api->result_value
   76286 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
   76287 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
   76288 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
   76289 #define sqlite3_snprintf               sqlite3_api->snprintf
   76290 #define sqlite3_step                   sqlite3_api->step
   76291 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
   76292 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
   76293 #define sqlite3_total_changes          sqlite3_api->total_changes
   76294 #define sqlite3_trace                  sqlite3_api->trace
   76295 #ifndef SQLITE_OMIT_DEPRECATED
   76296 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
   76297 #endif
   76298 #define sqlite3_update_hook            sqlite3_api->update_hook
   76299 #define sqlite3_user_data              sqlite3_api->user_data
   76300 #define sqlite3_value_blob             sqlite3_api->value_blob
   76301 #define sqlite3_value_bytes            sqlite3_api->value_bytes
   76302 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
   76303 #define sqlite3_value_double           sqlite3_api->value_double
   76304 #define sqlite3_value_int              sqlite3_api->value_int
   76305 #define sqlite3_value_int64            sqlite3_api->value_int64
   76306 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
   76307 #define sqlite3_value_text             sqlite3_api->value_text
   76308 #define sqlite3_value_text16           sqlite3_api->value_text16
   76309 #define sqlite3_value_text16be         sqlite3_api->value_text16be
   76310 #define sqlite3_value_text16le         sqlite3_api->value_text16le
   76311 #define sqlite3_value_type             sqlite3_api->value_type
   76312 #define sqlite3_vmprintf               sqlite3_api->vmprintf
   76313 #define sqlite3_overload_function      sqlite3_api->overload_function
   76314 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
   76315 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
   76316 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
   76317 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
   76318 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
   76319 #define sqlite3_blob_close             sqlite3_api->blob_close
   76320 #define sqlite3_blob_open              sqlite3_api->blob_open
   76321 #define sqlite3_blob_read              sqlite3_api->blob_read
   76322 #define sqlite3_blob_write             sqlite3_api->blob_write
   76323 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
   76324 #define sqlite3_file_control           sqlite3_api->file_control
   76325 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
   76326 #define sqlite3_memory_used            sqlite3_api->memory_used
   76327 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
   76328 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
   76329 #define sqlite3_mutex_free             sqlite3_api->mutex_free
   76330 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
   76331 #define sqlite3_mutex_try              sqlite3_api->mutex_try
   76332 #define sqlite3_open_v2                sqlite3_api->open_v2
   76333 #define sqlite3_release_memory         sqlite3_api->release_memory
   76334 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
   76335 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
   76336 #define sqlite3_sleep                  sqlite3_api->sleep
   76337 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
   76338 #define sqlite3_vfs_find               sqlite3_api->vfs_find
   76339 #define sqlite3_vfs_register           sqlite3_api->vfs_register
   76340 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
   76341 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
   76342 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
   76343 #define sqlite3_result_error_code      sqlite3_api->result_error_code
   76344 #define sqlite3_test_control           sqlite3_api->test_control
   76345 #define sqlite3_randomness             sqlite3_api->randomness
   76346 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
   76347 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
   76348 #define sqlite3_limit                  sqlite3_api->limit
   76349 #define sqlite3_next_stmt              sqlite3_api->next_stmt
   76350 #define sqlite3_sql                    sqlite3_api->sql
   76351 #define sqlite3_status                 sqlite3_api->status
   76352 #endif /* SQLITE_CORE */
   76353 
   76354 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
   76355 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
   76356 
   76357 #endif /* _SQLITE3EXT_H_ */
   76358 
   76359 /************** End of sqlite3ext.h ******************************************/
   76360 /************** Continuing where we left off in loadext.c ********************/
   76361 
   76362 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   76363 
   76364 /*
   76365 ** Some API routines are omitted when various features are
   76366 ** excluded from a build of SQLite.  Substitute a NULL pointer
   76367 ** for any missing APIs.
   76368 */
   76369 #ifndef SQLITE_ENABLE_COLUMN_METADATA
   76370 # define sqlite3_column_database_name   0
   76371 # define sqlite3_column_database_name16 0
   76372 # define sqlite3_column_table_name      0
   76373 # define sqlite3_column_table_name16    0
   76374 # define sqlite3_column_origin_name     0
   76375 # define sqlite3_column_origin_name16   0
   76376 # define sqlite3_table_column_metadata  0
   76377 #endif
   76378 
   76379 #ifdef SQLITE_OMIT_AUTHORIZATION
   76380 # define sqlite3_set_authorizer         0
   76381 #endif
   76382 
   76383 #ifdef SQLITE_OMIT_UTF16
   76384 # define sqlite3_bind_text16            0
   76385 # define sqlite3_collation_needed16     0
   76386 # define sqlite3_column_decltype16      0
   76387 # define sqlite3_column_name16          0
   76388 # define sqlite3_column_text16          0
   76389 # define sqlite3_complete16             0
   76390 # define sqlite3_create_collation16     0
   76391 # define sqlite3_create_function16      0
   76392 # define sqlite3_errmsg16               0
   76393 # define sqlite3_open16                 0
   76394 # define sqlite3_prepare16              0
   76395 # define sqlite3_prepare16_v2           0
   76396 # define sqlite3_result_error16         0
   76397 # define sqlite3_result_text16          0
   76398 # define sqlite3_result_text16be        0
   76399 # define sqlite3_result_text16le        0
   76400 # define sqlite3_value_text16           0
   76401 # define sqlite3_value_text16be         0
   76402 # define sqlite3_value_text16le         0
   76403 # define sqlite3_column_database_name16 0
   76404 # define sqlite3_column_table_name16    0
   76405 # define sqlite3_column_origin_name16   0
   76406 #endif
   76407 
   76408 #ifdef SQLITE_OMIT_COMPLETE
   76409 # define sqlite3_complete 0
   76410 # define sqlite3_complete16 0
   76411 #endif
   76412 
   76413 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
   76414 # define sqlite3_progress_handler 0
   76415 #endif
   76416 
   76417 #ifdef SQLITE_OMIT_VIRTUALTABLE
   76418 # define sqlite3_create_module 0
   76419 # define sqlite3_create_module_v2 0
   76420 # define sqlite3_declare_vtab 0
   76421 #endif
   76422 
   76423 #ifdef SQLITE_OMIT_SHARED_CACHE
   76424 # define sqlite3_enable_shared_cache 0
   76425 #endif
   76426 
   76427 #ifdef SQLITE_OMIT_TRACE
   76428 # define sqlite3_profile       0
   76429 # define sqlite3_trace         0
   76430 #endif
   76431 
   76432 #ifdef SQLITE_OMIT_GET_TABLE
   76433 # define sqlite3_free_table    0
   76434 # define sqlite3_get_table     0
   76435 #endif
   76436 
   76437 #ifdef SQLITE_OMIT_INCRBLOB
   76438 #define sqlite3_bind_zeroblob  0
   76439 #define sqlite3_blob_bytes     0
   76440 #define sqlite3_blob_close     0
   76441 #define sqlite3_blob_open      0
   76442 #define sqlite3_blob_read      0
   76443 #define sqlite3_blob_write     0
   76444 #endif
   76445 
   76446 /*
   76447 ** The following structure contains pointers to all SQLite API routines.
   76448 ** A pointer to this structure is passed into extensions when they are
   76449 ** loaded so that the extension can make calls back into the SQLite
   76450 ** library.
   76451 **
   76452 ** When adding new APIs, add them to the bottom of this structure
   76453 ** in order to preserve backwards compatibility.
   76454 **
   76455 ** Extensions that use newer APIs should first call the
   76456 ** sqlite3_libversion_number() to make sure that the API they
   76457 ** intend to use is supported by the library.  Extensions should
   76458 ** also check to make sure that the pointer to the function is
   76459 ** not NULL before calling it.
   76460 */
   76461 static const sqlite3_api_routines sqlite3Apis = {
   76462   sqlite3_aggregate_context,
   76463 #ifndef SQLITE_OMIT_DEPRECATED
   76464   sqlite3_aggregate_count,
   76465 #else
   76466   0,
   76467 #endif
   76468   sqlite3_bind_blob,
   76469   sqlite3_bind_double,
   76470   sqlite3_bind_int,
   76471   sqlite3_bind_int64,
   76472   sqlite3_bind_null,
   76473   sqlite3_bind_parameter_count,
   76474   sqlite3_bind_parameter_index,
   76475   sqlite3_bind_parameter_name,
   76476   sqlite3_bind_text,
   76477   sqlite3_bind_text16,
   76478   sqlite3_bind_value,
   76479   sqlite3_busy_handler,
   76480   sqlite3_busy_timeout,
   76481   sqlite3_changes,
   76482   sqlite3_close,
   76483   sqlite3_collation_needed,
   76484   sqlite3_collation_needed16,
   76485   sqlite3_column_blob,
   76486   sqlite3_column_bytes,
   76487   sqlite3_column_bytes16,
   76488   sqlite3_column_count,
   76489   sqlite3_column_database_name,
   76490   sqlite3_column_database_name16,
   76491   sqlite3_column_decltype,
   76492   sqlite3_column_decltype16,
   76493   sqlite3_column_double,
   76494   sqlite3_column_int,
   76495   sqlite3_column_int64,
   76496   sqlite3_column_name,
   76497   sqlite3_column_name16,
   76498   sqlite3_column_origin_name,
   76499   sqlite3_column_origin_name16,
   76500   sqlite3_column_table_name,
   76501   sqlite3_column_table_name16,
   76502   sqlite3_column_text,
   76503   sqlite3_column_text16,
   76504   sqlite3_column_type,
   76505   sqlite3_column_value,
   76506   sqlite3_commit_hook,
   76507   sqlite3_complete,
   76508   sqlite3_complete16,
   76509   sqlite3_create_collation,
   76510   sqlite3_create_collation16,
   76511   sqlite3_create_function,
   76512   sqlite3_create_function16,
   76513   sqlite3_create_module,
   76514   sqlite3_data_count,
   76515   sqlite3_db_handle,
   76516   sqlite3_declare_vtab,
   76517   sqlite3_enable_shared_cache,
   76518   sqlite3_errcode,
   76519   sqlite3_errmsg,
   76520   sqlite3_errmsg16,
   76521   sqlite3_exec,
   76522 #ifndef SQLITE_OMIT_DEPRECATED
   76523   sqlite3_expired,
   76524 #else
   76525   0,
   76526 #endif
   76527   sqlite3_finalize,
   76528   sqlite3_free,
   76529   sqlite3_free_table,
   76530   sqlite3_get_autocommit,
   76531   sqlite3_get_auxdata,
   76532   sqlite3_get_table,
   76533   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
   76534   sqlite3_interrupt,
   76535   sqlite3_last_insert_rowid,
   76536   sqlite3_libversion,
   76537   sqlite3_libversion_number,
   76538   sqlite3_malloc,
   76539   sqlite3_mprintf,
   76540   sqlite3_open,
   76541   sqlite3_open16,
   76542   sqlite3_prepare,
   76543   sqlite3_prepare16,
   76544   sqlite3_profile,
   76545   sqlite3_progress_handler,
   76546   sqlite3_realloc,
   76547   sqlite3_reset,
   76548   sqlite3_result_blob,
   76549   sqlite3_result_double,
   76550   sqlite3_result_error,
   76551   sqlite3_result_error16,
   76552   sqlite3_result_int,
   76553   sqlite3_result_int64,
   76554   sqlite3_result_null,
   76555   sqlite3_result_text,
   76556   sqlite3_result_text16,
   76557   sqlite3_result_text16be,
   76558   sqlite3_result_text16le,
   76559   sqlite3_result_value,
   76560   sqlite3_rollback_hook,
   76561   sqlite3_set_authorizer,
   76562   sqlite3_set_auxdata,
   76563   sqlite3_snprintf,
   76564   sqlite3_step,
   76565   sqlite3_table_column_metadata,
   76566 #ifndef SQLITE_OMIT_DEPRECATED
   76567   sqlite3_thread_cleanup,
   76568 #else
   76569   0,
   76570 #endif
   76571   sqlite3_total_changes,
   76572   sqlite3_trace,
   76573 #ifndef SQLITE_OMIT_DEPRECATED
   76574   sqlite3_transfer_bindings,
   76575 #else
   76576   0,
   76577 #endif
   76578   sqlite3_update_hook,
   76579   sqlite3_user_data,
   76580   sqlite3_value_blob,
   76581   sqlite3_value_bytes,
   76582   sqlite3_value_bytes16,
   76583   sqlite3_value_double,
   76584   sqlite3_value_int,
   76585   sqlite3_value_int64,
   76586   sqlite3_value_numeric_type,
   76587   sqlite3_value_text,
   76588   sqlite3_value_text16,
   76589   sqlite3_value_text16be,
   76590   sqlite3_value_text16le,
   76591   sqlite3_value_type,
   76592   sqlite3_vmprintf,
   76593   /*
   76594   ** The original API set ends here.  All extensions can call any
   76595   ** of the APIs above provided that the pointer is not NULL.  But
   76596   ** before calling APIs that follow, extension should check the
   76597   ** sqlite3_libversion_number() to make sure they are dealing with
   76598   ** a library that is new enough to support that API.
   76599   *************************************************************************
   76600   */
   76601   sqlite3_overload_function,
   76602 
   76603   /*
   76604   ** Added after 3.3.13
   76605   */
   76606   sqlite3_prepare_v2,
   76607   sqlite3_prepare16_v2,
   76608   sqlite3_clear_bindings,
   76609 
   76610   /*
   76611   ** Added for 3.4.1
   76612   */
   76613   sqlite3_create_module_v2,
   76614 
   76615   /*
   76616   ** Added for 3.5.0
   76617   */
   76618   sqlite3_bind_zeroblob,
   76619   sqlite3_blob_bytes,
   76620   sqlite3_blob_close,
   76621   sqlite3_blob_open,
   76622   sqlite3_blob_read,
   76623   sqlite3_blob_write,
   76624   sqlite3_create_collation_v2,
   76625   sqlite3_file_control,
   76626   sqlite3_memory_highwater,
   76627   sqlite3_memory_used,
   76628 #ifdef SQLITE_MUTEX_OMIT
   76629   0,
   76630   0,
   76631   0,
   76632   0,
   76633   0,
   76634 #else
   76635   sqlite3_mutex_alloc,
   76636   sqlite3_mutex_enter,
   76637   sqlite3_mutex_free,
   76638   sqlite3_mutex_leave,
   76639   sqlite3_mutex_try,
   76640 #endif
   76641   sqlite3_open_v2,
   76642   sqlite3_release_memory,
   76643   sqlite3_result_error_nomem,
   76644   sqlite3_result_error_toobig,
   76645   sqlite3_sleep,
   76646   sqlite3_soft_heap_limit,
   76647   sqlite3_vfs_find,
   76648   sqlite3_vfs_register,
   76649   sqlite3_vfs_unregister,
   76650 
   76651   /*
   76652   ** Added for 3.5.8
   76653   */
   76654   sqlite3_threadsafe,
   76655   sqlite3_result_zeroblob,
   76656   sqlite3_result_error_code,
   76657   sqlite3_test_control,
   76658   sqlite3_randomness,
   76659   sqlite3_context_db_handle,
   76660 
   76661   /*
   76662   ** Added for 3.6.0
   76663   */
   76664   sqlite3_extended_result_codes,
   76665   sqlite3_limit,
   76666   sqlite3_next_stmt,
   76667   sqlite3_sql,
   76668   sqlite3_status,
   76669 };
   76670 
   76671 /*
   76672 ** Attempt to load an SQLite extension library contained in the file
   76673 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
   76674 ** default entry point name (sqlite3_extension_init) is used.  Use
   76675 ** of the default name is recommended.
   76676 **
   76677 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
   76678 **
   76679 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
   76680 ** error message text.  The calling function should free this memory
   76681 ** by calling sqlite3DbFree(db, ).
   76682 */
   76683 static int sqlite3LoadExtension(
   76684   sqlite3 *db,          /* Load the extension into this database connection */
   76685   const char *zFile,    /* Name of the shared library containing extension */
   76686   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
   76687   char **pzErrMsg       /* Put error message here if not 0 */
   76688 ){
   76689   sqlite3_vfs *pVfs = db->pVfs;
   76690   void *handle;
   76691   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
   76692   char *zErrmsg = 0;
   76693   void **aHandle;
   76694   const int nMsg = 300;
   76695 
   76696   if( pzErrMsg ) *pzErrMsg = 0;
   76697 
   76698   /* Ticket #1863.  To avoid a creating security problems for older
   76699   ** applications that relink against newer versions of SQLite, the
   76700   ** ability to run load_extension is turned off by default.  One
   76701   ** must call sqlite3_enable_load_extension() to turn on extension
   76702   ** loading.  Otherwise you get the following error.
   76703   */
   76704   if( (db->flags & SQLITE_LoadExtension)==0 ){
   76705     if( pzErrMsg ){
   76706       *pzErrMsg = sqlite3_mprintf("not authorized");
   76707     }
   76708     return SQLITE_ERROR;
   76709   }
   76710 
   76711   if( zProc==0 ){
   76712     zProc = "sqlite3_extension_init";
   76713   }
   76714 
   76715   handle = sqlite3OsDlOpen(pVfs, zFile);
   76716   if( handle==0 ){
   76717     if( pzErrMsg ){
   76718       zErrmsg = sqlite3StackAllocZero(db, nMsg);
   76719       if( zErrmsg ){
   76720         sqlite3_snprintf(nMsg, zErrmsg,
   76721             "unable to open shared library [%s]", zFile);
   76722         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
   76723         *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
   76724         sqlite3StackFree(db, zErrmsg);
   76725       }
   76726     }
   76727     return SQLITE_ERROR;
   76728   }
   76729   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
   76730                    sqlite3OsDlSym(pVfs, handle, zProc);
   76731   if( xInit==0 ){
   76732     if( pzErrMsg ){
   76733       zErrmsg = sqlite3StackAllocZero(db, nMsg);
   76734       if( zErrmsg ){
   76735         sqlite3_snprintf(nMsg, zErrmsg,
   76736             "no entry point [%s] in shared library [%s]", zProc,zFile);
   76737         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
   76738         *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
   76739         sqlite3StackFree(db, zErrmsg);
   76740       }
   76741       sqlite3OsDlClose(pVfs, handle);
   76742     }
   76743     return SQLITE_ERROR;
   76744   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
   76745     if( pzErrMsg ){
   76746       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
   76747     }
   76748     sqlite3_free(zErrmsg);
   76749     sqlite3OsDlClose(pVfs, handle);
   76750     return SQLITE_ERROR;
   76751   }
   76752 
   76753   /* Append the new shared library handle to the db->aExtension array. */
   76754   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
   76755   if( aHandle==0 ){
   76756     return SQLITE_NOMEM;
   76757   }
   76758   if( db->nExtension>0 ){
   76759     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
   76760   }
   76761   sqlite3DbFree(db, db->aExtension);
   76762   db->aExtension = aHandle;
   76763 
   76764   db->aExtension[db->nExtension++] = handle;
   76765   return SQLITE_OK;
   76766 }
   76767 SQLITE_API int sqlite3_load_extension(
   76768   sqlite3 *db,          /* Load the extension into this database connection */
   76769   const char *zFile,    /* Name of the shared library containing extension */
   76770   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
   76771   char **pzErrMsg       /* Put error message here if not 0 */
   76772 ){
   76773   int rc;
   76774   sqlite3_mutex_enter(db->mutex);
   76775   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
   76776   rc = sqlite3ApiExit(db, rc);
   76777   sqlite3_mutex_leave(db->mutex);
   76778   return rc;
   76779 }
   76780 
   76781 /*
   76782 ** Call this routine when the database connection is closing in order
   76783 ** to clean up loaded extensions
   76784 */
   76785 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
   76786   int i;
   76787   assert( sqlite3_mutex_held(db->mutex) );
   76788   for(i=0; i<db->nExtension; i++){
   76789     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
   76790   }
   76791   sqlite3DbFree(db, db->aExtension);
   76792 }
   76793 
   76794 /*
   76795 ** Enable or disable extension loading.  Extension loading is disabled by
   76796 ** default so as not to open security holes in older applications.
   76797 */
   76798 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
   76799   sqlite3_mutex_enter(db->mutex);
   76800   if( onoff ){
   76801     db->flags |= SQLITE_LoadExtension;
   76802   }else{
   76803     db->flags &= ~SQLITE_LoadExtension;
   76804   }
   76805   sqlite3_mutex_leave(db->mutex);
   76806   return SQLITE_OK;
   76807 }
   76808 
   76809 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   76810 
   76811 /*
   76812 ** The auto-extension code added regardless of whether or not extension
   76813 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
   76814 ** code if regular extension loading is not available.  This is that
   76815 ** dummy pointer.
   76816 */
   76817 #ifdef SQLITE_OMIT_LOAD_EXTENSION
   76818 static const sqlite3_api_routines sqlite3Apis = { 0 };
   76819 #endif
   76820 
   76821 
   76822 /*
   76823 ** The following object holds the list of automatically loaded
   76824 ** extensions.
   76825 **
   76826 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
   76827 ** mutex must be held while accessing this list.
   76828 */
   76829 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
   76830 static SQLITE_WSD struct sqlite3AutoExtList {
   76831   int nExt;              /* Number of entries in aExt[] */
   76832   void (**aExt)(void);   /* Pointers to the extension init functions */
   76833 } sqlite3Autoext = { 0, 0 };
   76834 
   76835 /* The "wsdAutoext" macro will resolve to the autoextension
   76836 ** state vector.  If writable static data is unsupported on the target,
   76837 ** we have to locate the state vector at run-time.  In the more common
   76838 ** case where writable static data is supported, wsdStat can refer directly
   76839 ** to the "sqlite3Autoext" state vector declared above.
   76840 */
   76841 #ifdef SQLITE_OMIT_WSD
   76842 # define wsdAutoextInit \
   76843   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
   76844 # define wsdAutoext x[0]
   76845 #else
   76846 # define wsdAutoextInit
   76847 # define wsdAutoext sqlite3Autoext
   76848 #endif
   76849 
   76850 
   76851 /*
   76852 ** Register a statically linked extension that is automatically
   76853 ** loaded by every new database connection.
   76854 */
   76855 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
   76856   int rc = SQLITE_OK;
   76857 #ifndef SQLITE_OMIT_AUTOINIT
   76858   rc = sqlite3_initialize();
   76859   if( rc ){
   76860     return rc;
   76861   }else
   76862 #endif
   76863   {
   76864     int i;
   76865 #if SQLITE_THREADSAFE
   76866     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   76867 #endif
   76868     wsdAutoextInit;
   76869     sqlite3_mutex_enter(mutex);
   76870     for(i=0; i<wsdAutoext.nExt; i++){
   76871       if( wsdAutoext.aExt[i]==xInit ) break;
   76872     }
   76873     if( i==wsdAutoext.nExt ){
   76874       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
   76875       void (**aNew)(void);
   76876       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
   76877       if( aNew==0 ){
   76878         rc = SQLITE_NOMEM;
   76879       }else{
   76880         wsdAutoext.aExt = aNew;
   76881         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
   76882         wsdAutoext.nExt++;
   76883       }
   76884     }
   76885     sqlite3_mutex_leave(mutex);
   76886     assert( (rc&0xff)==rc );
   76887     return rc;
   76888   }
   76889 }
   76890 
   76891 /*
   76892 ** Reset the automatic extension loading mechanism.
   76893 */
   76894 SQLITE_API void sqlite3_reset_auto_extension(void){
   76895 #ifndef SQLITE_OMIT_AUTOINIT
   76896   if( sqlite3_initialize()==SQLITE_OK )
   76897 #endif
   76898   {
   76899 #if SQLITE_THREADSAFE
   76900     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   76901 #endif
   76902     wsdAutoextInit;
   76903     sqlite3_mutex_enter(mutex);
   76904     sqlite3_free(wsdAutoext.aExt);
   76905     wsdAutoext.aExt = 0;
   76906     wsdAutoext.nExt = 0;
   76907     sqlite3_mutex_leave(mutex);
   76908   }
   76909 }
   76910 
   76911 /*
   76912 ** Load all automatic extensions.
   76913 **
   76914 ** If anything goes wrong, set an error in the database connection.
   76915 */
   76916 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
   76917   int i;
   76918   int go = 1;
   76919   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
   76920 
   76921   wsdAutoextInit;
   76922   if( wsdAutoext.nExt==0 ){
   76923     /* Common case: early out without every having to acquire a mutex */
   76924     return;
   76925   }
   76926   for(i=0; go; i++){
   76927     char *zErrmsg;
   76928 #if SQLITE_THREADSAFE
   76929     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   76930 #endif
   76931     sqlite3_mutex_enter(mutex);
   76932     if( i>=wsdAutoext.nExt ){
   76933       xInit = 0;
   76934       go = 0;
   76935     }else{
   76936       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
   76937               wsdAutoext.aExt[i];
   76938     }
   76939     sqlite3_mutex_leave(mutex);
   76940     zErrmsg = 0;
   76941     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
   76942       sqlite3Error(db, SQLITE_ERROR,
   76943             "automatic extension loading failed: %s", zErrmsg);
   76944       go = 0;
   76945     }
   76946     sqlite3_free(zErrmsg);
   76947   }
   76948 }
   76949 
   76950 /************** End of loadext.c *********************************************/
   76951 /************** Begin file pragma.c ******************************************/
   76952 /*
   76953 ** 2003 April 6
   76954 **
   76955 ** The author disclaims copyright to this source code.  In place of
   76956 ** a legal notice, here is a blessing:
   76957 **
   76958 **    May you do good and not evil.
   76959 **    May you find forgiveness for yourself and forgive others.
   76960 **    May you share freely, never taking more than you give.
   76961 **
   76962 *************************************************************************
   76963 ** This file contains code used to implement the PRAGMA command.
   76964 */
   76965 
   76966 /* Ignore this whole file if pragmas are disabled
   76967 */
   76968 #if !defined(SQLITE_OMIT_PRAGMA)
   76969 
   76970 /*
   76971 ** Interpret the given string as a safety level.  Return 0 for OFF,
   76972 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
   76973 ** unrecognized string argument.
   76974 **
   76975 ** Note that the values returned are one less that the values that
   76976 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
   76977 ** to support legacy SQL code.  The safety level used to be boolean
   76978 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
   76979 */
   76980 static u8 getSafetyLevel(const char *z){
   76981                              /* 123456789 123456789 */
   76982   static const char zText[] = "onoffalseyestruefull";
   76983   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
   76984   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
   76985   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
   76986   int i, n;
   76987   if( sqlite3Isdigit(*z) ){
   76988     return (u8)atoi(z);
   76989   }
   76990   n = sqlite3Strlen30(z);
   76991   for(i=0; i<ArraySize(iLength); i++){
   76992     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
   76993       return iValue[i];
   76994     }
   76995   }
   76996   return 1;
   76997 }
   76998 
   76999 /*
   77000 ** Interpret the given string as a boolean value.
   77001 */
   77002 static u8 getBoolean(const char *z){
   77003   return getSafetyLevel(z)&1;
   77004 }
   77005 
   77006 /*
   77007 ** Interpret the given string as a locking mode value.
   77008 */
   77009 static int getLockingMode(const char *z){
   77010   if( z ){
   77011     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
   77012     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
   77013   }
   77014   return PAGER_LOCKINGMODE_QUERY;
   77015 }
   77016 
   77017 #ifndef SQLITE_OMIT_AUTOVACUUM
   77018 /*
   77019 ** Interpret the given string as an auto-vacuum mode value.
   77020 **
   77021 ** The following strings, "none", "full" and "incremental" are
   77022 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
   77023 */
   77024 static int getAutoVacuum(const char *z){
   77025   int i;
   77026   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
   77027   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
   77028   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
   77029   i = atoi(z);
   77030   return (u8)((i>=0&&i<=2)?i:0);
   77031 }
   77032 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
   77033 
   77034 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   77035 /*
   77036 ** Interpret the given string as a temp db location. Return 1 for file
   77037 ** backed temporary databases, 2 for the Red-Black tree in memory database
   77038 ** and 0 to use the compile-time default.
   77039 */
   77040 static int getTempStore(const char *z){
   77041   if( z[0]>='0' && z[0]<='2' ){
   77042     return z[0] - '0';
   77043   }else if( sqlite3StrICmp(z, "file")==0 ){
   77044     return 1;
   77045   }else if( sqlite3StrICmp(z, "memory")==0 ){
   77046     return 2;
   77047   }else{
   77048     return 0;
   77049   }
   77050 }
   77051 #endif /* SQLITE_PAGER_PRAGMAS */
   77052 
   77053 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   77054 /*
   77055 ** Invalidate temp storage, either when the temp storage is changed
   77056 ** from default, or when 'file' and the temp_store_directory has changed
   77057 */
   77058 static int invalidateTempStorage(Parse *pParse){
   77059   sqlite3 *db = pParse->db;
   77060   if( db->aDb[1].pBt!=0 ){
   77061     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
   77062       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
   77063         "from within a transaction");
   77064       return SQLITE_ERROR;
   77065     }
   77066     sqlite3BtreeClose(db->aDb[1].pBt);
   77067     db->aDb[1].pBt = 0;
   77068     sqlite3ResetInternalSchema(db, 0);
   77069   }
   77070   return SQLITE_OK;
   77071 }
   77072 #endif /* SQLITE_PAGER_PRAGMAS */
   77073 
   77074 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   77075 /*
   77076 ** If the TEMP database is open, close it and mark the database schema
   77077 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
   77078 ** or DEFAULT_TEMP_STORE pragmas.
   77079 */
   77080 static int changeTempStorage(Parse *pParse, const char *zStorageType){
   77081   int ts = getTempStore(zStorageType);
   77082   sqlite3 *db = pParse->db;
   77083   if( db->temp_store==ts ) return SQLITE_OK;
   77084   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
   77085     return SQLITE_ERROR;
   77086   }
   77087   db->temp_store = (u8)ts;
   77088   return SQLITE_OK;
   77089 }
   77090 #endif /* SQLITE_PAGER_PRAGMAS */
   77091 
   77092 /*
   77093 ** Generate code to return a single integer value.
   77094 */
   77095 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
   77096   Vdbe *v = sqlite3GetVdbe(pParse);
   77097   int mem = ++pParse->nMem;
   77098   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
   77099   if( pI64 ){
   77100     memcpy(pI64, &value, sizeof(value));
   77101   }
   77102   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
   77103   sqlite3VdbeSetNumCols(v, 1);
   77104   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
   77105   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
   77106 }
   77107 
   77108 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
   77109 /*
   77110 ** Check to see if zRight and zLeft refer to a pragma that queries
   77111 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
   77112 ** Also, implement the pragma.
   77113 */
   77114 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
   77115   static const struct sPragmaType {
   77116     const char *zName;  /* Name of the pragma */
   77117     int mask;           /* Mask for the db->flags value */
   77118   } aPragma[] = {
   77119     { "full_column_names",        SQLITE_FullColNames  },
   77120     { "short_column_names",       SQLITE_ShortColNames },
   77121     { "count_changes",            SQLITE_CountRows     },
   77122     { "empty_result_callbacks",   SQLITE_NullCallback  },
   77123     { "legacy_file_format",       SQLITE_LegacyFileFmt },
   77124     { "fullfsync",                SQLITE_FullFSync     },
   77125     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
   77126 #ifdef SQLITE_DEBUG
   77127     { "sql_trace",                SQLITE_SqlTrace      },
   77128     { "vdbe_listing",             SQLITE_VdbeListing   },
   77129     { "vdbe_trace",               SQLITE_VdbeTrace     },
   77130 #endif
   77131 #ifndef SQLITE_OMIT_CHECK
   77132     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
   77133 #endif
   77134     /* The following is VERY experimental */
   77135     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
   77136     { "omit_readlock",            SQLITE_NoReadlock    },
   77137 
   77138     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
   77139     ** flag if there are any active statements. */
   77140     { "read_uncommitted",         SQLITE_ReadUncommitted },
   77141     { "recursive_triggers",       SQLITE_RecTriggers },
   77142 
   77143     /* This flag may only be set if both foreign-key and trigger support
   77144     ** are present in the build.  */
   77145 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   77146     { "foreign_keys",             SQLITE_ForeignKeys },
   77147 #endif
   77148   };
   77149   int i;
   77150   const struct sPragmaType *p;
   77151   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
   77152     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
   77153       sqlite3 *db = pParse->db;
   77154       Vdbe *v;
   77155       v = sqlite3GetVdbe(pParse);
   77156       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
   77157       if( ALWAYS(v) ){
   77158         if( zRight==0 ){
   77159           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
   77160         }else{
   77161           int mask = p->mask;          /* Mask of bits to set or clear. */
   77162           if( db->autoCommit==0 ){
   77163             /* Foreign key support may not be enabled or disabled while not
   77164             ** in auto-commit mode.  */
   77165             mask &= ~(SQLITE_ForeignKeys);
   77166           }
   77167 
   77168           if( getBoolean(zRight) ){
   77169             db->flags |= mask;
   77170           }else{
   77171             db->flags &= ~mask;
   77172           }
   77173 
   77174           /* Many of the flag-pragmas modify the code generated by the SQL
   77175           ** compiler (eg. count_changes). So add an opcode to expire all
   77176           ** compiled SQL statements after modifying a pragma value.
   77177           */
   77178           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
   77179         }
   77180       }
   77181 
   77182       return 1;
   77183     }
   77184   }
   77185   return 0;
   77186 }
   77187 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
   77188 
   77189 /*
   77190 ** Return a human-readable name for a constraint resolution action.
   77191 */
   77192 #ifndef SQLITE_OMIT_FOREIGN_KEY
   77193 static const char *actionName(u8 action){
   77194   const char *zName;
   77195   switch( action ){
   77196     case OE_SetNull:  zName = "SET NULL";        break;
   77197     case OE_SetDflt:  zName = "SET DEFAULT";     break;
   77198     case OE_Cascade:  zName = "CASCADE";         break;
   77199     case OE_Restrict: zName = "RESTRICT";        break;
   77200     default:          zName = "NO ACTION";
   77201                       assert( action==OE_None ); break;
   77202   }
   77203   return zName;
   77204 }
   77205 #endif
   77206 
   77207 /*
   77208 ** Process a pragma statement.
   77209 **
   77210 ** Pragmas are of this form:
   77211 **
   77212 **      PRAGMA [database.]id [= value]
   77213 **
   77214 ** The identifier might also be a string.  The value is a string, and
   77215 ** identifier, or a number.  If minusFlag is true, then the value is
   77216 ** a number that was preceded by a minus sign.
   77217 **
   77218 ** If the left side is "database.id" then pId1 is the database name
   77219 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
   77220 ** id and pId2 is any empty string.
   77221 */
   77222 SQLITE_PRIVATE void sqlite3Pragma(
   77223   Parse *pParse,
   77224   Token *pId1,        /* First part of [database.]id field */
   77225   Token *pId2,        /* Second part of [database.]id field, or NULL */
   77226   Token *pValue,      /* Token for <value>, or NULL */
   77227   int minusFlag       /* True if a '-' sign preceded <value> */
   77228 ){
   77229   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
   77230   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
   77231   const char *zDb = 0;   /* The database name */
   77232   Token *pId;            /* Pointer to <id> token */
   77233   int iDb;               /* Database index for <database> */
   77234   sqlite3 *db = pParse->db;
   77235   Db *pDb;
   77236   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
   77237   if( v==0 ) return;
   77238   sqlite3VdbeRunOnlyOnce(v);
   77239   pParse->nMem = 2;
   77240 
   77241   /* Interpret the [database.] part of the pragma statement. iDb is the
   77242   ** index of the database this pragma is being applied to in db.aDb[]. */
   77243   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
   77244   if( iDb<0 ) return;
   77245   pDb = &db->aDb[iDb];
   77246 
   77247   /* If the temp database has been explicitly named as part of the
   77248   ** pragma, make sure it is open.
   77249   */
   77250   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
   77251     return;
   77252   }
   77253 
   77254   zLeft = sqlite3NameFromToken(db, pId);
   77255   if( !zLeft ) return;
   77256   if( minusFlag ){
   77257     zRight = sqlite3MPrintf(db, "-%T", pValue);
   77258   }else{
   77259     zRight = sqlite3NameFromToken(db, pValue);
   77260   }
   77261 
   77262   assert( pId2 );
   77263   zDb = pId2->n>0 ? pDb->zName : 0;
   77264   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
   77265     goto pragma_out;
   77266   }
   77267 
   77268 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   77269   /*
   77270   **  PRAGMA [database.]default_cache_size
   77271   **  PRAGMA [database.]default_cache_size=N
   77272   **
   77273   ** The first form reports the current persistent setting for the
   77274   ** page cache size.  The value returned is the maximum number of
   77275   ** pages in the page cache.  The second form sets both the current
   77276   ** page cache size value and the persistent page cache size value
   77277   ** stored in the database file.
   77278   **
   77279   ** The default cache size is stored in meta-value 2 of page 1 of the
   77280   ** database file.  The cache size is actually the absolute value of
   77281   ** this memory location.  The sign of meta-value 2 determines the
   77282   ** synchronous setting.  A negative value means synchronous is off
   77283   ** and a positive value means synchronous is on.
   77284   */
   77285   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
   77286     static const VdbeOpList getCacheSize[] = {
   77287       { OP_Transaction, 0, 0,        0},                         /* 0 */
   77288       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
   77289       { OP_IfPos,       1, 7,        0},
   77290       { OP_Integer,     0, 2,        0},
   77291       { OP_Subtract,    1, 2,        1},
   77292       { OP_IfPos,       1, 7,        0},
   77293       { OP_Integer,     0, 1,        0},                         /* 6 */
   77294       { OP_ResultRow,   1, 1,        0},
   77295     };
   77296     int addr;
   77297     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   77298     sqlite3VdbeUsesBtree(v, iDb);
   77299     if( !zRight ){
   77300       sqlite3VdbeSetNumCols(v, 1);
   77301       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
   77302       pParse->nMem += 2;
   77303       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
   77304       sqlite3VdbeChangeP1(v, addr, iDb);
   77305       sqlite3VdbeChangeP1(v, addr+1, iDb);
   77306       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
   77307     }else{
   77308       int size = atoi(zRight);
   77309       if( size<0 ) size = -size;
   77310       sqlite3BeginWriteOperation(pParse, 0, iDb);
   77311       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
   77312       sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, BTREE_DEFAULT_CACHE_SIZE);
   77313       addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
   77314       sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
   77315       sqlite3VdbeJumpHere(v, addr);
   77316       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
   77317       pDb->pSchema->cache_size = size;
   77318       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   77319     }
   77320   }else
   77321 
   77322   /*
   77323   **  PRAGMA [database.]page_size
   77324   **  PRAGMA [database.]page_size=N
   77325   **
   77326   ** The first form reports the current setting for the
   77327   ** database page size in bytes.  The second form sets the
   77328   ** database page size value.  The value can only be set if
   77329   ** the database has not yet been created.
   77330   */
   77331   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
   77332     Btree *pBt = pDb->pBt;
   77333     assert( pBt!=0 );
   77334     if( !zRight ){
   77335       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
   77336       returnSingleInt(pParse, "page_size", size);
   77337     }else{
   77338       /* Malloc may fail when setting the page-size, as there is an internal
   77339       ** buffer that the pager module resizes using sqlite3_realloc().
   77340       */
   77341       db->nextPagesize = atoi(zRight);
   77342       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
   77343         db->mallocFailed = 1;
   77344       }
   77345     }
   77346   }else
   77347 
   77348   /*
   77349   **  PRAGMA [database.]max_page_count
   77350   **  PRAGMA [database.]max_page_count=N
   77351   **
   77352   ** The first form reports the current setting for the
   77353   ** maximum number of pages in the database file.  The
   77354   ** second form attempts to change this setting.  Both
   77355   ** forms return the current setting.
   77356   */
   77357   if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
   77358     Btree *pBt = pDb->pBt;
   77359     int newMax = 0;
   77360     assert( pBt!=0 );
   77361     if( zRight ){
   77362       newMax = atoi(zRight);
   77363     }
   77364     if( ALWAYS(pBt) ){
   77365       newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
   77366     }
   77367     returnSingleInt(pParse, "max_page_count", newMax);
   77368   }else
   77369 
   77370   /*
   77371   **  PRAGMA [database.]page_count
   77372   **
   77373   ** Return the number of pages in the specified database.
   77374   */
   77375   if( sqlite3StrICmp(zLeft,"page_count")==0 ){
   77376     int iReg;
   77377     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   77378     sqlite3CodeVerifySchema(pParse, iDb);
   77379     iReg = ++pParse->nMem;
   77380     sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
   77381     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
   77382     sqlite3VdbeSetNumCols(v, 1);
   77383     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
   77384   }else
   77385 
   77386   /*
   77387   **  PRAGMA [database.]locking_mode
   77388   **  PRAGMA [database.]locking_mode = (normal|exclusive)
   77389   */
   77390   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
   77391     const char *zRet = "normal";
   77392     int eMode = getLockingMode(zRight);
   77393 
   77394     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
   77395       /* Simple "PRAGMA locking_mode;" statement. This is a query for
   77396       ** the current default locking mode (which may be different to
   77397       ** the locking-mode of the main database).
   77398       */
   77399       eMode = db->dfltLockMode;
   77400     }else{
   77401       Pager *pPager;
   77402       if( pId2->n==0 ){
   77403         /* This indicates that no database name was specified as part
   77404         ** of the PRAGMA command. In this case the locking-mode must be
   77405         ** set on all attached databases, as well as the main db file.
   77406         **
   77407         ** Also, the sqlite3.dfltLockMode variable is set so that
   77408         ** any subsequently attached databases also use the specified
   77409         ** locking mode.
   77410         */
   77411         int ii;
   77412         assert(pDb==&db->aDb[0]);
   77413         for(ii=2; ii<db->nDb; ii++){
   77414           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
   77415           sqlite3PagerLockingMode(pPager, eMode);
   77416         }
   77417         db->dfltLockMode = (u8)eMode;
   77418       }
   77419       pPager = sqlite3BtreePager(pDb->pBt);
   77420       eMode = sqlite3PagerLockingMode(pPager, eMode);
   77421     }
   77422 
   77423     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
   77424     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
   77425       zRet = "exclusive";
   77426     }
   77427     sqlite3VdbeSetNumCols(v, 1);
   77428     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
   77429     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
   77430     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   77431   }else
   77432 
   77433   /*
   77434   **  PRAGMA [database.]journal_mode
   77435   **  PRAGMA [database.]journal_mode = (delete|persist|off|truncate|memory)
   77436   */
   77437   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
   77438     int eMode;
   77439     static char * const azModeName[] = {
   77440       "delete", "persist", "off", "truncate", "memory"
   77441     };
   77442 
   77443     if( zRight==0 ){
   77444       eMode = PAGER_JOURNALMODE_QUERY;
   77445     }else{
   77446       int n = sqlite3Strlen30(zRight);
   77447       eMode = sizeof(azModeName)/sizeof(azModeName[0]) - 1;
   77448       while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
   77449         eMode--;
   77450       }
   77451     }
   77452     if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
   77453       /* Simple "PRAGMA journal_mode;" statement. This is a query for
   77454       ** the current default journal mode (which may be different to
   77455       ** the journal-mode of the main database).
   77456       */
   77457       eMode = db->dfltJournalMode;
   77458     }else{
   77459       Pager *pPager;
   77460       if( pId2->n==0 ){
   77461         /* This indicates that no database name was specified as part
   77462         ** of the PRAGMA command. In this case the journal-mode must be
   77463         ** set on all attached databases, as well as the main db file.
   77464         **
   77465         ** Also, the sqlite3.dfltJournalMode variable is set so that
   77466         ** any subsequently attached databases also use the specified
   77467         ** journal mode.
   77468         */
   77469         int ii;
   77470         assert(pDb==&db->aDb[0]);
   77471         for(ii=1; ii<db->nDb; ii++){
   77472           if( db->aDb[ii].pBt ){
   77473             pPager = sqlite3BtreePager(db->aDb[ii].pBt);
   77474             sqlite3PagerJournalMode(pPager, eMode);
   77475           }
   77476         }
   77477         db->dfltJournalMode = (u8)eMode;
   77478       }
   77479       pPager = sqlite3BtreePager(pDb->pBt);
   77480       eMode = sqlite3PagerJournalMode(pPager, eMode);
   77481     }
   77482     assert( eMode==PAGER_JOURNALMODE_DELETE
   77483               || eMode==PAGER_JOURNALMODE_TRUNCATE
   77484               || eMode==PAGER_JOURNALMODE_PERSIST
   77485               || eMode==PAGER_JOURNALMODE_OFF
   77486               || eMode==PAGER_JOURNALMODE_MEMORY );
   77487     sqlite3VdbeSetNumCols(v, 1);
   77488     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
   77489     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0,
   77490            azModeName[eMode], P4_STATIC);
   77491     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   77492   }else
   77493 
   77494   /*
   77495   **  PRAGMA [database.]journal_size_limit
   77496   **  PRAGMA [database.]journal_size_limit=N
   77497   **
   77498   ** Get or set the size limit on rollback journal files.
   77499   */
   77500   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
   77501     Pager *pPager = sqlite3BtreePager(pDb->pBt);
   77502     i64 iLimit = -2;
   77503     if( zRight ){
   77504       sqlite3Atoi64(zRight, &iLimit);
   77505       if( iLimit<-1 ) iLimit = -1;
   77506     }
   77507     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
   77508     returnSingleInt(pParse, "journal_size_limit", iLimit);
   77509   }else
   77510 
   77511 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
   77512 
   77513   /*
   77514   **  PRAGMA [database.]auto_vacuum
   77515   **  PRAGMA [database.]auto_vacuum=N
   77516   **
   77517   ** Get or set the value of the database 'auto-vacuum' parameter.
   77518   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
   77519   */
   77520 #ifndef SQLITE_OMIT_AUTOVACUUM
   77521   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
   77522     Btree *pBt = pDb->pBt;
   77523     assert( pBt!=0 );
   77524     if( sqlite3ReadSchema(pParse) ){
   77525       goto pragma_out;
   77526     }
   77527     if( !zRight ){
   77528       int auto_vacuum;
   77529       if( ALWAYS(pBt) ){
   77530          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
   77531       }else{
   77532          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
   77533       }
   77534       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
   77535     }else{
   77536       int eAuto = getAutoVacuum(zRight);
   77537       assert( eAuto>=0 && eAuto<=2 );
   77538       db->nextAutovac = (u8)eAuto;
   77539       if( ALWAYS(eAuto>=0) ){
   77540         /* Call SetAutoVacuum() to set initialize the internal auto and
   77541         ** incr-vacuum flags. This is required in case this connection
   77542         ** creates the database file. It is important that it is created
   77543         ** as an auto-vacuum capable db.
   77544         */
   77545         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
   77546         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
   77547           /* When setting the auto_vacuum mode to either "full" or
   77548           ** "incremental", write the value of meta[6] in the database
   77549           ** file. Before writing to meta[6], check that meta[3] indicates
   77550           ** that this really is an auto-vacuum capable database.
   77551           */
   77552           static const VdbeOpList setMeta6[] = {
   77553             { OP_Transaction,    0,         1,                 0},    /* 0 */
   77554             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
   77555             { OP_If,             1,         0,                 0},    /* 2 */
   77556             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
   77557             { OP_Integer,        0,         1,                 0},    /* 4 */
   77558             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
   77559           };
   77560           int iAddr;
   77561           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
   77562           sqlite3VdbeChangeP1(v, iAddr, iDb);
   77563           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
   77564           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
   77565           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
   77566           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
   77567           sqlite3VdbeUsesBtree(v, iDb);
   77568         }
   77569       }
   77570     }
   77571   }else
   77572 #endif
   77573 
   77574   /*
   77575   **  PRAGMA [database.]incremental_vacuum(N)
   77576   **
   77577   ** Do N steps of incremental vacuuming on a database.
   77578   */
   77579 #ifndef SQLITE_OMIT_AUTOVACUUM
   77580   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
   77581     int iLimit, addr;
   77582     if( sqlite3ReadSchema(pParse) ){
   77583       goto pragma_out;
   77584     }
   77585     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
   77586       iLimit = 0x7fffffff;
   77587     }
   77588     sqlite3BeginWriteOperation(pParse, 0, iDb);
   77589     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
   77590     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
   77591     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
   77592     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
   77593     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
   77594     sqlite3VdbeJumpHere(v, addr);
   77595   }else
   77596 #endif
   77597 
   77598 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   77599   /*
   77600   **  PRAGMA [database.]cache_size
   77601   **  PRAGMA [database.]cache_size=N
   77602   **
   77603   ** The first form reports the current local setting for the
   77604   ** page cache size.  The local setting can be different from
   77605   ** the persistent cache size value that is stored in the database
   77606   ** file itself.  The value returned is the maximum number of
   77607   ** pages in the page cache.  The second form sets the local
   77608   ** page cache size value.  It does not change the persistent
   77609   ** cache size stored on the disk so the cache size will revert
   77610   ** to its default value when the database is closed and reopened.
   77611   ** N should be a positive integer.
   77612   */
   77613   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
   77614     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   77615     if( !zRight ){
   77616       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
   77617     }else{
   77618       int size = atoi(zRight);
   77619       if( size<0 ) size = -size;
   77620       pDb->pSchema->cache_size = size;
   77621       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   77622     }
   77623   }else
   77624 
   77625   /*
   77626   **   PRAGMA temp_store
   77627   **   PRAGMA temp_store = "default"|"memory"|"file"
   77628   **
   77629   ** Return or set the local value of the temp_store flag.  Changing
   77630   ** the local value does not make changes to the disk file and the default
   77631   ** value will be restored the next time the database is opened.
   77632   **
   77633   ** Note that it is possible for the library compile-time options to
   77634   ** override this setting
   77635   */
   77636   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
   77637     if( !zRight ){
   77638       returnSingleInt(pParse, "temp_store", db->temp_store);
   77639     }else{
   77640       changeTempStorage(pParse, zRight);
   77641     }
   77642   }else
   77643 
   77644   /*
   77645   **   PRAGMA temp_store_directory
   77646   **   PRAGMA temp_store_directory = ""|"directory_name"
   77647   **
   77648   ** Return or set the local value of the temp_store_directory flag.  Changing
   77649   ** the value sets a specific directory to be used for temporary files.
   77650   ** Setting to a null string reverts to the default temporary directory search.
   77651   ** If temporary directory is changed, then invalidateTempStorage.
   77652   **
   77653   */
   77654   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
   77655     if( !zRight ){
   77656       if( sqlite3_temp_directory ){
   77657         sqlite3VdbeSetNumCols(v, 1);
   77658         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
   77659             "temp_store_directory", SQLITE_STATIC);
   77660         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
   77661         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   77662       }
   77663     }else{
   77664 #ifndef SQLITE_OMIT_WSD
   77665       if( zRight[0] ){
   77666         int rc;
   77667         int res;
   77668         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
   77669         if( rc!=SQLITE_OK || res==0 ){
   77670           sqlite3ErrorMsg(pParse, "not a writable directory");
   77671           goto pragma_out;
   77672         }
   77673       }
   77674       if( SQLITE_TEMP_STORE==0
   77675        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
   77676        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
   77677       ){
   77678         invalidateTempStorage(pParse);
   77679       }
   77680       sqlite3_free(sqlite3_temp_directory);
   77681       if( zRight[0] ){
   77682         sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
   77683       }else{
   77684         sqlite3_temp_directory = 0;
   77685       }
   77686 #endif /* SQLITE_OMIT_WSD */
   77687     }
   77688   }else
   77689 
   77690 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
   77691 #  if defined(__APPLE__)
   77692 #    define SQLITE_ENABLE_LOCKING_STYLE 1
   77693 #  else
   77694 #    define SQLITE_ENABLE_LOCKING_STYLE 0
   77695 #  endif
   77696 #endif
   77697 #if SQLITE_ENABLE_LOCKING_STYLE
   77698   /*
   77699    **   PRAGMA [database.]lock_proxy_file
   77700    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
   77701    **
   77702    ** Return or set the value of the lock_proxy_file flag.  Changing
   77703    ** the value sets a specific file to be used for database access locks.
   77704    **
   77705    */
   77706   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
   77707     if( !zRight ){
   77708       Pager *pPager = sqlite3BtreePager(pDb->pBt);
   77709       char *proxy_file_path = NULL;
   77710       sqlite3_file *pFile = sqlite3PagerFile(pPager);
   77711       sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE,
   77712                            &proxy_file_path);
   77713 
   77714       if( proxy_file_path ){
   77715         sqlite3VdbeSetNumCols(v, 1);
   77716         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
   77717                               "lock_proxy_file", SQLITE_STATIC);
   77718         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
   77719         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   77720       }
   77721     }else{
   77722       Pager *pPager = sqlite3BtreePager(pDb->pBt);
   77723       sqlite3_file *pFile = sqlite3PagerFile(pPager);
   77724       int res;
   77725       if( zRight[0] ){
   77726         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
   77727                                      zRight);
   77728       } else {
   77729         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
   77730                                      NULL);
   77731       }
   77732       if( res!=SQLITE_OK ){
   77733         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
   77734         goto pragma_out;
   77735       }
   77736     }
   77737   }else
   77738 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
   77739 
   77740   /*
   77741   **   PRAGMA [database.]synchronous
   77742   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
   77743   **
   77744   ** Return or set the local value of the synchronous flag.  Changing
   77745   ** the local value does not make changes to the disk file and the
   77746   ** default value will be restored the next time the database is
   77747   ** opened.
   77748   */
   77749   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
   77750     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   77751     if( !zRight ){
   77752       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
   77753     }else{
   77754       if( !db->autoCommit ){
   77755         sqlite3ErrorMsg(pParse,
   77756             "Safety level may not be changed inside a transaction");
   77757       }else{
   77758         pDb->safety_level = getSafetyLevel(zRight)+1;
   77759       }
   77760     }
   77761   }else
   77762 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
   77763 
   77764 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
   77765   if( flagPragma(pParse, zLeft, zRight) ){
   77766     /* The flagPragma() subroutine also generates any necessary code
   77767     ** there is nothing more to do here */
   77768   }else
   77769 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
   77770 
   77771 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
   77772   /*
   77773   **   PRAGMA table_info(<table>)
   77774   **
   77775   ** Return a single row for each column of the named table. The columns of
   77776   ** the returned data set are:
   77777   **
   77778   ** cid:        Column id (numbered from left to right, starting at 0)
   77779   ** name:       Column name
   77780   ** type:       Column declaration type.
   77781   ** notnull:    True if 'NOT NULL' is part of column declaration
   77782   ** dflt_value: The default value for the column, if any.
   77783   */
   77784   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
   77785     Table *pTab;
   77786     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   77787     pTab = sqlite3FindTable(db, zRight, zDb);
   77788     if( pTab ){
   77789       int i;
   77790       int nHidden = 0;
   77791       Column *pCol;
   77792       sqlite3VdbeSetNumCols(v, 6);
   77793       pParse->nMem = 6;
   77794       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
   77795       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   77796       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
   77797       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
   77798       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
   77799       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
   77800       sqlite3ViewGetColumnNames(pParse, pTab);
   77801       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
   77802         if( IsHiddenColumn(pCol) ){
   77803           nHidden++;
   77804           continue;
   77805         }
   77806         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
   77807         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
   77808         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   77809            pCol->zType ? pCol->zType : "", 0);
   77810         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
   77811         if( pCol->zDflt ){
   77812           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
   77813         }else{
   77814           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
   77815         }
   77816         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
   77817         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
   77818       }
   77819     }
   77820   }else
   77821 
   77822   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
   77823     Index *pIdx;
   77824     Table *pTab;
   77825     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   77826     pIdx = sqlite3FindIndex(db, zRight, zDb);
   77827     if( pIdx ){
   77828       int i;
   77829       pTab = pIdx->pTable;
   77830       sqlite3VdbeSetNumCols(v, 3);
   77831       pParse->nMem = 3;
   77832       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
   77833       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
   77834       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
   77835       for(i=0; i<pIdx->nColumn; i++){
   77836         int cnum = pIdx->aiColumn[i];
   77837         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   77838         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
   77839         assert( pTab->nCol>cnum );
   77840         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
   77841         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   77842       }
   77843     }
   77844   }else
   77845 
   77846   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
   77847     Index *pIdx;
   77848     Table *pTab;
   77849     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   77850     pTab = sqlite3FindTable(db, zRight, zDb);
   77851     if( pTab ){
   77852       v = sqlite3GetVdbe(pParse);
   77853       pIdx = pTab->pIndex;
   77854       if( pIdx ){
   77855         int i = 0;
   77856         sqlite3VdbeSetNumCols(v, 3);
   77857         pParse->nMem = 3;
   77858         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   77859         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   77860         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
   77861         while(pIdx){
   77862           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   77863           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
   77864           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
   77865           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   77866           ++i;
   77867           pIdx = pIdx->pNext;
   77868         }
   77869       }
   77870     }
   77871   }else
   77872 
   77873   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
   77874     int i;
   77875     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   77876     sqlite3VdbeSetNumCols(v, 3);
   77877     pParse->nMem = 3;
   77878     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   77879     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   77880     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
   77881     for(i=0; i<db->nDb; i++){
   77882       if( db->aDb[i].pBt==0 ) continue;
   77883       assert( db->aDb[i].zName!=0 );
   77884       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   77885       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
   77886       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   77887            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
   77888       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   77889     }
   77890   }else
   77891 
   77892   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
   77893     int i = 0;
   77894     HashElem *p;
   77895     sqlite3VdbeSetNumCols(v, 2);
   77896     pParse->nMem = 2;
   77897     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   77898     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   77899     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
   77900       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
   77901       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
   77902       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
   77903       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
   77904     }
   77905   }else
   77906 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
   77907 
   77908 #ifndef SQLITE_OMIT_FOREIGN_KEY
   77909   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
   77910     FKey *pFK;
   77911     Table *pTab;
   77912     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   77913     pTab = sqlite3FindTable(db, zRight, zDb);
   77914     if( pTab ){
   77915       v = sqlite3GetVdbe(pParse);
   77916       pFK = pTab->pFKey;
   77917       if( pFK ){
   77918         int i = 0;
   77919         sqlite3VdbeSetNumCols(v, 8);
   77920         pParse->nMem = 8;
   77921         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
   77922         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
   77923         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
   77924         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
   77925         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
   77926         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
   77927         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
   77928         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
   77929         while(pFK){
   77930           int j;
   77931           for(j=0; j<pFK->nCol; j++){
   77932             char *zCol = pFK->aCol[j].zCol;
   77933             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
   77934             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
   77935             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   77936             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
   77937             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
   77938             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
   77939                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
   77940             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
   77941             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
   77942             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
   77943             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
   77944             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
   77945           }
   77946           ++i;
   77947           pFK = pFK->pNextFrom;
   77948         }
   77949       }
   77950     }
   77951   }else
   77952 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   77953 
   77954 #ifndef NDEBUG
   77955   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
   77956     if( zRight ){
   77957       if( getBoolean(zRight) ){
   77958         sqlite3ParserTrace(stderr, "parser: ");
   77959       }else{
   77960         sqlite3ParserTrace(0, 0);
   77961       }
   77962     }
   77963   }else
   77964 #endif
   77965 
   77966   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
   77967   ** used will be case sensitive or not depending on the RHS.
   77968   */
   77969   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
   77970     if( zRight ){
   77971       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
   77972     }
   77973   }else
   77974 
   77975 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
   77976 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
   77977 #endif
   77978 
   77979 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   77980   /* Pragma "quick_check" is an experimental reduced version of
   77981   ** integrity_check designed to detect most database corruption
   77982   ** without most of the overhead of a full integrity-check.
   77983   */
   77984   if( sqlite3StrICmp(zLeft, "integrity_check")==0
   77985    || sqlite3StrICmp(zLeft, "quick_check")==0
   77986   ){
   77987     int i, j, addr, mxErr;
   77988 
   77989     /* Code that appears at the end of the integrity check.  If no error
   77990     ** messages have been generated, output OK.  Otherwise output the
   77991     ** error message
   77992     */
   77993     static const VdbeOpList endCode[] = {
   77994       { OP_AddImm,      1, 0,        0},    /* 0 */
   77995       { OP_IfNeg,       1, 0,        0},    /* 1 */
   77996       { OP_String8,     0, 3,        0},    /* 2 */
   77997       { OP_ResultRow,   3, 1,        0},
   77998     };
   77999 
   78000     int isQuick = (zLeft[0]=='q');
   78001 
   78002     /* Initialize the VDBE program */
   78003     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   78004     pParse->nMem = 6;
   78005     sqlite3VdbeSetNumCols(v, 1);
   78006     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
   78007 
   78008     /* Set the maximum error count */
   78009     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
   78010     if( zRight ){
   78011       mxErr = atoi(zRight);
   78012       if( mxErr<=0 ){
   78013         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
   78014       }
   78015     }
   78016     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
   78017 
   78018     /* Do an integrity check on each database file */
   78019     for(i=0; i<db->nDb; i++){
   78020       HashElem *x;
   78021       Hash *pTbls;
   78022       int cnt = 0;
   78023 
   78024       if( OMIT_TEMPDB && i==1 ) continue;
   78025 
   78026       sqlite3CodeVerifySchema(pParse, i);
   78027       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
   78028       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   78029       sqlite3VdbeJumpHere(v, addr);
   78030 
   78031       /* Do an integrity check of the B-Tree
   78032       **
   78033       ** Begin by filling registers 2, 3, ... with the root pages numbers
   78034       ** for all tables and indices in the database.
   78035       */
   78036       pTbls = &db->aDb[i].pSchema->tblHash;
   78037       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
   78038         Table *pTab = sqliteHashData(x);
   78039         Index *pIdx;
   78040         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
   78041         cnt++;
   78042         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   78043           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
   78044           cnt++;
   78045         }
   78046       }
   78047 
   78048       /* Make sure sufficient number of registers have been allocated */
   78049       if( pParse->nMem < cnt+4 ){
   78050         pParse->nMem = cnt+4;
   78051       }
   78052 
   78053       /* Do the b-tree integrity checks */
   78054       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
   78055       sqlite3VdbeChangeP5(v, (u8)i);
   78056       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
   78057       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   78058          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
   78059          P4_DYNAMIC);
   78060       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
   78061       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
   78062       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
   78063       sqlite3VdbeJumpHere(v, addr);
   78064 
   78065       /* Make sure all the indices are constructed correctly.
   78066       */
   78067       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
   78068         Table *pTab = sqliteHashData(x);
   78069         Index *pIdx;
   78070         int loopTop;
   78071 
   78072         if( pTab->pIndex==0 ) continue;
   78073         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
   78074         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   78075         sqlite3VdbeJumpHere(v, addr);
   78076         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
   78077         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
   78078         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
   78079         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
   78080         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   78081           int jmp2;
   78082           int r1;
   78083           static const VdbeOpList idxErr[] = {
   78084             { OP_AddImm,      1, -1,  0},
   78085             { OP_String8,     0,  3,  0},    /* 1 */
   78086             { OP_Rowid,       1,  4,  0},
   78087             { OP_String8,     0,  5,  0},    /* 3 */
   78088             { OP_String8,     0,  6,  0},    /* 4 */
   78089             { OP_Concat,      4,  3,  3},
   78090             { OP_Concat,      5,  3,  3},
   78091             { OP_Concat,      6,  3,  3},
   78092             { OP_ResultRow,   3,  1,  0},
   78093             { OP_IfPos,       1,  0,  0},    /* 9 */
   78094             { OP_Halt,        0,  0,  0},
   78095           };
   78096           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
   78097           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
   78098           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
   78099           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
   78100           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
   78101           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
   78102           sqlite3VdbeJumpHere(v, addr+9);
   78103           sqlite3VdbeJumpHere(v, jmp2);
   78104         }
   78105         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
   78106         sqlite3VdbeJumpHere(v, loopTop);
   78107         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   78108           static const VdbeOpList cntIdx[] = {
   78109              { OP_Integer,      0,  3,  0},
   78110              { OP_Rewind,       0,  0,  0},  /* 1 */
   78111              { OP_AddImm,       3,  1,  0},
   78112              { OP_Next,         0,  0,  0},  /* 3 */
   78113              { OP_Eq,           2,  0,  3},  /* 4 */
   78114              { OP_AddImm,       1, -1,  0},
   78115              { OP_String8,      0,  2,  0},  /* 6 */
   78116              { OP_String8,      0,  3,  0},  /* 7 */
   78117              { OP_Concat,       3,  2,  2},
   78118              { OP_ResultRow,    2,  1,  0},
   78119           };
   78120           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
   78121           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   78122           sqlite3VdbeJumpHere(v, addr);
   78123           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
   78124           sqlite3VdbeChangeP1(v, addr+1, j+2);
   78125           sqlite3VdbeChangeP2(v, addr+1, addr+4);
   78126           sqlite3VdbeChangeP1(v, addr+3, j+2);
   78127           sqlite3VdbeChangeP2(v, addr+3, addr+2);
   78128           sqlite3VdbeJumpHere(v, addr+4);
   78129           sqlite3VdbeChangeP4(v, addr+6,
   78130                      "wrong # of entries in index ", P4_STATIC);
   78131           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
   78132         }
   78133       }
   78134     }
   78135     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
   78136     sqlite3VdbeChangeP2(v, addr, -mxErr);
   78137     sqlite3VdbeJumpHere(v, addr+1);
   78138     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
   78139   }else
   78140 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   78141 
   78142 #ifndef SQLITE_OMIT_UTF16
   78143   /*
   78144   **   PRAGMA encoding
   78145   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
   78146   **
   78147   ** In its first form, this pragma returns the encoding of the main
   78148   ** database. If the database is not initialized, it is initialized now.
   78149   **
   78150   ** The second form of this pragma is a no-op if the main database file
   78151   ** has not already been initialized. In this case it sets the default
   78152   ** encoding that will be used for the main database file if a new file
   78153   ** is created. If an existing main database file is opened, then the
   78154   ** default text encoding for the existing database is used.
   78155   **
   78156   ** In all cases new databases created using the ATTACH command are
   78157   ** created to use the same default text encoding as the main database. If
   78158   ** the main database has not been initialized and/or created when ATTACH
   78159   ** is executed, this is done before the ATTACH operation.
   78160   **
   78161   ** In the second form this pragma sets the text encoding to be used in
   78162   ** new database files created using this database handle. It is only
   78163   ** useful if invoked immediately after the main database i
   78164   */
   78165   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
   78166     static const struct EncName {
   78167       char *zName;
   78168       u8 enc;
   78169     } encnames[] = {
   78170       { "UTF8",     SQLITE_UTF8        },
   78171       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
   78172       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
   78173       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
   78174       { "UTF16le",  SQLITE_UTF16LE     },
   78175       { "UTF16be",  SQLITE_UTF16BE     },
   78176       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
   78177       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
   78178       { 0, 0 }
   78179     };
   78180     const struct EncName *pEnc;
   78181     if( !zRight ){    /* "PRAGMA encoding" */
   78182       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   78183       sqlite3VdbeSetNumCols(v, 1);
   78184       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
   78185       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
   78186       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
   78187       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
   78188       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
   78189       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
   78190       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   78191     }else{                        /* "PRAGMA encoding = XXX" */
   78192       /* Only change the value of sqlite.enc if the database handle is not
   78193       ** initialized. If the main database exists, the new sqlite.enc value
   78194       ** will be overwritten when the schema is next loaded. If it does not
   78195       ** already exists, it will be created to use the new encoding value.
   78196       */
   78197       if(
   78198         !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
   78199         DbHasProperty(db, 0, DB_Empty)
   78200       ){
   78201         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
   78202           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
   78203             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
   78204             break;
   78205           }
   78206         }
   78207         if( !pEnc->zName ){
   78208           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
   78209         }
   78210       }
   78211     }
   78212   }else
   78213 #endif /* SQLITE_OMIT_UTF16 */
   78214 
   78215 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
   78216   /*
   78217   **   PRAGMA [database.]schema_version
   78218   **   PRAGMA [database.]schema_version = <integer>
   78219   **
   78220   **   PRAGMA [database.]user_version
   78221   **   PRAGMA [database.]user_version = <integer>
   78222   **
   78223   ** The pragma's schema_version and user_version are used to set or get
   78224   ** the value of the schema-version and user-version, respectively. Both
   78225   ** the schema-version and the user-version are 32-bit signed integers
   78226   ** stored in the database header.
   78227   **
   78228   ** The schema-cookie is usually only manipulated internally by SQLite. It
   78229   ** is incremented by SQLite whenever the database schema is modified (by
   78230   ** creating or dropping a table or index). The schema version is used by
   78231   ** SQLite each time a query is executed to ensure that the internal cache
   78232   ** of the schema used when compiling the SQL query matches the schema of
   78233   ** the database against which the compiled query is actually executed.
   78234   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
   78235   ** the schema-version is potentially dangerous and may lead to program
   78236   ** crashes or database corruption. Use with caution!
   78237   **
   78238   ** The user-version is not used internally by SQLite. It may be used by
   78239   ** applications for any purpose.
   78240   */
   78241   if( sqlite3StrICmp(zLeft, "schema_version")==0
   78242    || sqlite3StrICmp(zLeft, "user_version")==0
   78243    || sqlite3StrICmp(zLeft, "freelist_count")==0
   78244   ){
   78245     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
   78246     sqlite3VdbeUsesBtree(v, iDb);
   78247     switch( zLeft[0] ){
   78248       case 'f': case 'F':
   78249         iCookie = BTREE_FREE_PAGE_COUNT;
   78250         break;
   78251       case 's': case 'S':
   78252         iCookie = BTREE_SCHEMA_VERSION;
   78253         break;
   78254       default:
   78255         iCookie = BTREE_USER_VERSION;
   78256         break;
   78257     }
   78258 
   78259     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
   78260       /* Write the specified cookie value */
   78261       static const VdbeOpList setCookie[] = {
   78262         { OP_Transaction,    0,  1,  0},    /* 0 */
   78263         { OP_Integer,        0,  1,  0},    /* 1 */
   78264         { OP_SetCookie,      0,  0,  1},    /* 2 */
   78265       };
   78266       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
   78267       sqlite3VdbeChangeP1(v, addr, iDb);
   78268       sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
   78269       sqlite3VdbeChangeP1(v, addr+2, iDb);
   78270       sqlite3VdbeChangeP2(v, addr+2, iCookie);
   78271     }else{
   78272       /* Read the specified cookie value */
   78273       static const VdbeOpList readCookie[] = {
   78274         { OP_Transaction,     0,  0,  0},    /* 0 */
   78275         { OP_ReadCookie,      0,  1,  0},    /* 1 */
   78276         { OP_ResultRow,       1,  1,  0}
   78277       };
   78278       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
   78279       sqlite3VdbeChangeP1(v, addr, iDb);
   78280       sqlite3VdbeChangeP1(v, addr+1, iDb);
   78281       sqlite3VdbeChangeP3(v, addr+1, iCookie);
   78282       sqlite3VdbeSetNumCols(v, 1);
   78283       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
   78284     }
   78285   }else
   78286 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
   78287 
   78288 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   78289   /*
   78290   ** Report the current state of file logs for all databases
   78291   */
   78292   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
   78293     static const char *const azLockName[] = {
   78294       "unlocked", "shared", "reserved", "pending", "exclusive"
   78295     };
   78296     int i;
   78297     sqlite3VdbeSetNumCols(v, 2);
   78298     pParse->nMem = 2;
   78299     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
   78300     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
   78301     for(i=0; i<db->nDb; i++){
   78302       Btree *pBt;
   78303       Pager *pPager;
   78304       const char *zState = "unknown";
   78305       int j;
   78306       if( db->aDb[i].zName==0 ) continue;
   78307       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
   78308       pBt = db->aDb[i].pBt;
   78309       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
   78310         zState = "closed";
   78311       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
   78312                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
   78313          zState = azLockName[j];
   78314       }
   78315       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
   78316       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
   78317     }
   78318 
   78319   }else
   78320 #endif
   78321 
   78322 #if SQLITE_HAS_CODEC
   78323   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
   78324     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
   78325   }else
   78326   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
   78327     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
   78328   }else
   78329   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
   78330                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
   78331     int i, h1, h2;
   78332     char zKey[40];
   78333     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
   78334       h1 += 9*(1&(h1>>6));
   78335       h2 += 9*(1&(h2>>6));
   78336       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
   78337     }
   78338     if( (zLeft[3] & 0xf)==0xb ){
   78339       sqlite3_key(db, zKey, i/2);
   78340     }else{
   78341       sqlite3_rekey(db, zKey, i/2);
   78342     }
   78343   }else
   78344 #endif
   78345 #if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
   78346   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
   78347 #if SQLITE_HAS_CODEC
   78348     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
   78349       extern void sqlite3_activate_see(const char*);
   78350       sqlite3_activate_see(&zRight[4]);
   78351     }
   78352 #endif
   78353 #ifdef SQLITE_ENABLE_CEROD
   78354     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
   78355       extern void sqlite3_activate_cerod(const char*);
   78356       sqlite3_activate_cerod(&zRight[6]);
   78357     }
   78358 #endif
   78359   }else
   78360 #endif
   78361 
   78362 
   78363   {/* Empty ELSE clause */}
   78364 
   78365   /*
   78366   ** Reset the safety level, in case the fullfsync flag or synchronous
   78367   ** setting changed.
   78368   */
   78369 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   78370   if( db->autoCommit ){
   78371     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
   78372                (db->flags&SQLITE_FullFSync)!=0);
   78373   }
   78374 #endif
   78375 pragma_out:
   78376   sqlite3DbFree(db, zLeft);
   78377   sqlite3DbFree(db, zRight);
   78378 }
   78379 
   78380 #endif /* SQLITE_OMIT_PRAGMA */
   78381 
   78382 /************** End of pragma.c **********************************************/
   78383 /************** Begin file prepare.c *****************************************/
   78384 /*
   78385 ** 2005 May 25
   78386 **
   78387 ** The author disclaims copyright to this source code.  In place of
   78388 ** a legal notice, here is a blessing:
   78389 **
   78390 **    May you do good and not evil.
   78391 **    May you find forgiveness for yourself and forgive others.
   78392 **    May you share freely, never taking more than you give.
   78393 **
   78394 *************************************************************************
   78395 ** This file contains the implementation of the sqlite3_prepare()
   78396 ** interface, and routines that contribute to loading the database schema
   78397 ** from disk.
   78398 */
   78399 
   78400 /*
   78401 ** Fill the InitData structure with an error message that indicates
   78402 ** that the database is corrupt.
   78403 */
   78404 static void corruptSchema(
   78405   InitData *pData,     /* Initialization context */
   78406   const char *zObj,    /* Object being parsed at the point of error */
   78407   const char *zExtra   /* Error information */
   78408 ){
   78409   sqlite3 *db = pData->db;
   78410   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
   78411     if( zObj==0 ) zObj = "?";
   78412     sqlite3SetString(pData->pzErrMsg, db,
   78413       "malformed database schema (%s)", zObj);
   78414     if( zExtra ){
   78415       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
   78416                                  "%s - %s", *pData->pzErrMsg, zExtra);
   78417     }
   78418   }
   78419   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT;
   78420 }
   78421 
   78422 /*
   78423 ** This is the callback routine for the code that initializes the
   78424 ** database.  See sqlite3Init() below for additional information.
   78425 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
   78426 **
   78427 ** Each callback contains the following information:
   78428 **
   78429 **     argv[0] = name of thing being created
   78430 **     argv[1] = root page number for table or index. 0 for trigger or view.
   78431 **     argv[2] = SQL text for the CREATE statement.
   78432 **
   78433 */
   78434 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
   78435   InitData *pData = (InitData*)pInit;
   78436   sqlite3 *db = pData->db;
   78437   int iDb = pData->iDb;
   78438 
   78439   assert( argc==3 );
   78440   UNUSED_PARAMETER2(NotUsed, argc);
   78441   assert( sqlite3_mutex_held(db->mutex) );
   78442   DbClearProperty(db, iDb, DB_Empty);
   78443   if( db->mallocFailed ){
   78444     corruptSchema(pData, argv[0], 0);
   78445     return 1;
   78446   }
   78447 
   78448   assert( iDb>=0 && iDb<db->nDb );
   78449   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
   78450   if( argv[1]==0 ){
   78451     corruptSchema(pData, argv[0], 0);
   78452   }else if( argv[2] && argv[2][0] ){
   78453     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
   78454     ** But because db->init.busy is set to 1, no VDBE code is generated
   78455     ** or executed.  All the parser does is build the internal data
   78456     ** structures that describe the table, index, or view.
   78457     */
   78458     char *zErr;
   78459     int rc;
   78460     assert( db->init.busy );
   78461     db->init.iDb = iDb;
   78462     db->init.newTnum = atoi(argv[1]);
   78463     db->init.orphanTrigger = 0;
   78464     rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
   78465     db->init.iDb = 0;
   78466     assert( rc!=SQLITE_OK || zErr==0 );
   78467     if( SQLITE_OK!=rc ){
   78468       if( db->init.orphanTrigger ){
   78469         assert( iDb==1 );
   78470       }else{
   78471         pData->rc = rc;
   78472         if( rc==SQLITE_NOMEM ){
   78473           db->mallocFailed = 1;
   78474         }else if( rc!=SQLITE_INTERRUPT && rc!=SQLITE_LOCKED ){
   78475           corruptSchema(pData, argv[0], zErr);
   78476         }
   78477       }
   78478       sqlite3DbFree(db, zErr);
   78479     }
   78480   }else if( argv[0]==0 ){
   78481     corruptSchema(pData, 0, 0);
   78482   }else{
   78483     /* If the SQL column is blank it means this is an index that
   78484     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
   78485     ** constraint for a CREATE TABLE.  The index should have already
   78486     ** been created when we processed the CREATE TABLE.  All we have
   78487     ** to do here is record the root page number for that index.
   78488     */
   78489     Index *pIndex;
   78490     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
   78491     if( pIndex==0 ){
   78492       /* This can occur if there exists an index on a TEMP table which
   78493       ** has the same name as another index on a permanent index.  Since
   78494       ** the permanent table is hidden by the TEMP table, we can also
   78495       ** safely ignore the index on the permanent table.
   78496       */
   78497       /* Do Nothing */;
   78498     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
   78499       corruptSchema(pData, argv[0], "invalid rootpage");
   78500     }
   78501   }
   78502   return 0;
   78503 }
   78504 
   78505 /*
   78506 ** Attempt to read the database schema and initialize internal
   78507 ** data structures for a single database file.  The index of the
   78508 ** database file is given by iDb.  iDb==0 is used for the main
   78509 ** database.  iDb==1 should never be used.  iDb>=2 is used for
   78510 ** auxiliary databases.  Return one of the SQLITE_ error codes to
   78511 ** indicate success or failure.
   78512 */
   78513 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
   78514   int rc;
   78515   int i;
   78516   int size;
   78517   Table *pTab;
   78518   Db *pDb;
   78519   char const *azArg[4];
   78520   int meta[5];
   78521   InitData initData;
   78522   char const *zMasterSchema;
   78523   char const *zMasterName = SCHEMA_TABLE(iDb);
   78524   int openedTransaction = 0;
   78525 
   78526   /*
   78527   ** The master database table has a structure like this
   78528   */
   78529   static const char master_schema[] =
   78530      "CREATE TABLE sqlite_master(\n"
   78531      "  type text,\n"
   78532      "  name text,\n"
   78533      "  tbl_name text,\n"
   78534      "  rootpage integer,\n"
   78535      "  sql text\n"
   78536      ")"
   78537   ;
   78538 #ifndef SQLITE_OMIT_TEMPDB
   78539   static const char temp_master_schema[] =
   78540      "CREATE TEMP TABLE sqlite_temp_master(\n"
   78541      "  type text,\n"
   78542      "  name text,\n"
   78543      "  tbl_name text,\n"
   78544      "  rootpage integer,\n"
   78545      "  sql text\n"
   78546      ")"
   78547   ;
   78548 #else
   78549   #define temp_master_schema 0
   78550 #endif
   78551 
   78552   assert( iDb>=0 && iDb<db->nDb );
   78553   assert( db->aDb[iDb].pSchema );
   78554   assert( sqlite3_mutex_held(db->mutex) );
   78555   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
   78556 
   78557   /* zMasterSchema and zInitScript are set to point at the master schema
   78558   ** and initialisation script appropriate for the database being
   78559   ** initialised. zMasterName is the name of the master table.
   78560   */
   78561   if( !OMIT_TEMPDB && iDb==1 ){
   78562     zMasterSchema = temp_master_schema;
   78563   }else{
   78564     zMasterSchema = master_schema;
   78565   }
   78566   zMasterName = SCHEMA_TABLE(iDb);
   78567 
   78568   /* Construct the schema tables.  */
   78569   azArg[0] = zMasterName;
   78570   azArg[1] = "1";
   78571   azArg[2] = zMasterSchema;
   78572   azArg[3] = 0;
   78573   initData.db = db;
   78574   initData.iDb = iDb;
   78575   initData.rc = SQLITE_OK;
   78576   initData.pzErrMsg = pzErrMsg;
   78577   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
   78578   if( initData.rc ){
   78579     rc = initData.rc;
   78580     goto error_out;
   78581   }
   78582   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
   78583   if( ALWAYS(pTab) ){
   78584     pTab->tabFlags |= TF_Readonly;
   78585   }
   78586 
   78587   /* Create a cursor to hold the database open
   78588   */
   78589   pDb = &db->aDb[iDb];
   78590   if( pDb->pBt==0 ){
   78591     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
   78592       DbSetProperty(db, 1, DB_SchemaLoaded);
   78593     }
   78594     return SQLITE_OK;
   78595   }
   78596 
   78597   /* If there is not already a read-only (or read-write) transaction opened
   78598   ** on the b-tree database, open one now. If a transaction is opened, it
   78599   ** will be closed before this function returns.  */
   78600   sqlite3BtreeEnter(pDb->pBt);
   78601   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
   78602     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
   78603     if( rc!=SQLITE_OK ){
   78604       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
   78605       goto initone_error_out;
   78606     }
   78607     openedTransaction = 1;
   78608   }
   78609 
   78610   /* Get the database meta information.
   78611   **
   78612   ** Meta values are as follows:
   78613   **    meta[0]   Schema cookie.  Changes with each schema change.
   78614   **    meta[1]   File format of schema layer.
   78615   **    meta[2]   Size of the page cache.
   78616   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
   78617   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
   78618   **    meta[5]   User version
   78619   **    meta[6]   Incremental vacuum mode
   78620   **    meta[7]   unused
   78621   **    meta[8]   unused
   78622   **    meta[9]   unused
   78623   **
   78624   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
   78625   ** the possible values of meta[4].
   78626   */
   78627   for(i=0; i<ArraySize(meta); i++){
   78628     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
   78629   }
   78630   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
   78631 
   78632   /* If opening a non-empty database, check the text encoding. For the
   78633   ** main database, set sqlite3.enc to the encoding of the main database.
   78634   ** For an attached db, it is an error if the encoding is not the same
   78635   ** as sqlite3.enc.
   78636   */
   78637   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
   78638     if( iDb==0 ){
   78639       u8 encoding;
   78640       /* If opening the main database, set ENC(db). */
   78641       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
   78642       if( encoding==0 ) encoding = SQLITE_UTF8;
   78643       ENC(db) = encoding;
   78644       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
   78645     }else{
   78646       /* If opening an attached database, the encoding much match ENC(db) */
   78647       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
   78648         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
   78649             " text encoding as main database");
   78650         rc = SQLITE_ERROR;
   78651         goto initone_error_out;
   78652       }
   78653     }
   78654   }else{
   78655     DbSetProperty(db, iDb, DB_Empty);
   78656   }
   78657   pDb->pSchema->enc = ENC(db);
   78658 
   78659   if( pDb->pSchema->cache_size==0 ){
   78660     size = meta[BTREE_DEFAULT_CACHE_SIZE-1];
   78661     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
   78662     if( size<0 ) size = -size;
   78663     pDb->pSchema->cache_size = size;
   78664     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   78665   }
   78666 
   78667   /*
   78668   ** file_format==1    Version 3.0.0.
   78669   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
   78670   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
   78671   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
   78672   */
   78673   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
   78674   if( pDb->pSchema->file_format==0 ){
   78675     pDb->pSchema->file_format = 1;
   78676   }
   78677   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
   78678     sqlite3SetString(pzErrMsg, db, "unsupported file format");
   78679     rc = SQLITE_CORRUPT_BKPT; // Android Change from "rc = SQLITE_ERROR;"
   78680     goto initone_error_out;
   78681   }
   78682 
   78683   /* Ticket #2804:  When we open a database in the newer file format,
   78684   ** clear the legacy_file_format pragma flag so that a VACUUM will
   78685   ** not downgrade the database and thus invalidate any descending
   78686   ** indices that the user might have created.
   78687   */
   78688   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
   78689     db->flags &= ~SQLITE_LegacyFileFmt;
   78690   }
   78691 
   78692   /* Read the schema information out of the schema tables
   78693   */
   78694   assert( db->init.busy );
   78695   {
   78696     char *zSql;
   78697     zSql = sqlite3MPrintf(db,
   78698         "SELECT name, rootpage, sql FROM '%q'.%s",
   78699         db->aDb[iDb].zName, zMasterName);
   78700 #ifndef SQLITE_OMIT_AUTHORIZATION
   78701     {
   78702       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   78703       xAuth = db->xAuth;
   78704       db->xAuth = 0;
   78705 #endif
   78706       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
   78707 #ifndef SQLITE_OMIT_AUTHORIZATION
   78708       db->xAuth = xAuth;
   78709     }
   78710 #endif
   78711     if( rc==SQLITE_OK ) rc = initData.rc;
   78712     sqlite3DbFree(db, zSql);
   78713 #ifndef SQLITE_OMIT_ANALYZE
   78714     if( rc==SQLITE_OK ){
   78715       sqlite3AnalysisLoad(db, iDb);
   78716     }
   78717 #endif
   78718   }
   78719   if( db->mallocFailed ){
   78720     rc = SQLITE_NOMEM;
   78721     sqlite3ResetInternalSchema(db, 0);
   78722   }
   78723   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
   78724     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
   78725     ** the schema loaded, even if errors occurred. In this situation the
   78726     ** current sqlite3_prepare() operation will fail, but the following one
   78727     ** will attempt to compile the supplied statement against whatever subset
   78728     ** of the schema was loaded before the error occurred. The primary
   78729     ** purpose of this is to allow access to the sqlite_master table
   78730     ** even when its contents have been corrupted.
   78731     */
   78732     DbSetProperty(db, iDb, DB_SchemaLoaded);
   78733     rc = SQLITE_OK;
   78734   }
   78735 
   78736   /* Jump here for an error that occurs after successfully allocating
   78737   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
   78738   ** before that point, jump to error_out.
   78739   */
   78740 initone_error_out:
   78741   if( openedTransaction ){
   78742     sqlite3BtreeCommit(pDb->pBt);
   78743   }
   78744   sqlite3BtreeLeave(pDb->pBt);
   78745 
   78746 error_out:
   78747   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   78748     db->mallocFailed = 1;
   78749   }
   78750   return rc;
   78751 }
   78752 
   78753 /*
   78754 ** Initialize all database files - the main database file, the file
   78755 ** used to store temporary tables, and any additional database files
   78756 ** created using ATTACH statements.  Return a success code.  If an
   78757 ** error occurs, write an error message into *pzErrMsg.
   78758 **
   78759 ** After a database is initialized, the DB_SchemaLoaded bit is set
   78760 ** bit is set in the flags field of the Db structure. If the database
   78761 ** file was of zero-length, then the DB_Empty flag is also set.
   78762 */
   78763 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
   78764   int i, rc;
   78765   int commit_internal = !(db->flags&SQLITE_InternChanges);
   78766 
   78767   assert( sqlite3_mutex_held(db->mutex) );
   78768   rc = SQLITE_OK;
   78769   db->init.busy = 1;
   78770   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   78771     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
   78772     rc = sqlite3InitOne(db, i, pzErrMsg);
   78773     if( rc ){
   78774       sqlite3ResetInternalSchema(db, i);
   78775     }
   78776   }
   78777 
   78778   /* Once all the other databases have been initialised, load the schema
   78779   ** for the TEMP database. This is loaded last, as the TEMP database
   78780   ** schema may contain references to objects in other databases.
   78781   */
   78782 #ifndef SQLITE_OMIT_TEMPDB
   78783   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
   78784                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
   78785     rc = sqlite3InitOne(db, 1, pzErrMsg);
   78786     if( rc ){
   78787       sqlite3ResetInternalSchema(db, 1);
   78788     }
   78789   }
   78790 #endif
   78791 
   78792   db->init.busy = 0;
   78793   if( rc==SQLITE_OK && commit_internal ){
   78794     sqlite3CommitInternalChanges(db);
   78795   }
   78796 
   78797   return rc;
   78798 }
   78799 
   78800 /*
   78801 ** This routine is a no-op if the database schema is already initialised.
   78802 ** Otherwise, the schema is loaded. An error code is returned.
   78803 */
   78804 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
   78805   int rc = SQLITE_OK;
   78806   sqlite3 *db = pParse->db;
   78807   assert( sqlite3_mutex_held(db->mutex) );
   78808   if( !db->init.busy ){
   78809     rc = sqlite3Init(db, &pParse->zErrMsg);
   78810   }
   78811   if( rc!=SQLITE_OK ){
   78812     pParse->rc = rc;
   78813     pParse->nErr++;
   78814   }
   78815   return rc;
   78816 }
   78817 
   78818 
   78819 /*
   78820 ** Check schema cookies in all databases.  If any cookie is out
   78821 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
   78822 ** make no changes to pParse->rc.
   78823 */
   78824 static void schemaIsValid(Parse *pParse){
   78825   sqlite3 *db = pParse->db;
   78826   int iDb;
   78827   int rc;
   78828   int cookie;
   78829 
   78830   assert( pParse->checkSchema );
   78831   assert( sqlite3_mutex_held(db->mutex) );
   78832   for(iDb=0; iDb<db->nDb; iDb++){
   78833     int openedTransaction = 0;         /* True if a transaction is opened */
   78834     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
   78835     if( pBt==0 ) continue;
   78836 
   78837     /* If there is not already a read-only (or read-write) transaction opened
   78838     ** on the b-tree database, open one now. If a transaction is opened, it
   78839     ** will be closed immediately after reading the meta-value. */
   78840     if( !sqlite3BtreeIsInReadTrans(pBt) ){
   78841       rc = sqlite3BtreeBeginTrans(pBt, 0);
   78842       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   78843         db->mallocFailed = 1;
   78844       }
   78845       if( rc!=SQLITE_OK ) return;
   78846       openedTransaction = 1;
   78847     }
   78848 
   78849     /* Read the schema cookie from the database. If it does not match the
   78850     ** value stored as part of the in-memory schema representation,
   78851     ** set Parse.rc to SQLITE_SCHEMA. */
   78852     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
   78853     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
   78854       pParse->rc = SQLITE_SCHEMA;
   78855     }
   78856 
   78857     /* Close the transaction, if one was opened. */
   78858     if( openedTransaction ){
   78859       sqlite3BtreeCommit(pBt);
   78860     }
   78861   }
   78862 }
   78863 
   78864 /*
   78865 ** Convert a schema pointer into the iDb index that indicates
   78866 ** which database file in db->aDb[] the schema refers to.
   78867 **
   78868 ** If the same database is attached more than once, the first
   78869 ** attached database is returned.
   78870 */
   78871 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
   78872   int i = -1000000;
   78873 
   78874   /* If pSchema is NULL, then return -1000000. This happens when code in
   78875   ** expr.c is trying to resolve a reference to a transient table (i.e. one
   78876   ** created by a sub-select). In this case the return value of this
   78877   ** function should never be used.
   78878   **
   78879   ** We return -1000000 instead of the more usual -1 simply because using
   78880   ** -1000000 as the incorrect index into db->aDb[] is much
   78881   ** more likely to cause a segfault than -1 (of course there are assert()
   78882   ** statements too, but it never hurts to play the odds).
   78883   */
   78884   assert( sqlite3_mutex_held(db->mutex) );
   78885   if( pSchema ){
   78886     for(i=0; ALWAYS(i<db->nDb); i++){
   78887       if( db->aDb[i].pSchema==pSchema ){
   78888         break;
   78889       }
   78890     }
   78891     assert( i>=0 && i<db->nDb );
   78892   }
   78893   return i;
   78894 }
   78895 
   78896 /*
   78897 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
   78898 */
   78899 static int sqlite3Prepare(
   78900   sqlite3 *db,              /* Database handle. */
   78901   const char *zSql,         /* UTF-8 encoded SQL statement. */
   78902   int nBytes,               /* Length of zSql in bytes. */
   78903   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
   78904   Vdbe *pReprepare,         /* VM being reprepared */
   78905   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   78906   const char **pzTail       /* OUT: End of parsed string */
   78907 ){
   78908   Parse *pParse;            /* Parsing context */
   78909   char *zErrMsg = 0;        /* Error message */
   78910   int rc = SQLITE_OK;       /* Result code */
   78911   int i;                    /* Loop counter */
   78912 
   78913   /* Allocate the parsing context */
   78914   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
   78915   if( pParse==0 ){
   78916     rc = SQLITE_NOMEM;
   78917     goto end_prepare;
   78918   }
   78919   pParse->pReprepare = pReprepare;
   78920   assert( ppStmt && *ppStmt==0 );
   78921   assert( !db->mallocFailed );
   78922   assert( sqlite3_mutex_held(db->mutex) );
   78923 
   78924   /* Check to verify that it is possible to get a read lock on all
   78925   ** database schemas.  The inability to get a read lock indicates that
   78926   ** some other database connection is holding a write-lock, which in
   78927   ** turn means that the other connection has made uncommitted changes
   78928   ** to the schema.
   78929   **
   78930   ** Were we to proceed and prepare the statement against the uncommitted
   78931   ** schema changes and if those schema changes are subsequently rolled
   78932   ** back and different changes are made in their place, then when this
   78933   ** prepared statement goes to run the schema cookie would fail to detect
   78934   ** the schema change.  Disaster would follow.
   78935   **
   78936   ** This thread is currently holding mutexes on all Btrees (because
   78937   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
   78938   ** is not possible for another thread to start a new schema change
   78939   ** while this routine is running.  Hence, we do not need to hold
   78940   ** locks on the schema, we just need to make sure nobody else is
   78941   ** holding them.
   78942   **
   78943   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
   78944   ** but it does *not* override schema lock detection, so this all still
   78945   ** works even if READ_UNCOMMITTED is set.
   78946   */
   78947   for(i=0; i<db->nDb; i++) {
   78948     Btree *pBt = db->aDb[i].pBt;
   78949     if( pBt ){
   78950       assert( sqlite3BtreeHoldsMutex(pBt) );
   78951       rc = sqlite3BtreeSchemaLocked(pBt);
   78952       if( rc ){
   78953         const char *zDb = db->aDb[i].zName;
   78954         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
   78955         testcase( db->flags & SQLITE_ReadUncommitted );
   78956         goto end_prepare;
   78957       }
   78958     }
   78959   }
   78960 
   78961   sqlite3VtabUnlockList(db);
   78962 
   78963   pParse->db = db;
   78964   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
   78965     char *zSqlCopy;
   78966     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
   78967     testcase( nBytes==mxLen );
   78968     testcase( nBytes==mxLen+1 );
   78969     if( nBytes>mxLen ){
   78970       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
   78971       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
   78972       goto end_prepare;
   78973     }
   78974     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
   78975     if( zSqlCopy ){
   78976       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
   78977       sqlite3DbFree(db, zSqlCopy);
   78978       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
   78979     }else{
   78980       pParse->zTail = &zSql[nBytes];
   78981     }
   78982   }else{
   78983     sqlite3RunParser(pParse, zSql, &zErrMsg);
   78984   }
   78985 
   78986   if( db->mallocFailed ){
   78987     pParse->rc = SQLITE_NOMEM;
   78988   }
   78989   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
   78990   if( pParse->checkSchema ){
   78991     schemaIsValid(pParse);
   78992   }
   78993   if( pParse->rc==SQLITE_SCHEMA ){
   78994     sqlite3ResetInternalSchema(db, 0);
   78995   }
   78996   if( db->mallocFailed ){
   78997     pParse->rc = SQLITE_NOMEM;
   78998   }
   78999   if( pzTail ){
   79000     *pzTail = pParse->zTail;
   79001   }
   79002   rc = pParse->rc;
   79003 
   79004 #ifndef SQLITE_OMIT_EXPLAIN
   79005   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
   79006     static const char * const azColName[] = {
   79007        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
   79008        "order", "from", "detail"
   79009     };
   79010     int iFirst, mx;
   79011     if( pParse->explain==2 ){
   79012       sqlite3VdbeSetNumCols(pParse->pVdbe, 3);
   79013       iFirst = 8;
   79014       mx = 11;
   79015     }else{
   79016       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
   79017       iFirst = 0;
   79018       mx = 8;
   79019     }
   79020     for(i=iFirst; i<mx; i++){
   79021       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
   79022                             azColName[i], SQLITE_STATIC);
   79023     }
   79024   }
   79025 #endif
   79026 
   79027   assert( db->init.busy==0 || saveSqlFlag==0 );
   79028   if( db->init.busy==0 ){
   79029     Vdbe *pVdbe = pParse->pVdbe;
   79030     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
   79031   }
   79032   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
   79033     sqlite3VdbeFinalize(pParse->pVdbe);
   79034     assert(!(*ppStmt));
   79035   }else{
   79036     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
   79037   }
   79038 
   79039   if( zErrMsg ){
   79040     sqlite3Error(db, rc, "%s", zErrMsg);
   79041     sqlite3DbFree(db, zErrMsg);
   79042   }else{
   79043     sqlite3Error(db, rc, 0);
   79044   }
   79045 
   79046   /* Delete any TriggerPrg structures allocated while parsing this statement. */
   79047   while( pParse->pTriggerPrg ){
   79048     TriggerPrg *pT = pParse->pTriggerPrg;
   79049     pParse->pTriggerPrg = pT->pNext;
   79050     sqlite3VdbeProgramDelete(db, pT->pProgram, 0);
   79051     sqlite3DbFree(db, pT);
   79052   }
   79053 
   79054 end_prepare:
   79055 
   79056   sqlite3StackFree(db, pParse);
   79057   rc = sqlite3ApiExit(db, rc);
   79058   assert( (rc&db->errMask)==rc );
   79059   return rc;
   79060 }
   79061 static int sqlite3LockAndPrepare(
   79062   sqlite3 *db,              /* Database handle. */
   79063   const char *zSql,         /* UTF-8 encoded SQL statement. */
   79064   int nBytes,               /* Length of zSql in bytes. */
   79065   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
   79066   Vdbe *pOld,               /* VM being reprepared */
   79067   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   79068   const char **pzTail       /* OUT: End of parsed string */
   79069 ){
   79070   int rc;
   79071   assert( ppStmt!=0 );
   79072   *ppStmt = 0;
   79073   if( !sqlite3SafetyCheckOk(db) ){
   79074     return SQLITE_MISUSE_BKPT;
   79075   }
   79076   sqlite3_mutex_enter(db->mutex);
   79077   sqlite3BtreeEnterAll(db);
   79078   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
   79079   if( rc==SQLITE_SCHEMA ){
   79080     sqlite3_finalize(*ppStmt);
   79081     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
   79082   }
   79083   sqlite3BtreeLeaveAll(db);
   79084   sqlite3_mutex_leave(db->mutex);
   79085   return rc;
   79086 }
   79087 
   79088 /*
   79089 ** Rerun the compilation of a statement after a schema change.
   79090 **
   79091 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
   79092 ** if the statement cannot be recompiled because another connection has
   79093 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
   79094 ** occurs, return SQLITE_SCHEMA.
   79095 */
   79096 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
   79097   int rc;
   79098   sqlite3_stmt *pNew;
   79099   const char *zSql;
   79100   sqlite3 *db;
   79101 
   79102   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
   79103   zSql = sqlite3_sql((sqlite3_stmt *)p);
   79104   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
   79105   db = sqlite3VdbeDb(p);
   79106   assert( sqlite3_mutex_held(db->mutex) );
   79107   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
   79108   if( rc ){
   79109     if( rc==SQLITE_NOMEM ){
   79110       db->mallocFailed = 1;
   79111     }
   79112     assert( pNew==0 );
   79113     return rc;
   79114   }else{
   79115     assert( pNew!=0 );
   79116   }
   79117   sqlite3VdbeSwap((Vdbe*)pNew, p);
   79118   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
   79119   sqlite3VdbeResetStepResult((Vdbe*)pNew);
   79120   sqlite3VdbeFinalize((Vdbe*)pNew);
   79121   return SQLITE_OK;
   79122 }
   79123 
   79124 
   79125 /*
   79126 ** Two versions of the official API.  Legacy and new use.  In the legacy
   79127 ** version, the original SQL text is not saved in the prepared statement
   79128 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
   79129 ** sqlite3_step().  In the new version, the original SQL text is retained
   79130 ** and the statement is automatically recompiled if an schema change
   79131 ** occurs.
   79132 */
   79133 SQLITE_API int sqlite3_prepare(
   79134   sqlite3 *db,              /* Database handle. */
   79135   const char *zSql,         /* UTF-8 encoded SQL statement. */
   79136   int nBytes,               /* Length of zSql in bytes. */
   79137   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   79138   const char **pzTail       /* OUT: End of parsed string */
   79139 ){
   79140   int rc;
   79141   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
   79142   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   79143   return rc;
   79144 }
   79145 SQLITE_API int sqlite3_prepare_v2(
   79146   sqlite3 *db,              /* Database handle. */
   79147   const char *zSql,         /* UTF-8 encoded SQL statement. */
   79148   int nBytes,               /* Length of zSql in bytes. */
   79149   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   79150   const char **pzTail       /* OUT: End of parsed string */
   79151 ){
   79152   int rc;
   79153   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
   79154   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   79155   return rc;
   79156 }
   79157 
   79158 
   79159 #ifndef SQLITE_OMIT_UTF16
   79160 /*
   79161 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
   79162 */
   79163 static int sqlite3Prepare16(
   79164   sqlite3 *db,              /* Database handle. */
   79165   const void *zSql,         /* UTF-8 encoded SQL statement. */
   79166   int nBytes,               /* Length of zSql in bytes. */
   79167   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
   79168   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   79169   const void **pzTail       /* OUT: End of parsed string */
   79170 ){
   79171   /* This function currently works by first transforming the UTF-16
   79172   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
   79173   ** tricky bit is figuring out the pointer to return in *pzTail.
   79174   */
   79175   char *zSql8;
   79176   const char *zTail8 = 0;
   79177   int rc = SQLITE_OK;
   79178 
   79179   assert( ppStmt );
   79180   *ppStmt = 0;
   79181   if( !sqlite3SafetyCheckOk(db) ){
   79182     return SQLITE_MISUSE_BKPT;
   79183   }
   79184   sqlite3_mutex_enter(db->mutex);
   79185   zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
   79186   if( zSql8 ){
   79187     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
   79188   }
   79189 
   79190   if( zTail8 && pzTail ){
   79191     /* If sqlite3_prepare returns a tail pointer, we calculate the
   79192     ** equivalent pointer into the UTF-16 string by counting the unicode
   79193     ** characters between zSql8 and zTail8, and then returning a pointer
   79194     ** the same number of characters into the UTF-16 string.
   79195     */
   79196     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
   79197     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
   79198   }
   79199   sqlite3DbFree(db, zSql8);
   79200   rc = sqlite3ApiExit(db, rc);
   79201   sqlite3_mutex_leave(db->mutex);
   79202   return rc;
   79203 }
   79204 
   79205 /*
   79206 ** Two versions of the official API.  Legacy and new use.  In the legacy
   79207 ** version, the original SQL text is not saved in the prepared statement
   79208 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
   79209 ** sqlite3_step().  In the new version, the original SQL text is retained
   79210 ** and the statement is automatically recompiled if an schema change
   79211 ** occurs.
   79212 */
   79213 SQLITE_API int sqlite3_prepare16(
   79214   sqlite3 *db,              /* Database handle. */
   79215   const void *zSql,         /* UTF-8 encoded SQL statement. */
   79216   int nBytes,               /* Length of zSql in bytes. */
   79217   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   79218   const void **pzTail       /* OUT: End of parsed string */
   79219 ){
   79220   int rc;
   79221   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
   79222   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   79223   return rc;
   79224 }
   79225 SQLITE_API int sqlite3_prepare16_v2(
   79226   sqlite3 *db,              /* Database handle. */
   79227   const void *zSql,         /* UTF-8 encoded SQL statement. */
   79228   int nBytes,               /* Length of zSql in bytes. */
   79229   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   79230   const void **pzTail       /* OUT: End of parsed string */
   79231 ){
   79232   int rc;
   79233   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
   79234   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   79235   return rc;
   79236 }
   79237 
   79238 #endif /* SQLITE_OMIT_UTF16 */
   79239 
   79240 /************** End of prepare.c *********************************************/
   79241 /************** Begin file select.c ******************************************/
   79242 /*
   79243 ** 2001 September 15
   79244 **
   79245 ** The author disclaims copyright to this source code.  In place of
   79246 ** a legal notice, here is a blessing:
   79247 **
   79248 **    May you do good and not evil.
   79249 **    May you find forgiveness for yourself and forgive others.
   79250 **    May you share freely, never taking more than you give.
   79251 **
   79252 *************************************************************************
   79253 ** This file contains C code routines that are called by the parser
   79254 ** to handle SELECT statements in SQLite.
   79255 */
   79256 
   79257 
   79258 /*
   79259 ** Delete all the content of a Select structure but do not deallocate
   79260 ** the select structure itself.
   79261 */
   79262 static void clearSelect(sqlite3 *db, Select *p){
   79263   sqlite3ExprListDelete(db, p->pEList);
   79264   sqlite3SrcListDelete(db, p->pSrc);
   79265   sqlite3ExprDelete(db, p->pWhere);
   79266   sqlite3ExprListDelete(db, p->pGroupBy);
   79267   sqlite3ExprDelete(db, p->pHaving);
   79268   sqlite3ExprListDelete(db, p->pOrderBy);
   79269   sqlite3SelectDelete(db, p->pPrior);
   79270   sqlite3ExprDelete(db, p->pLimit);
   79271   sqlite3ExprDelete(db, p->pOffset);
   79272 }
   79273 
   79274 /*
   79275 ** Initialize a SelectDest structure.
   79276 */
   79277 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
   79278   pDest->eDest = (u8)eDest;
   79279   pDest->iParm = iParm;
   79280   pDest->affinity = 0;
   79281   pDest->iMem = 0;
   79282   pDest->nMem = 0;
   79283 }
   79284 
   79285 
   79286 /*
   79287 ** Allocate a new Select structure and return a pointer to that
   79288 ** structure.
   79289 */
   79290 SQLITE_PRIVATE Select *sqlite3SelectNew(
   79291   Parse *pParse,        /* Parsing context */
   79292   ExprList *pEList,     /* which columns to include in the result */
   79293   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
   79294   Expr *pWhere,         /* the WHERE clause */
   79295   ExprList *pGroupBy,   /* the GROUP BY clause */
   79296   Expr *pHaving,        /* the HAVING clause */
   79297   ExprList *pOrderBy,   /* the ORDER BY clause */
   79298   int isDistinct,       /* true if the DISTINCT keyword is present */
   79299   Expr *pLimit,         /* LIMIT value.  NULL means not used */
   79300   Expr *pOffset         /* OFFSET value.  NULL means no offset */
   79301 ){
   79302   Select *pNew;
   79303   Select standin;
   79304   sqlite3 *db = pParse->db;
   79305   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
   79306   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
   79307   if( pNew==0 ){
   79308     pNew = &standin;
   79309     memset(pNew, 0, sizeof(*pNew));
   79310   }
   79311   if( pEList==0 ){
   79312     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
   79313   }
   79314   pNew->pEList = pEList;
   79315   pNew->pSrc = pSrc;
   79316   pNew->pWhere = pWhere;
   79317   pNew->pGroupBy = pGroupBy;
   79318   pNew->pHaving = pHaving;
   79319   pNew->pOrderBy = pOrderBy;
   79320   pNew->selFlags = isDistinct ? SF_Distinct : 0;
   79321   pNew->op = TK_SELECT;
   79322   pNew->pLimit = pLimit;
   79323   pNew->pOffset = pOffset;
   79324   assert( pOffset==0 || pLimit!=0 );
   79325   pNew->addrOpenEphm[0] = -1;
   79326   pNew->addrOpenEphm[1] = -1;
   79327   pNew->addrOpenEphm[2] = -1;
   79328   if( db->mallocFailed ) {
   79329     clearSelect(db, pNew);
   79330     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
   79331     pNew = 0;
   79332   }
   79333   return pNew;
   79334 }
   79335 
   79336 /*
   79337 ** Delete the given Select structure and all of its substructures.
   79338 */
   79339 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
   79340   if( p ){
   79341     clearSelect(db, p);
   79342     sqlite3DbFree(db, p);
   79343   }
   79344 }
   79345 
   79346 /*
   79347 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
   79348 ** type of join.  Return an integer constant that expresses that type
   79349 ** in terms of the following bit values:
   79350 **
   79351 **     JT_INNER
   79352 **     JT_CROSS
   79353 **     JT_OUTER
   79354 **     JT_NATURAL
   79355 **     JT_LEFT
   79356 **     JT_RIGHT
   79357 **
   79358 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
   79359 **
   79360 ** If an illegal or unsupported join type is seen, then still return
   79361 ** a join type, but put an error in the pParse structure.
   79362 */
   79363 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
   79364   int jointype = 0;
   79365   Token *apAll[3];
   79366   Token *p;
   79367                              /*   0123456789 123456789 123456789 123 */
   79368   static const char zKeyText[] = "naturaleftouterightfullinnercross";
   79369   static const struct {
   79370     u8 i;        /* Beginning of keyword text in zKeyText[] */
   79371     u8 nChar;    /* Length of the keyword in characters */
   79372     u8 code;     /* Join type mask */
   79373   } aKeyword[] = {
   79374     /* natural */ { 0,  7, JT_NATURAL                },
   79375     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
   79376     /* outer   */ { 10, 5, JT_OUTER                  },
   79377     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
   79378     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
   79379     /* inner   */ { 23, 5, JT_INNER                  },
   79380     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
   79381   };
   79382   int i, j;
   79383   apAll[0] = pA;
   79384   apAll[1] = pB;
   79385   apAll[2] = pC;
   79386   for(i=0; i<3 && apAll[i]; i++){
   79387     p = apAll[i];
   79388     for(j=0; j<ArraySize(aKeyword); j++){
   79389       if( p->n==aKeyword[j].nChar
   79390           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
   79391         jointype |= aKeyword[j].code;
   79392         break;
   79393       }
   79394     }
   79395     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
   79396     if( j>=ArraySize(aKeyword) ){
   79397       jointype |= JT_ERROR;
   79398       break;
   79399     }
   79400   }
   79401   if(
   79402      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
   79403      (jointype & JT_ERROR)!=0
   79404   ){
   79405     const char *zSp = " ";
   79406     assert( pB!=0 );
   79407     if( pC==0 ){ zSp++; }
   79408     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
   79409        "%T %T%s%T", pA, pB, zSp, pC);
   79410     jointype = JT_INNER;
   79411   }else if( (jointype & JT_OUTER)!=0
   79412          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
   79413     sqlite3ErrorMsg(pParse,
   79414       "RIGHT and FULL OUTER JOINs are not currently supported");
   79415     jointype = JT_INNER;
   79416   }
   79417   return jointype;
   79418 }
   79419 
   79420 /*
   79421 ** Return the index of a column in a table.  Return -1 if the column
   79422 ** is not contained in the table.
   79423 */
   79424 static int columnIndex(Table *pTab, const char *zCol){
   79425   int i;
   79426   for(i=0; i<pTab->nCol; i++){
   79427     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
   79428   }
   79429   return -1;
   79430 }
   79431 
   79432 /*
   79433 ** Search the first N tables in pSrc, from left to right, looking for a
   79434 ** table that has a column named zCol.
   79435 **
   79436 ** When found, set *piTab and *piCol to the table index and column index
   79437 ** of the matching column and return TRUE.
   79438 **
   79439 ** If not found, return FALSE.
   79440 */
   79441 static int tableAndColumnIndex(
   79442   SrcList *pSrc,       /* Array of tables to search */
   79443   int N,               /* Number of tables in pSrc->a[] to search */
   79444   const char *zCol,    /* Name of the column we are looking for */
   79445   int *piTab,          /* Write index of pSrc->a[] here */
   79446   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
   79447 ){
   79448   int i;               /* For looping over tables in pSrc */
   79449   int iCol;            /* Index of column matching zCol */
   79450 
   79451   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
   79452   for(i=0; i<N; i++){
   79453     iCol = columnIndex(pSrc->a[i].pTab, zCol);
   79454     if( iCol>=0 ){
   79455       if( piTab ){
   79456         *piTab = i;
   79457         *piCol = iCol;
   79458       }
   79459       return 1;
   79460     }
   79461   }
   79462   return 0;
   79463 }
   79464 
   79465 /*
   79466 ** This function is used to add terms implied by JOIN syntax to the
   79467 ** WHERE clause expression of a SELECT statement. The new term, which
   79468 ** is ANDed with the existing WHERE clause, is of the form:
   79469 **
   79470 **    (tab1.col1 = tab2.col2)
   79471 **
   79472 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
   79473 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
   79474 ** column iColRight of tab2.
   79475 */
   79476 static void addWhereTerm(
   79477   Parse *pParse,                  /* Parsing context */
   79478   SrcList *pSrc,                  /* List of tables in FROM clause */
   79479   int iLeft,                      /* Index of first table to join in pSrc */
   79480   int iColLeft,                   /* Index of column in first table */
   79481   int iRight,                     /* Index of second table in pSrc */
   79482   int iColRight,                  /* Index of column in second table */
   79483   int isOuterJoin,                /* True if this is an OUTER join */
   79484   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
   79485 ){
   79486   sqlite3 *db = pParse->db;
   79487   Expr *pE1;
   79488   Expr *pE2;
   79489   Expr *pEq;
   79490 
   79491   assert( iLeft<iRight );
   79492   assert( pSrc->nSrc>iRight );
   79493   assert( pSrc->a[iLeft].pTab );
   79494   assert( pSrc->a[iRight].pTab );
   79495 
   79496   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
   79497   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
   79498 
   79499   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
   79500   if( pEq && isOuterJoin ){
   79501     ExprSetProperty(pEq, EP_FromJoin);
   79502     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
   79503     ExprSetIrreducible(pEq);
   79504     pEq->iRightJoinTable = (i16)pE2->iTable;
   79505   }
   79506   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
   79507 }
   79508 
   79509 /*
   79510 ** Set the EP_FromJoin property on all terms of the given expression.
   79511 ** And set the Expr.iRightJoinTable to iTable for every term in the
   79512 ** expression.
   79513 **
   79514 ** The EP_FromJoin property is used on terms of an expression to tell
   79515 ** the LEFT OUTER JOIN processing logic that this term is part of the
   79516 ** join restriction specified in the ON or USING clause and not a part
   79517 ** of the more general WHERE clause.  These terms are moved over to the
   79518 ** WHERE clause during join processing but we need to remember that they
   79519 ** originated in the ON or USING clause.
   79520 **
   79521 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
   79522 ** expression depends on table iRightJoinTable even if that table is not
   79523 ** explicitly mentioned in the expression.  That information is needed
   79524 ** for cases like this:
   79525 **
   79526 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
   79527 **
   79528 ** The where clause needs to defer the handling of the t1.x=5
   79529 ** term until after the t2 loop of the join.  In that way, a
   79530 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
   79531 ** defer the handling of t1.x=5, it will be processed immediately
   79532 ** after the t1 loop and rows with t1.x!=5 will never appear in
   79533 ** the output, which is incorrect.
   79534 */
   79535 static void setJoinExpr(Expr *p, int iTable){
   79536   while( p ){
   79537     ExprSetProperty(p, EP_FromJoin);
   79538     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
   79539     ExprSetIrreducible(p);
   79540     p->iRightJoinTable = (i16)iTable;
   79541     setJoinExpr(p->pLeft, iTable);
   79542     p = p->pRight;
   79543   }
   79544 }
   79545 
   79546 /*
   79547 ** This routine processes the join information for a SELECT statement.
   79548 ** ON and USING clauses are converted into extra terms of the WHERE clause.
   79549 ** NATURAL joins also create extra WHERE clause terms.
   79550 **
   79551 ** The terms of a FROM clause are contained in the Select.pSrc structure.
   79552 ** The left most table is the first entry in Select.pSrc.  The right-most
   79553 ** table is the last entry.  The join operator is held in the entry to
   79554 ** the left.  Thus entry 0 contains the join operator for the join between
   79555 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
   79556 ** also attached to the left entry.
   79557 **
   79558 ** This routine returns the number of errors encountered.
   79559 */
   79560 static int sqliteProcessJoin(Parse *pParse, Select *p){
   79561   SrcList *pSrc;                  /* All tables in the FROM clause */
   79562   int i, j;                       /* Loop counters */
   79563   struct SrcList_item *pLeft;     /* Left table being joined */
   79564   struct SrcList_item *pRight;    /* Right table being joined */
   79565 
   79566   pSrc = p->pSrc;
   79567   pLeft = &pSrc->a[0];
   79568   pRight = &pLeft[1];
   79569   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
   79570     Table *pLeftTab = pLeft->pTab;
   79571     Table *pRightTab = pRight->pTab;
   79572     int isOuter;
   79573 
   79574     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
   79575     isOuter = (pRight->jointype & JT_OUTER)!=0;
   79576 
   79577     /* When the NATURAL keyword is present, add WHERE clause terms for
   79578     ** every column that the two tables have in common.
   79579     */
   79580     if( pRight->jointype & JT_NATURAL ){
   79581       if( pRight->pOn || pRight->pUsing ){
   79582         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
   79583            "an ON or USING clause", 0);
   79584         return 1;
   79585       }
   79586       for(j=0; j<pRightTab->nCol; j++){
   79587         char *zName;   /* Name of column in the right table */
   79588         int iLeft;     /* Matching left table */
   79589         int iLeftCol;  /* Matching column in the left table */
   79590 
   79591         zName = pRightTab->aCol[j].zName;
   79592         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
   79593           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
   79594                        isOuter, &p->pWhere);
   79595         }
   79596       }
   79597     }
   79598 
   79599     /* Disallow both ON and USING clauses in the same join
   79600     */
   79601     if( pRight->pOn && pRight->pUsing ){
   79602       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
   79603         "clauses in the same join");
   79604       return 1;
   79605     }
   79606 
   79607     /* Add the ON clause to the end of the WHERE clause, connected by
   79608     ** an AND operator.
   79609     */
   79610     if( pRight->pOn ){
   79611       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
   79612       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
   79613       pRight->pOn = 0;
   79614     }
   79615 
   79616     /* Create extra terms on the WHERE clause for each column named
   79617     ** in the USING clause.  Example: If the two tables to be joined are
   79618     ** A and B and the USING clause names X, Y, and Z, then add this
   79619     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
   79620     ** Report an error if any column mentioned in the USING clause is
   79621     ** not contained in both tables to be joined.
   79622     */
   79623     if( pRight->pUsing ){
   79624       IdList *pList = pRight->pUsing;
   79625       for(j=0; j<pList->nId; j++){
   79626         char *zName;     /* Name of the term in the USING clause */
   79627         int iLeft;       /* Table on the left with matching column name */
   79628         int iLeftCol;    /* Column number of matching column on the left */
   79629         int iRightCol;   /* Column number of matching column on the right */
   79630 
   79631         zName = pList->a[j].zName;
   79632         iRightCol = columnIndex(pRightTab, zName);
   79633         if( iRightCol<0
   79634          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
   79635         ){
   79636           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
   79637             "not present in both tables", zName);
   79638           return 1;
   79639         }
   79640         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
   79641                      isOuter, &p->pWhere);
   79642       }
   79643     }
   79644   }
   79645   return 0;
   79646 }
   79647 
   79648 /*
   79649 ** Insert code into "v" that will push the record on the top of the
   79650 ** stack into the sorter.
   79651 */
   79652 static void pushOntoSorter(
   79653   Parse *pParse,         /* Parser context */
   79654   ExprList *pOrderBy,    /* The ORDER BY clause */
   79655   Select *pSelect,       /* The whole SELECT statement */
   79656   int regData            /* Register holding data to be sorted */
   79657 ){
   79658   Vdbe *v = pParse->pVdbe;
   79659   int nExpr = pOrderBy->nExpr;
   79660   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
   79661   int regRecord = sqlite3GetTempReg(pParse);
   79662   sqlite3ExprCacheClear(pParse);
   79663   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
   79664   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
   79665   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
   79666   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
   79667   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
   79668   sqlite3ReleaseTempReg(pParse, regRecord);
   79669   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
   79670   if( pSelect->iLimit ){
   79671     int addr1, addr2;
   79672     int iLimit;
   79673     if( pSelect->iOffset ){
   79674       iLimit = pSelect->iOffset+1;
   79675     }else{
   79676       iLimit = pSelect->iLimit;
   79677     }
   79678     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
   79679     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
   79680     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
   79681     sqlite3VdbeJumpHere(v, addr1);
   79682     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
   79683     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
   79684     sqlite3VdbeJumpHere(v, addr2);
   79685     pSelect->iLimit = 0;
   79686   }
   79687 }
   79688 
   79689 /*
   79690 ** Add code to implement the OFFSET
   79691 */
   79692 static void codeOffset(
   79693   Vdbe *v,          /* Generate code into this VM */
   79694   Select *p,        /* The SELECT statement being coded */
   79695   int iContinue     /* Jump here to skip the current record */
   79696 ){
   79697   if( p->iOffset && iContinue!=0 ){
   79698     int addr;
   79699     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
   79700     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
   79701     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
   79702     VdbeComment((v, "skip OFFSET records"));
   79703     sqlite3VdbeJumpHere(v, addr);
   79704   }
   79705 }
   79706 
   79707 /*
   79708 ** Add code that will check to make sure the N registers starting at iMem
   79709 ** form a distinct entry.  iTab is a sorting index that holds previously
   79710 ** seen combinations of the N values.  A new entry is made in iTab
   79711 ** if the current N values are new.
   79712 **
   79713 ** A jump to addrRepeat is made and the N+1 values are popped from the
   79714 ** stack if the top N elements are not distinct.
   79715 */
   79716 static void codeDistinct(
   79717   Parse *pParse,     /* Parsing and code generating context */
   79718   int iTab,          /* A sorting index used to test for distinctness */
   79719   int addrRepeat,    /* Jump to here if not distinct */
   79720   int N,             /* Number of elements */
   79721   int iMem           /* First element */
   79722 ){
   79723   Vdbe *v;
   79724   int r1;
   79725 
   79726   v = pParse->pVdbe;
   79727   r1 = sqlite3GetTempReg(pParse);
   79728   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
   79729   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
   79730   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
   79731   sqlite3ReleaseTempReg(pParse, r1);
   79732 }
   79733 
   79734 /*
   79735 ** Generate an error message when a SELECT is used within a subexpression
   79736 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
   79737 ** column.  We do this in a subroutine because the error occurs in multiple
   79738 ** places.
   79739 */
   79740 static int checkForMultiColumnSelectError(
   79741   Parse *pParse,       /* Parse context. */
   79742   SelectDest *pDest,   /* Destination of SELECT results */
   79743   int nExpr            /* Number of result columns returned by SELECT */
   79744 ){
   79745   int eDest = pDest->eDest;
   79746   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
   79747     sqlite3ErrorMsg(pParse, "only a single result allowed for "
   79748        "a SELECT that is part of an expression");
   79749     return 1;
   79750   }else{
   79751     return 0;
   79752   }
   79753 }
   79754 
   79755 /*
   79756 ** This routine generates the code for the inside of the inner loop
   79757 ** of a SELECT.
   79758 **
   79759 ** If srcTab and nColumn are both zero, then the pEList expressions
   79760 ** are evaluated in order to get the data for this row.  If nColumn>0
   79761 ** then data is pulled from srcTab and pEList is used only to get the
   79762 ** datatypes for each column.
   79763 */
   79764 static void selectInnerLoop(
   79765   Parse *pParse,          /* The parser context */
   79766   Select *p,              /* The complete select statement being coded */
   79767   ExprList *pEList,       /* List of values being extracted */
   79768   int srcTab,             /* Pull data from this table */
   79769   int nColumn,            /* Number of columns in the source table */
   79770   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
   79771   int distinct,           /* If >=0, make sure results are distinct */
   79772   SelectDest *pDest,      /* How to dispose of the results */
   79773   int iContinue,          /* Jump here to continue with next row */
   79774   int iBreak              /* Jump here to break out of the inner loop */
   79775 ){
   79776   Vdbe *v = pParse->pVdbe;
   79777   int i;
   79778   int hasDistinct;        /* True if the DISTINCT keyword is present */
   79779   int regResult;              /* Start of memory holding result set */
   79780   int eDest = pDest->eDest;   /* How to dispose of results */
   79781   int iParm = pDest->iParm;   /* First argument to disposal method */
   79782   int nResultCol;             /* Number of result columns */
   79783 
   79784   assert( v );
   79785   if( NEVER(v==0) ) return;
   79786   assert( pEList!=0 );
   79787   hasDistinct = distinct>=0;
   79788   if( pOrderBy==0 && !hasDistinct ){
   79789     codeOffset(v, p, iContinue);
   79790   }
   79791 
   79792   /* Pull the requested columns.
   79793   */
   79794   if( nColumn>0 ){
   79795     nResultCol = nColumn;
   79796   }else{
   79797     nResultCol = pEList->nExpr;
   79798   }
   79799   if( pDest->iMem==0 ){
   79800     pDest->iMem = pParse->nMem+1;
   79801     pDest->nMem = nResultCol;
   79802     pParse->nMem += nResultCol;
   79803   }else{
   79804     assert( pDest->nMem==nResultCol );
   79805   }
   79806   regResult = pDest->iMem;
   79807   if( nColumn>0 ){
   79808     for(i=0; i<nColumn; i++){
   79809       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
   79810     }
   79811   }else if( eDest!=SRT_Exists ){
   79812     /* If the destination is an EXISTS(...) expression, the actual
   79813     ** values returned by the SELECT are not required.
   79814     */
   79815     sqlite3ExprCacheClear(pParse);
   79816     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
   79817   }
   79818   nColumn = nResultCol;
   79819 
   79820   /* If the DISTINCT keyword was present on the SELECT statement
   79821   ** and this row has been seen before, then do not make this row
   79822   ** part of the result.
   79823   */
   79824   if( hasDistinct ){
   79825     assert( pEList!=0 );
   79826     assert( pEList->nExpr==nColumn );
   79827     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
   79828     if( pOrderBy==0 ){
   79829       codeOffset(v, p, iContinue);
   79830     }
   79831   }
   79832 
   79833   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
   79834     return;
   79835   }
   79836 
   79837   switch( eDest ){
   79838     /* In this mode, write each query result to the key of the temporary
   79839     ** table iParm.
   79840     */
   79841 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   79842     case SRT_Union: {
   79843       int r1;
   79844       r1 = sqlite3GetTempReg(pParse);
   79845       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
   79846       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
   79847       sqlite3ReleaseTempReg(pParse, r1);
   79848       break;
   79849     }
   79850 
   79851     /* Construct a record from the query result, but instead of
   79852     ** saving that record, use it as a key to delete elements from
   79853     ** the temporary table iParm.
   79854     */
   79855     case SRT_Except: {
   79856       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
   79857       break;
   79858     }
   79859 #endif
   79860 
   79861     /* Store the result as data using a unique key.
   79862     */
   79863     case SRT_Table:
   79864     case SRT_EphemTab: {
   79865       int r1 = sqlite3GetTempReg(pParse);
   79866       testcase( eDest==SRT_Table );
   79867       testcase( eDest==SRT_EphemTab );
   79868       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
   79869       if( pOrderBy ){
   79870         pushOntoSorter(pParse, pOrderBy, p, r1);
   79871       }else{
   79872         int r2 = sqlite3GetTempReg(pParse);
   79873         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
   79874         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
   79875         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   79876         sqlite3ReleaseTempReg(pParse, r2);
   79877       }
   79878       sqlite3ReleaseTempReg(pParse, r1);
   79879       break;
   79880     }
   79881 
   79882 #ifndef SQLITE_OMIT_SUBQUERY
   79883     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
   79884     ** then there should be a single item on the stack.  Write this
   79885     ** item into the set table with bogus data.
   79886     */
   79887     case SRT_Set: {
   79888       assert( nColumn==1 );
   79889       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
   79890       if( pOrderBy ){
   79891         /* At first glance you would think we could optimize out the
   79892         ** ORDER BY in this case since the order of entries in the set
   79893         ** does not matter.  But there might be a LIMIT clause, in which
   79894         ** case the order does matter */
   79895         pushOntoSorter(pParse, pOrderBy, p, regResult);
   79896       }else{
   79897         int r1 = sqlite3GetTempReg(pParse);
   79898         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
   79899         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
   79900         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
   79901         sqlite3ReleaseTempReg(pParse, r1);
   79902       }
   79903       break;
   79904     }
   79905 
   79906     /* If any row exist in the result set, record that fact and abort.
   79907     */
   79908     case SRT_Exists: {
   79909       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
   79910       /* The LIMIT clause will terminate the loop for us */
   79911       break;
   79912     }
   79913 
   79914     /* If this is a scalar select that is part of an expression, then
   79915     ** store the results in the appropriate memory cell and break out
   79916     ** of the scan loop.
   79917     */
   79918     case SRT_Mem: {
   79919       assert( nColumn==1 );
   79920       if( pOrderBy ){
   79921         pushOntoSorter(pParse, pOrderBy, p, regResult);
   79922       }else{
   79923         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
   79924         /* The LIMIT clause will jump out of the loop for us */
   79925       }
   79926       break;
   79927     }
   79928 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
   79929 
   79930     /* Send the data to the callback function or to a subroutine.  In the
   79931     ** case of a subroutine, the subroutine itself is responsible for
   79932     ** popping the data from the stack.
   79933     */
   79934     case SRT_Coroutine:
   79935     case SRT_Output: {
   79936       testcase( eDest==SRT_Coroutine );
   79937       testcase( eDest==SRT_Output );
   79938       if( pOrderBy ){
   79939         int r1 = sqlite3GetTempReg(pParse);
   79940         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
   79941         pushOntoSorter(pParse, pOrderBy, p, r1);
   79942         sqlite3ReleaseTempReg(pParse, r1);
   79943       }else if( eDest==SRT_Coroutine ){
   79944         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
   79945       }else{
   79946         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
   79947         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
   79948       }
   79949       break;
   79950     }
   79951 
   79952 #if !defined(SQLITE_OMIT_TRIGGER)
   79953     /* Discard the results.  This is used for SELECT statements inside
   79954     ** the body of a TRIGGER.  The purpose of such selects is to call
   79955     ** user-defined functions that have side effects.  We do not care
   79956     ** about the actual results of the select.
   79957     */
   79958     default: {
   79959       assert( eDest==SRT_Discard );
   79960       break;
   79961     }
   79962 #endif
   79963   }
   79964 
   79965   /* Jump to the end of the loop if the LIMIT is reached.
   79966   */
   79967   if( p->iLimit ){
   79968     assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
   79969                             ** pushOntoSorter() would have cleared p->iLimit */
   79970     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
   79971   }
   79972 }
   79973 
   79974 /*
   79975 ** Given an expression list, generate a KeyInfo structure that records
   79976 ** the collating sequence for each expression in that expression list.
   79977 **
   79978 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
   79979 ** KeyInfo structure is appropriate for initializing a virtual index to
   79980 ** implement that clause.  If the ExprList is the result set of a SELECT
   79981 ** then the KeyInfo structure is appropriate for initializing a virtual
   79982 ** index to implement a DISTINCT test.
   79983 **
   79984 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
   79985 ** function is responsible for seeing that this structure is eventually
   79986 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
   79987 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
   79988 */
   79989 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
   79990   sqlite3 *db = pParse->db;
   79991   int nExpr;
   79992   KeyInfo *pInfo;
   79993   struct ExprList_item *pItem;
   79994   int i;
   79995 
   79996   nExpr = pList->nExpr;
   79997   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
   79998   if( pInfo ){
   79999     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
   80000     pInfo->nField = (u16)nExpr;
   80001     pInfo->enc = ENC(db);
   80002     pInfo->db = db;
   80003     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
   80004       CollSeq *pColl;
   80005       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
   80006       if( !pColl ){
   80007         pColl = db->pDfltColl;
   80008       }
   80009       pInfo->aColl[i] = pColl;
   80010       pInfo->aSortOrder[i] = pItem->sortOrder;
   80011     }
   80012   }
   80013   return pInfo;
   80014 }
   80015 
   80016 
   80017 /*
   80018 ** If the inner loop was generated using a non-null pOrderBy argument,
   80019 ** then the results were placed in a sorter.  After the loop is terminated
   80020 ** we need to run the sorter and output the results.  The following
   80021 ** routine generates the code needed to do that.
   80022 */
   80023 static void generateSortTail(
   80024   Parse *pParse,    /* Parsing context */
   80025   Select *p,        /* The SELECT statement */
   80026   Vdbe *v,          /* Generate code into this VDBE */
   80027   int nColumn,      /* Number of columns of data */
   80028   SelectDest *pDest /* Write the sorted results here */
   80029 ){
   80030   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
   80031   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
   80032   int addr;
   80033   int iTab;
   80034   int pseudoTab = 0;
   80035   ExprList *pOrderBy = p->pOrderBy;
   80036 
   80037   int eDest = pDest->eDest;
   80038   int iParm = pDest->iParm;
   80039 
   80040   int regRow;
   80041   int regRowid;
   80042 
   80043   iTab = pOrderBy->iECursor;
   80044   regRow = sqlite3GetTempReg(pParse);
   80045   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
   80046     pseudoTab = pParse->nTab++;
   80047     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
   80048     regRowid = 0;
   80049   }else{
   80050     regRowid = sqlite3GetTempReg(pParse);
   80051   }
   80052   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
   80053   codeOffset(v, p, addrContinue);
   80054   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
   80055   switch( eDest ){
   80056     case SRT_Table:
   80057     case SRT_EphemTab: {
   80058       testcase( eDest==SRT_Table );
   80059       testcase( eDest==SRT_EphemTab );
   80060       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
   80061       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
   80062       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   80063       break;
   80064     }
   80065 #ifndef SQLITE_OMIT_SUBQUERY
   80066     case SRT_Set: {
   80067       assert( nColumn==1 );
   80068       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
   80069       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
   80070       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
   80071       break;
   80072     }
   80073     case SRT_Mem: {
   80074       assert( nColumn==1 );
   80075       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
   80076       /* The LIMIT clause will terminate the loop for us */
   80077       break;
   80078     }
   80079 #endif
   80080     default: {
   80081       int i;
   80082       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
   80083       testcase( eDest==SRT_Output );
   80084       testcase( eDest==SRT_Coroutine );
   80085       for(i=0; i<nColumn; i++){
   80086         assert( regRow!=pDest->iMem+i );
   80087         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
   80088         if( i==0 ){
   80089           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
   80090         }
   80091       }
   80092       if( eDest==SRT_Output ){
   80093         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
   80094         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
   80095       }else{
   80096         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
   80097       }
   80098       break;
   80099     }
   80100   }
   80101   sqlite3ReleaseTempReg(pParse, regRow);
   80102   sqlite3ReleaseTempReg(pParse, regRowid);
   80103 
   80104   /* LIMIT has been implemented by the pushOntoSorter() routine.
   80105   */
   80106   assert( p->iLimit==0 );
   80107 
   80108   /* The bottom of the loop
   80109   */
   80110   sqlite3VdbeResolveLabel(v, addrContinue);
   80111   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
   80112   sqlite3VdbeResolveLabel(v, addrBreak);
   80113   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
   80114     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
   80115   }
   80116 }
   80117 
   80118 /*
   80119 ** Return a pointer to a string containing the 'declaration type' of the
   80120 ** expression pExpr. The string may be treated as static by the caller.
   80121 **
   80122 ** The declaration type is the exact datatype definition extracted from the
   80123 ** original CREATE TABLE statement if the expression is a column. The
   80124 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
   80125 ** is considered a column can be complex in the presence of subqueries. The
   80126 ** result-set expression in all of the following SELECT statements is
   80127 ** considered a column by this function.
   80128 **
   80129 **   SELECT col FROM tbl;
   80130 **   SELECT (SELECT col FROM tbl;
   80131 **   SELECT (SELECT col FROM tbl);
   80132 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
   80133 **
   80134 ** The declaration type for any expression other than a column is NULL.
   80135 */
   80136 static const char *columnType(
   80137   NameContext *pNC,
   80138   Expr *pExpr,
   80139   const char **pzOriginDb,
   80140   const char **pzOriginTab,
   80141   const char **pzOriginCol
   80142 ){
   80143   char const *zType = 0;
   80144   char const *zOriginDb = 0;
   80145   char const *zOriginTab = 0;
   80146   char const *zOriginCol = 0;
   80147   int j;
   80148   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
   80149 
   80150   switch( pExpr->op ){
   80151     case TK_AGG_COLUMN:
   80152     case TK_COLUMN: {
   80153       /* The expression is a column. Locate the table the column is being
   80154       ** extracted from in NameContext.pSrcList. This table may be real
   80155       ** database table or a subquery.
   80156       */
   80157       Table *pTab = 0;            /* Table structure column is extracted from */
   80158       Select *pS = 0;             /* Select the column is extracted from */
   80159       int iCol = pExpr->iColumn;  /* Index of column in pTab */
   80160       testcase( pExpr->op==TK_AGG_COLUMN );
   80161       testcase( pExpr->op==TK_COLUMN );
   80162       while( pNC && !pTab ){
   80163         SrcList *pTabList = pNC->pSrcList;
   80164         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
   80165         if( j<pTabList->nSrc ){
   80166           pTab = pTabList->a[j].pTab;
   80167           pS = pTabList->a[j].pSelect;
   80168         }else{
   80169           pNC = pNC->pNext;
   80170         }
   80171       }
   80172 
   80173       if( pTab==0 ){
   80174         /* At one time, code such as "SELECT new.x" within a trigger would
   80175         ** cause this condition to run.  Since then, we have restructured how
   80176         ** trigger code is generated and so this condition is no longer
   80177         ** possible. However, it can still be true for statements like
   80178         ** the following:
   80179         **
   80180         **   CREATE TABLE t1(col INTEGER);
   80181         **   SELECT (SELECT t1.col) FROM FROM t1;
   80182         **
   80183         ** when columnType() is called on the expression "t1.col" in the
   80184         ** sub-select. In this case, set the column type to NULL, even
   80185         ** though it should really be "INTEGER".
   80186         **
   80187         ** This is not a problem, as the column type of "t1.col" is never
   80188         ** used. When columnType() is called on the expression
   80189         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
   80190         ** branch below.  */
   80191         break;
   80192       }
   80193 
   80194       assert( pTab && pExpr->pTab==pTab );
   80195       if( pS ){
   80196         /* The "table" is actually a sub-select or a view in the FROM clause
   80197         ** of the SELECT statement. Return the declaration type and origin
   80198         ** data for the result-set column of the sub-select.
   80199         */
   80200         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
   80201           /* If iCol is less than zero, then the expression requests the
   80202           ** rowid of the sub-select or view. This expression is legal (see
   80203           ** test case misc2.2.2) - it always evaluates to NULL.
   80204           */
   80205           NameContext sNC;
   80206           Expr *p = pS->pEList->a[iCol].pExpr;
   80207           sNC.pSrcList = pS->pSrc;
   80208           sNC.pNext = pNC;
   80209           sNC.pParse = pNC->pParse;
   80210           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
   80211         }
   80212       }else if( ALWAYS(pTab->pSchema) ){
   80213         /* A real table */
   80214         assert( !pS );
   80215         if( iCol<0 ) iCol = pTab->iPKey;
   80216         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
   80217         if( iCol<0 ){
   80218           zType = "INTEGER";
   80219           zOriginCol = "rowid";
   80220         }else{
   80221           zType = pTab->aCol[iCol].zType;
   80222           zOriginCol = pTab->aCol[iCol].zName;
   80223         }
   80224         zOriginTab = pTab->zName;
   80225         if( pNC->pParse ){
   80226           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
   80227           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
   80228         }
   80229       }
   80230       break;
   80231     }
   80232 #ifndef SQLITE_OMIT_SUBQUERY
   80233     case TK_SELECT: {
   80234       /* The expression is a sub-select. Return the declaration type and
   80235       ** origin info for the single column in the result set of the SELECT
   80236       ** statement.
   80237       */
   80238       NameContext sNC;
   80239       Select *pS = pExpr->x.pSelect;
   80240       Expr *p = pS->pEList->a[0].pExpr;
   80241       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
   80242       sNC.pSrcList = pS->pSrc;
   80243       sNC.pNext = pNC;
   80244       sNC.pParse = pNC->pParse;
   80245       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
   80246       break;
   80247     }
   80248 #endif
   80249   }
   80250 
   80251   if( pzOriginDb ){
   80252     assert( pzOriginTab && pzOriginCol );
   80253     *pzOriginDb = zOriginDb;
   80254     *pzOriginTab = zOriginTab;
   80255     *pzOriginCol = zOriginCol;
   80256   }
   80257   return zType;
   80258 }
   80259 
   80260 /*
   80261 ** Generate code that will tell the VDBE the declaration types of columns
   80262 ** in the result set.
   80263 */
   80264 static void generateColumnTypes(
   80265   Parse *pParse,      /* Parser context */
   80266   SrcList *pTabList,  /* List of tables */
   80267   ExprList *pEList    /* Expressions defining the result set */
   80268 ){
   80269 #ifndef SQLITE_OMIT_DECLTYPE
   80270   Vdbe *v = pParse->pVdbe;
   80271   int i;
   80272   NameContext sNC;
   80273   sNC.pSrcList = pTabList;
   80274   sNC.pParse = pParse;
   80275   for(i=0; i<pEList->nExpr; i++){
   80276     Expr *p = pEList->a[i].pExpr;
   80277     const char *zType;
   80278 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   80279     const char *zOrigDb = 0;
   80280     const char *zOrigTab = 0;
   80281     const char *zOrigCol = 0;
   80282     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
   80283 
   80284     /* The vdbe must make its own copy of the column-type and other
   80285     ** column specific strings, in case the schema is reset before this
   80286     ** virtual machine is deleted.
   80287     */
   80288     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
   80289     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
   80290     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
   80291 #else
   80292     zType = columnType(&sNC, p, 0, 0, 0);
   80293 #endif
   80294     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
   80295   }
   80296 #endif /* SQLITE_OMIT_DECLTYPE */
   80297 }
   80298 
   80299 /*
   80300 ** Generate code that will tell the VDBE the names of columns
   80301 ** in the result set.  This information is used to provide the
   80302 ** azCol[] values in the callback.
   80303 */
   80304 static void generateColumnNames(
   80305   Parse *pParse,      /* Parser context */
   80306   SrcList *pTabList,  /* List of tables */
   80307   ExprList *pEList    /* Expressions defining the result set */
   80308 ){
   80309   Vdbe *v = pParse->pVdbe;
   80310   int i, j;
   80311   sqlite3 *db = pParse->db;
   80312   int fullNames, shortNames;
   80313 
   80314 #ifndef SQLITE_OMIT_EXPLAIN
   80315   /* If this is an EXPLAIN, skip this step */
   80316   if( pParse->explain ){
   80317     return;
   80318   }
   80319 #endif
   80320 
   80321   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
   80322   pParse->colNamesSet = 1;
   80323   fullNames = (db->flags & SQLITE_FullColNames)!=0;
   80324   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
   80325   sqlite3VdbeSetNumCols(v, pEList->nExpr);
   80326   for(i=0; i<pEList->nExpr; i++){
   80327     Expr *p;
   80328     p = pEList->a[i].pExpr;
   80329     if( NEVER(p==0) ) continue;
   80330     if( pEList->a[i].zName ){
   80331       char *zName = pEList->a[i].zName;
   80332       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
   80333     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
   80334       Table *pTab;
   80335       char *zCol;
   80336       int iCol = p->iColumn;
   80337       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
   80338         if( pTabList->a[j].iCursor==p->iTable ) break;
   80339       }
   80340       assert( j<pTabList->nSrc );
   80341       pTab = pTabList->a[j].pTab;
   80342       if( iCol<0 ) iCol = pTab->iPKey;
   80343       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
   80344       if( iCol<0 ){
   80345         zCol = "rowid";
   80346       }else{
   80347         zCol = pTab->aCol[iCol].zName;
   80348       }
   80349       if( !shortNames && !fullNames ){
   80350         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
   80351             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
   80352       }else if( fullNames ){
   80353         char *zName = 0;
   80354         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
   80355         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
   80356       }else{
   80357         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
   80358       }
   80359     }else{
   80360       sqlite3VdbeSetColName(v, i, COLNAME_NAME,
   80361           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
   80362     }
   80363   }
   80364   generateColumnTypes(pParse, pTabList, pEList);
   80365 }
   80366 
   80367 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   80368 /*
   80369 ** Name of the connection operator, used for error messages.
   80370 */
   80371 static const char *selectOpName(int id){
   80372   char *z;
   80373   switch( id ){
   80374     case TK_ALL:       z = "UNION ALL";   break;
   80375     case TK_INTERSECT: z = "INTERSECT";   break;
   80376     case TK_EXCEPT:    z = "EXCEPT";      break;
   80377     default:           z = "UNION";       break;
   80378   }
   80379   return z;
   80380 }
   80381 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   80382 
   80383 /*
   80384 ** Given a an expression list (which is really the list of expressions
   80385 ** that form the result set of a SELECT statement) compute appropriate
   80386 ** column names for a table that would hold the expression list.
   80387 **
   80388 ** All column names will be unique.
   80389 **
   80390 ** Only the column names are computed.  Column.zType, Column.zColl,
   80391 ** and other fields of Column are zeroed.
   80392 **
   80393 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
   80394 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
   80395 */
   80396 static int selectColumnsFromExprList(
   80397   Parse *pParse,          /* Parsing context */
   80398   ExprList *pEList,       /* Expr list from which to derive column names */
   80399   int *pnCol,             /* Write the number of columns here */
   80400   Column **paCol          /* Write the new column list here */
   80401 ){
   80402   sqlite3 *db = pParse->db;   /* Database connection */
   80403   int i, j;                   /* Loop counters */
   80404   int cnt;                    /* Index added to make the name unique */
   80405   Column *aCol, *pCol;        /* For looping over result columns */
   80406   int nCol;                   /* Number of columns in the result set */
   80407   Expr *p;                    /* Expression for a single result column */
   80408   char *zName;                /* Column name */
   80409   int nName;                  /* Size of name in zName[] */
   80410 
   80411   *pnCol = nCol = pEList->nExpr;
   80412   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
   80413   if( aCol==0 ) return SQLITE_NOMEM;
   80414   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
   80415     /* Get an appropriate name for the column
   80416     */
   80417     p = pEList->a[i].pExpr;
   80418     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
   80419                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
   80420     if( (zName = pEList->a[i].zName)!=0 ){
   80421       /* If the column contains an "AS <name>" phrase, use <name> as the name */
   80422       zName = sqlite3DbStrDup(db, zName);
   80423     }else{
   80424       Expr *pColExpr = p;  /* The expression that is the result column name */
   80425       Table *pTab;         /* Table associated with this expression */
   80426       while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
   80427       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
   80428         /* For columns use the column name name */
   80429         int iCol = pColExpr->iColumn;
   80430         pTab = pColExpr->pTab;
   80431         if( iCol<0 ) iCol = pTab->iPKey;
   80432         zName = sqlite3MPrintf(db, "%s",
   80433                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
   80434       }else if( pColExpr->op==TK_ID ){
   80435         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
   80436         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
   80437       }else{
   80438         /* Use the original text of the column expression as its name */
   80439         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
   80440       }
   80441     }
   80442     if( db->mallocFailed ){
   80443       sqlite3DbFree(db, zName);
   80444       break;
   80445     }
   80446 
   80447     /* Make sure the column name is unique.  If the name is not unique,
   80448     ** append a integer to the name so that it becomes unique.
   80449     */
   80450     nName = sqlite3Strlen30(zName);
   80451     for(j=cnt=0; j<i; j++){
   80452       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
   80453         char *zNewName;
   80454         zName[nName] = 0;
   80455         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
   80456         sqlite3DbFree(db, zName);
   80457         zName = zNewName;
   80458         j = -1;
   80459         if( zName==0 ) break;
   80460       }
   80461     }
   80462     pCol->zName = zName;
   80463   }
   80464   if( db->mallocFailed ){
   80465     for(j=0; j<i; j++){
   80466       sqlite3DbFree(db, aCol[j].zName);
   80467     }
   80468     sqlite3DbFree(db, aCol);
   80469     *paCol = 0;
   80470     *pnCol = 0;
   80471     return SQLITE_NOMEM;
   80472   }
   80473   return SQLITE_OK;
   80474 }
   80475 
   80476 /*
   80477 ** Add type and collation information to a column list based on
   80478 ** a SELECT statement.
   80479 **
   80480 ** The column list presumably came from selectColumnNamesFromExprList().
   80481 ** The column list has only names, not types or collations.  This
   80482 ** routine goes through and adds the types and collations.
   80483 **
   80484 ** This routine requires that all identifiers in the SELECT
   80485 ** statement be resolved.
   80486 */
   80487 static void selectAddColumnTypeAndCollation(
   80488   Parse *pParse,        /* Parsing contexts */
   80489   int nCol,             /* Number of columns */
   80490   Column *aCol,         /* List of columns */
   80491   Select *pSelect       /* SELECT used to determine types and collations */
   80492 ){
   80493   sqlite3 *db = pParse->db;
   80494   NameContext sNC;
   80495   Column *pCol;
   80496   CollSeq *pColl;
   80497   int i;
   80498   Expr *p;
   80499   struct ExprList_item *a;
   80500 
   80501   assert( pSelect!=0 );
   80502   assert( (pSelect->selFlags & SF_Resolved)!=0 );
   80503   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
   80504   if( db->mallocFailed ) return;
   80505   memset(&sNC, 0, sizeof(sNC));
   80506   sNC.pSrcList = pSelect->pSrc;
   80507   a = pSelect->pEList->a;
   80508   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
   80509     p = a[i].pExpr;
   80510     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
   80511     pCol->affinity = sqlite3ExprAffinity(p);
   80512     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
   80513     pColl = sqlite3ExprCollSeq(pParse, p);
   80514     if( pColl ){
   80515       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
   80516     }
   80517   }
   80518 }
   80519 
   80520 /*
   80521 ** Given a SELECT statement, generate a Table structure that describes
   80522 ** the result set of that SELECT.
   80523 */
   80524 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
   80525   Table *pTab;
   80526   sqlite3 *db = pParse->db;
   80527   int savedFlags;
   80528 
   80529   savedFlags = db->flags;
   80530   db->flags &= ~SQLITE_FullColNames;
   80531   db->flags |= SQLITE_ShortColNames;
   80532   sqlite3SelectPrep(pParse, pSelect, 0);
   80533   if( pParse->nErr ) return 0;
   80534   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
   80535   db->flags = savedFlags;
   80536   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
   80537   if( pTab==0 ){
   80538     return 0;
   80539   }
   80540   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
   80541   ** is disabled, so we might as well hard-code pTab->dbMem to NULL. */
   80542   assert( db->lookaside.bEnabled==0 );
   80543   pTab->dbMem = 0;
   80544   pTab->nRef = 1;
   80545   pTab->zName = 0;
   80546   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
   80547   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
   80548   pTab->iPKey = -1;
   80549   if( db->mallocFailed ){
   80550     sqlite3DeleteTable(pTab);
   80551     return 0;
   80552   }
   80553   return pTab;
   80554 }
   80555 
   80556 /*
   80557 ** Get a VDBE for the given parser context.  Create a new one if necessary.
   80558 ** If an error occurs, return NULL and leave a message in pParse.
   80559 */
   80560 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
   80561   Vdbe *v = pParse->pVdbe;
   80562   if( v==0 ){
   80563     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
   80564 #ifndef SQLITE_OMIT_TRACE
   80565     if( v ){
   80566       sqlite3VdbeAddOp0(v, OP_Trace);
   80567     }
   80568 #endif
   80569   }
   80570   return v;
   80571 }
   80572 
   80573 
   80574 /*
   80575 ** Compute the iLimit and iOffset fields of the SELECT based on the
   80576 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
   80577 ** that appear in the original SQL statement after the LIMIT and OFFSET
   80578 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
   80579 ** are the integer memory register numbers for counters used to compute
   80580 ** the limit and offset.  If there is no limit and/or offset, then
   80581 ** iLimit and iOffset are negative.
   80582 **
   80583 ** This routine changes the values of iLimit and iOffset only if
   80584 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
   80585 ** iOffset should have been preset to appropriate default values
   80586 ** (usually but not always -1) prior to calling this routine.
   80587 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
   80588 ** redefined.  The UNION ALL operator uses this property to force
   80589 ** the reuse of the same limit and offset registers across multiple
   80590 ** SELECT statements.
   80591 */
   80592 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
   80593   Vdbe *v = 0;
   80594   int iLimit = 0;
   80595   int iOffset;
   80596   int addr1, n;
   80597   if( p->iLimit ) return;
   80598 
   80599   /*
   80600   ** "LIMIT -1" always shows all rows.  There is some
   80601   ** contraversy about what the correct behavior should be.
   80602   ** The current implementation interprets "LIMIT 0" to mean
   80603   ** no rows.
   80604   */
   80605   sqlite3ExprCacheClear(pParse);
   80606   assert( p->pOffset==0 || p->pLimit!=0 );
   80607   if( p->pLimit ){
   80608     p->iLimit = iLimit = ++pParse->nMem;
   80609     v = sqlite3GetVdbe(pParse);
   80610     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
   80611     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
   80612       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
   80613       VdbeComment((v, "LIMIT counter"));
   80614       if( n==0 ){
   80615         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
   80616       }
   80617     }else{
   80618       sqlite3ExprCode(pParse, p->pLimit, iLimit);
   80619       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
   80620       VdbeComment((v, "LIMIT counter"));
   80621       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
   80622     }
   80623     if( p->pOffset ){
   80624       p->iOffset = iOffset = ++pParse->nMem;
   80625       pParse->nMem++;   /* Allocate an extra register for limit+offset */
   80626       sqlite3ExprCode(pParse, p->pOffset, iOffset);
   80627       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
   80628       VdbeComment((v, "OFFSET counter"));
   80629       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
   80630       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
   80631       sqlite3VdbeJumpHere(v, addr1);
   80632       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
   80633       VdbeComment((v, "LIMIT+OFFSET"));
   80634       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
   80635       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
   80636       sqlite3VdbeJumpHere(v, addr1);
   80637     }
   80638   }
   80639 }
   80640 
   80641 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   80642 /*
   80643 ** Return the appropriate collating sequence for the iCol-th column of
   80644 ** the result set for the compound-select statement "p".  Return NULL if
   80645 ** the column has no default collating sequence.
   80646 **
   80647 ** The collating sequence for the compound select is taken from the
   80648 ** left-most term of the select that has a collating sequence.
   80649 */
   80650 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
   80651   CollSeq *pRet;
   80652   if( p->pPrior ){
   80653     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
   80654   }else{
   80655     pRet = 0;
   80656   }
   80657   assert( iCol>=0 );
   80658   if( pRet==0 && iCol<p->pEList->nExpr ){
   80659     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
   80660   }
   80661   return pRet;
   80662 }
   80663 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   80664 
   80665 /* Forward reference */
   80666 static int multiSelectOrderBy(
   80667   Parse *pParse,        /* Parsing context */
   80668   Select *p,            /* The right-most of SELECTs to be coded */
   80669   SelectDest *pDest     /* What to do with query results */
   80670 );
   80671 
   80672 
   80673 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   80674 /*
   80675 ** This routine is called to process a compound query form from
   80676 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
   80677 ** INTERSECT
   80678 **
   80679 ** "p" points to the right-most of the two queries.  the query on the
   80680 ** left is p->pPrior.  The left query could also be a compound query
   80681 ** in which case this routine will be called recursively.
   80682 **
   80683 ** The results of the total query are to be written into a destination
   80684 ** of type eDest with parameter iParm.
   80685 **
   80686 ** Example 1:  Consider a three-way compound SQL statement.
   80687 **
   80688 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
   80689 **
   80690 ** This statement is parsed up as follows:
   80691 **
   80692 **     SELECT c FROM t3
   80693 **      |
   80694 **      `----->  SELECT b FROM t2
   80695 **                |
   80696 **                `------>  SELECT a FROM t1
   80697 **
   80698 ** The arrows in the diagram above represent the Select.pPrior pointer.
   80699 ** So if this routine is called with p equal to the t3 query, then
   80700 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
   80701 **
   80702 ** Notice that because of the way SQLite parses compound SELECTs, the
   80703 ** individual selects always group from left to right.
   80704 */
   80705 static int multiSelect(
   80706   Parse *pParse,        /* Parsing context */
   80707   Select *p,            /* The right-most of SELECTs to be coded */
   80708   SelectDest *pDest     /* What to do with query results */
   80709 ){
   80710   int rc = SQLITE_OK;   /* Success code from a subroutine */
   80711   Select *pPrior;       /* Another SELECT immediately to our left */
   80712   Vdbe *v;              /* Generate code to this VDBE */
   80713   SelectDest dest;      /* Alternative data destination */
   80714   Select *pDelete = 0;  /* Chain of simple selects to delete */
   80715   sqlite3 *db;          /* Database connection */
   80716 
   80717   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
   80718   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
   80719   */
   80720   assert( p && p->pPrior );  /* Calling function guarantees this much */
   80721   db = pParse->db;
   80722   pPrior = p->pPrior;
   80723   assert( pPrior->pRightmost!=pPrior );
   80724   assert( pPrior->pRightmost==p->pRightmost );
   80725   dest = *pDest;
   80726   if( pPrior->pOrderBy ){
   80727     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
   80728       selectOpName(p->op));
   80729     rc = 1;
   80730     goto multi_select_end;
   80731   }
   80732   if( pPrior->pLimit ){
   80733     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
   80734       selectOpName(p->op));
   80735     rc = 1;
   80736     goto multi_select_end;
   80737   }
   80738 
   80739   v = sqlite3GetVdbe(pParse);
   80740   assert( v!=0 );  /* The VDBE already created by calling function */
   80741 
   80742   /* Create the destination temporary table if necessary
   80743   */
   80744   if( dest.eDest==SRT_EphemTab ){
   80745     assert( p->pEList );
   80746     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
   80747     dest.eDest = SRT_Table;
   80748   }
   80749 
   80750   /* Make sure all SELECTs in the statement have the same number of elements
   80751   ** in their result sets.
   80752   */
   80753   assert( p->pEList && pPrior->pEList );
   80754   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
   80755     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
   80756       " do not have the same number of result columns", selectOpName(p->op));
   80757     rc = 1;
   80758     goto multi_select_end;
   80759   }
   80760 
   80761   /* Compound SELECTs that have an ORDER BY clause are handled separately.
   80762   */
   80763   if( p->pOrderBy ){
   80764     return multiSelectOrderBy(pParse, p, pDest);
   80765   }
   80766 
   80767   /* Generate code for the left and right SELECT statements.
   80768   */
   80769   switch( p->op ){
   80770     case TK_ALL: {
   80771       int addr = 0;
   80772       assert( !pPrior->pLimit );
   80773       pPrior->pLimit = p->pLimit;
   80774       pPrior->pOffset = p->pOffset;
   80775       rc = sqlite3Select(pParse, pPrior, &dest);
   80776       p->pLimit = 0;
   80777       p->pOffset = 0;
   80778       if( rc ){
   80779         goto multi_select_end;
   80780       }
   80781       p->pPrior = 0;
   80782       p->iLimit = pPrior->iLimit;
   80783       p->iOffset = pPrior->iOffset;
   80784       if( p->iLimit ){
   80785         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
   80786         VdbeComment((v, "Jump ahead if LIMIT reached"));
   80787       }
   80788       rc = sqlite3Select(pParse, p, &dest);
   80789       testcase( rc!=SQLITE_OK );
   80790       pDelete = p->pPrior;
   80791       p->pPrior = pPrior;
   80792       if( addr ){
   80793         sqlite3VdbeJumpHere(v, addr);
   80794       }
   80795       break;
   80796     }
   80797     case TK_EXCEPT:
   80798     case TK_UNION: {
   80799       int unionTab;    /* Cursor number of the temporary table holding result */
   80800       u8 op = 0;       /* One of the SRT_ operations to apply to self */
   80801       int priorOp;     /* The SRT_ operation to apply to prior selects */
   80802       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
   80803       int addr;
   80804       SelectDest uniondest;
   80805 
   80806       testcase( p->op==TK_EXCEPT );
   80807       testcase( p->op==TK_UNION );
   80808       priorOp = SRT_Union;
   80809       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
   80810         /* We can reuse a temporary table generated by a SELECT to our
   80811         ** right.
   80812         */
   80813         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
   80814                                      ** of a 3-way or more compound */
   80815         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
   80816         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
   80817         unionTab = dest.iParm;
   80818       }else{
   80819         /* We will need to create our own temporary table to hold the
   80820         ** intermediate results.
   80821         */
   80822         unionTab = pParse->nTab++;
   80823         assert( p->pOrderBy==0 );
   80824         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
   80825         assert( p->addrOpenEphm[0] == -1 );
   80826         p->addrOpenEphm[0] = addr;
   80827         p->pRightmost->selFlags |= SF_UsesEphemeral;
   80828         assert( p->pEList );
   80829       }
   80830 
   80831       /* Code the SELECT statements to our left
   80832       */
   80833       assert( !pPrior->pOrderBy );
   80834       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
   80835       rc = sqlite3Select(pParse, pPrior, &uniondest);
   80836       if( rc ){
   80837         goto multi_select_end;
   80838       }
   80839 
   80840       /* Code the current SELECT statement
   80841       */
   80842       if( p->op==TK_EXCEPT ){
   80843         op = SRT_Except;
   80844       }else{
   80845         assert( p->op==TK_UNION );
   80846         op = SRT_Union;
   80847       }
   80848       p->pPrior = 0;
   80849       pLimit = p->pLimit;
   80850       p->pLimit = 0;
   80851       pOffset = p->pOffset;
   80852       p->pOffset = 0;
   80853       uniondest.eDest = op;
   80854       rc = sqlite3Select(pParse, p, &uniondest);
   80855       testcase( rc!=SQLITE_OK );
   80856       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
   80857       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
   80858       sqlite3ExprListDelete(db, p->pOrderBy);
   80859       pDelete = p->pPrior;
   80860       p->pPrior = pPrior;
   80861       p->pOrderBy = 0;
   80862       sqlite3ExprDelete(db, p->pLimit);
   80863       p->pLimit = pLimit;
   80864       p->pOffset = pOffset;
   80865       p->iLimit = 0;
   80866       p->iOffset = 0;
   80867 
   80868       /* Convert the data in the temporary table into whatever form
   80869       ** it is that we currently need.
   80870       */
   80871       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
   80872       if( dest.eDest!=priorOp ){
   80873         int iCont, iBreak, iStart;
   80874         assert( p->pEList );
   80875         if( dest.eDest==SRT_Output ){
   80876           Select *pFirst = p;
   80877           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   80878           generateColumnNames(pParse, 0, pFirst->pEList);
   80879         }
   80880         iBreak = sqlite3VdbeMakeLabel(v);
   80881         iCont = sqlite3VdbeMakeLabel(v);
   80882         computeLimitRegisters(pParse, p, iBreak);
   80883         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
   80884         iStart = sqlite3VdbeCurrentAddr(v);
   80885         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
   80886                         0, -1, &dest, iCont, iBreak);
   80887         sqlite3VdbeResolveLabel(v, iCont);
   80888         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
   80889         sqlite3VdbeResolveLabel(v, iBreak);
   80890         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
   80891       }
   80892       break;
   80893     }
   80894     default: assert( p->op==TK_INTERSECT ); {
   80895       int tab1, tab2;
   80896       int iCont, iBreak, iStart;
   80897       Expr *pLimit, *pOffset;
   80898       int addr;
   80899       SelectDest intersectdest;
   80900       int r1;
   80901 
   80902       /* INTERSECT is different from the others since it requires
   80903       ** two temporary tables.  Hence it has its own case.  Begin
   80904       ** by allocating the tables we will need.
   80905       */
   80906       tab1 = pParse->nTab++;
   80907       tab2 = pParse->nTab++;
   80908       assert( p->pOrderBy==0 );
   80909 
   80910       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
   80911       assert( p->addrOpenEphm[0] == -1 );
   80912       p->addrOpenEphm[0] = addr;
   80913       p->pRightmost->selFlags |= SF_UsesEphemeral;
   80914       assert( p->pEList );
   80915 
   80916       /* Code the SELECTs to our left into temporary table "tab1".
   80917       */
   80918       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
   80919       rc = sqlite3Select(pParse, pPrior, &intersectdest);
   80920       if( rc ){
   80921         goto multi_select_end;
   80922       }
   80923 
   80924       /* Code the current SELECT into temporary table "tab2"
   80925       */
   80926       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
   80927       assert( p->addrOpenEphm[1] == -1 );
   80928       p->addrOpenEphm[1] = addr;
   80929       p->pPrior = 0;
   80930       pLimit = p->pLimit;
   80931       p->pLimit = 0;
   80932       pOffset = p->pOffset;
   80933       p->pOffset = 0;
   80934       intersectdest.iParm = tab2;
   80935       rc = sqlite3Select(pParse, p, &intersectdest);
   80936       testcase( rc!=SQLITE_OK );
   80937       pDelete = p->pPrior;
   80938       p->pPrior = pPrior;
   80939       sqlite3ExprDelete(db, p->pLimit);
   80940       p->pLimit = pLimit;
   80941       p->pOffset = pOffset;
   80942 
   80943       /* Generate code to take the intersection of the two temporary
   80944       ** tables.
   80945       */
   80946       assert( p->pEList );
   80947       if( dest.eDest==SRT_Output ){
   80948         Select *pFirst = p;
   80949         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   80950         generateColumnNames(pParse, 0, pFirst->pEList);
   80951       }
   80952       iBreak = sqlite3VdbeMakeLabel(v);
   80953       iCont = sqlite3VdbeMakeLabel(v);
   80954       computeLimitRegisters(pParse, p, iBreak);
   80955       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
   80956       r1 = sqlite3GetTempReg(pParse);
   80957       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
   80958       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
   80959       sqlite3ReleaseTempReg(pParse, r1);
   80960       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
   80961                       0, -1, &dest, iCont, iBreak);
   80962       sqlite3VdbeResolveLabel(v, iCont);
   80963       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
   80964       sqlite3VdbeResolveLabel(v, iBreak);
   80965       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
   80966       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
   80967       break;
   80968     }
   80969   }
   80970 
   80971   /* Compute collating sequences used by
   80972   ** temporary tables needed to implement the compound select.
   80973   ** Attach the KeyInfo structure to all temporary tables.
   80974   **
   80975   ** This section is run by the right-most SELECT statement only.
   80976   ** SELECT statements to the left always skip this part.  The right-most
   80977   ** SELECT might also skip this part if it has no ORDER BY clause and
   80978   ** no temp tables are required.
   80979   */
   80980   if( p->selFlags & SF_UsesEphemeral ){
   80981     int i;                        /* Loop counter */
   80982     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
   80983     Select *pLoop;                /* For looping through SELECT statements */
   80984     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
   80985     int nCol;                     /* Number of columns in result set */
   80986 
   80987     assert( p->pRightmost==p );
   80988     nCol = p->pEList->nExpr;
   80989     pKeyInfo = sqlite3DbMallocZero(db,
   80990                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
   80991     if( !pKeyInfo ){
   80992       rc = SQLITE_NOMEM;
   80993       goto multi_select_end;
   80994     }
   80995 
   80996     pKeyInfo->enc = ENC(db);
   80997     pKeyInfo->nField = (u16)nCol;
   80998 
   80999     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
   81000       *apColl = multiSelectCollSeq(pParse, p, i);
   81001       if( 0==*apColl ){
   81002         *apColl = db->pDfltColl;
   81003       }
   81004     }
   81005 
   81006     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
   81007       for(i=0; i<2; i++){
   81008         int addr = pLoop->addrOpenEphm[i];
   81009         if( addr<0 ){
   81010           /* If [0] is unused then [1] is also unused.  So we can
   81011           ** always safely abort as soon as the first unused slot is found */
   81012           assert( pLoop->addrOpenEphm[1]<0 );
   81013           break;
   81014         }
   81015         sqlite3VdbeChangeP2(v, addr, nCol);
   81016         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
   81017         pLoop->addrOpenEphm[i] = -1;
   81018       }
   81019     }
   81020     sqlite3DbFree(db, pKeyInfo);
   81021   }
   81022 
   81023 multi_select_end:
   81024   pDest->iMem = dest.iMem;
   81025   pDest->nMem = dest.nMem;
   81026   sqlite3SelectDelete(db, pDelete);
   81027   return rc;
   81028 }
   81029 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   81030 
   81031 /*
   81032 ** Code an output subroutine for a coroutine implementation of a
   81033 ** SELECT statment.
   81034 **
   81035 ** The data to be output is contained in pIn->iMem.  There are
   81036 ** pIn->nMem columns to be output.  pDest is where the output should
   81037 ** be sent.
   81038 **
   81039 ** regReturn is the number of the register holding the subroutine
   81040 ** return address.
   81041 **
   81042 ** If regPrev>0 then it is a the first register in a vector that
   81043 ** records the previous output.  mem[regPrev] is a flag that is false
   81044 ** if there has been no previous output.  If regPrev>0 then code is
   81045 ** generated to suppress duplicates.  pKeyInfo is used for comparing
   81046 ** keys.
   81047 **
   81048 ** If the LIMIT found in p->iLimit is reached, jump immediately to
   81049 ** iBreak.
   81050 */
   81051 static int generateOutputSubroutine(
   81052   Parse *pParse,          /* Parsing context */
   81053   Select *p,              /* The SELECT statement */
   81054   SelectDest *pIn,        /* Coroutine supplying data */
   81055   SelectDest *pDest,      /* Where to send the data */
   81056   int regReturn,          /* The return address register */
   81057   int regPrev,            /* Previous result register.  No uniqueness if 0 */
   81058   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
   81059   int p4type,             /* The p4 type for pKeyInfo */
   81060   int iBreak              /* Jump here if we hit the LIMIT */
   81061 ){
   81062   Vdbe *v = pParse->pVdbe;
   81063   int iContinue;
   81064   int addr;
   81065 
   81066   addr = sqlite3VdbeCurrentAddr(v);
   81067   iContinue = sqlite3VdbeMakeLabel(v);
   81068 
   81069   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
   81070   */
   81071   if( regPrev ){
   81072     int j1, j2;
   81073     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
   81074     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
   81075                               (char*)pKeyInfo, p4type);
   81076     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
   81077     sqlite3VdbeJumpHere(v, j1);
   81078     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
   81079     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
   81080   }
   81081   if( pParse->db->mallocFailed ) return 0;
   81082 
   81083   /* Suppress the the first OFFSET entries if there is an OFFSET clause
   81084   */
   81085   codeOffset(v, p, iContinue);
   81086 
   81087   switch( pDest->eDest ){
   81088     /* Store the result as data using a unique key.
   81089     */
   81090     case SRT_Table:
   81091     case SRT_EphemTab: {
   81092       int r1 = sqlite3GetTempReg(pParse);
   81093       int r2 = sqlite3GetTempReg(pParse);
   81094       testcase( pDest->eDest==SRT_Table );
   81095       testcase( pDest->eDest==SRT_EphemTab );
   81096       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
   81097       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
   81098       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
   81099       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   81100       sqlite3ReleaseTempReg(pParse, r2);
   81101       sqlite3ReleaseTempReg(pParse, r1);
   81102       break;
   81103     }
   81104 
   81105 #ifndef SQLITE_OMIT_SUBQUERY
   81106     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
   81107     ** then there should be a single item on the stack.  Write this
   81108     ** item into the set table with bogus data.
   81109     */
   81110     case SRT_Set: {
   81111       int r1;
   81112       assert( pIn->nMem==1 );
   81113       p->affinity =
   81114          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
   81115       r1 = sqlite3GetTempReg(pParse);
   81116       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
   81117       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
   81118       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
   81119       sqlite3ReleaseTempReg(pParse, r1);
   81120       break;
   81121     }
   81122 
   81123 #if 0  /* Never occurs on an ORDER BY query */
   81124     /* If any row exist in the result set, record that fact and abort.
   81125     */
   81126     case SRT_Exists: {
   81127       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
   81128       /* The LIMIT clause will terminate the loop for us */
   81129       break;
   81130     }
   81131 #endif
   81132 
   81133     /* If this is a scalar select that is part of an expression, then
   81134     ** store the results in the appropriate memory cell and break out
   81135     ** of the scan loop.
   81136     */
   81137     case SRT_Mem: {
   81138       assert( pIn->nMem==1 );
   81139       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
   81140       /* The LIMIT clause will jump out of the loop for us */
   81141       break;
   81142     }
   81143 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
   81144 
   81145     /* The results are stored in a sequence of registers
   81146     ** starting at pDest->iMem.  Then the co-routine yields.
   81147     */
   81148     case SRT_Coroutine: {
   81149       if( pDest->iMem==0 ){
   81150         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
   81151         pDest->nMem = pIn->nMem;
   81152       }
   81153       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
   81154       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
   81155       break;
   81156     }
   81157 
   81158     /* If none of the above, then the result destination must be
   81159     ** SRT_Output.  This routine is never called with any other
   81160     ** destination other than the ones handled above or SRT_Output.
   81161     **
   81162     ** For SRT_Output, results are stored in a sequence of registers.
   81163     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
   81164     ** return the next row of result.
   81165     */
   81166     default: {
   81167       assert( pDest->eDest==SRT_Output );
   81168       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
   81169       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
   81170       break;
   81171     }
   81172   }
   81173 
   81174   /* Jump to the end of the loop if the LIMIT is reached.
   81175   */
   81176   if( p->iLimit ){
   81177     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
   81178   }
   81179 
   81180   /* Generate the subroutine return
   81181   */
   81182   sqlite3VdbeResolveLabel(v, iContinue);
   81183   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
   81184 
   81185   return addr;
   81186 }
   81187 
   81188 /*
   81189 ** Alternative compound select code generator for cases when there
   81190 ** is an ORDER BY clause.
   81191 **
   81192 ** We assume a query of the following form:
   81193 **
   81194 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
   81195 **
   81196 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
   81197 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
   81198 ** co-routines.  Then run the co-routines in parallel and merge the results
   81199 ** into the output.  In addition to the two coroutines (called selectA and
   81200 ** selectB) there are 7 subroutines:
   81201 **
   81202 **    outA:    Move the output of the selectA coroutine into the output
   81203 **             of the compound query.
   81204 **
   81205 **    outB:    Move the output of the selectB coroutine into the output
   81206 **             of the compound query.  (Only generated for UNION and
   81207 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
   81208 **             appears only in B.)
   81209 **
   81210 **    AltB:    Called when there is data from both coroutines and A<B.
   81211 **
   81212 **    AeqB:    Called when there is data from both coroutines and A==B.
   81213 **
   81214 **    AgtB:    Called when there is data from both coroutines and A>B.
   81215 **
   81216 **    EofA:    Called when data is exhausted from selectA.
   81217 **
   81218 **    EofB:    Called when data is exhausted from selectB.
   81219 **
   81220 ** The implementation of the latter five subroutines depend on which
   81221 ** <operator> is used:
   81222 **
   81223 **
   81224 **             UNION ALL         UNION            EXCEPT          INTERSECT
   81225 **          -------------  -----------------  --------------  -----------------
   81226 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
   81227 **
   81228 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
   81229 **
   81230 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
   81231 **
   81232 **   EofA:   outB, nextB      outB, nextB          halt             halt
   81233 **
   81234 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
   81235 **
   81236 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
   81237 ** causes an immediate jump to EofA and an EOF on B following nextB causes
   81238 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
   81239 ** following nextX causes a jump to the end of the select processing.
   81240 **
   81241 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
   81242 ** within the output subroutine.  The regPrev register set holds the previously
   81243 ** output value.  A comparison is made against this value and the output
   81244 ** is skipped if the next results would be the same as the previous.
   81245 **
   81246 ** The implementation plan is to implement the two coroutines and seven
   81247 ** subroutines first, then put the control logic at the bottom.  Like this:
   81248 **
   81249 **          goto Init
   81250 **     coA: coroutine for left query (A)
   81251 **     coB: coroutine for right query (B)
   81252 **    outA: output one row of A
   81253 **    outB: output one row of B (UNION and UNION ALL only)
   81254 **    EofA: ...
   81255 **    EofB: ...
   81256 **    AltB: ...
   81257 **    AeqB: ...
   81258 **    AgtB: ...
   81259 **    Init: initialize coroutine registers
   81260 **          yield coA
   81261 **          if eof(A) goto EofA
   81262 **          yield coB
   81263 **          if eof(B) goto EofB
   81264 **    Cmpr: Compare A, B
   81265 **          Jump AltB, AeqB, AgtB
   81266 **     End: ...
   81267 **
   81268 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
   81269 ** actually called using Gosub and they do not Return.  EofA and EofB loop
   81270 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
   81271 ** and AgtB jump to either L2 or to one of EofA or EofB.
   81272 */
   81273 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   81274 static int multiSelectOrderBy(
   81275   Parse *pParse,        /* Parsing context */
   81276   Select *p,            /* The right-most of SELECTs to be coded */
   81277   SelectDest *pDest     /* What to do with query results */
   81278 ){
   81279   int i, j;             /* Loop counters */
   81280   Select *pPrior;       /* Another SELECT immediately to our left */
   81281   Vdbe *v;              /* Generate code to this VDBE */
   81282   SelectDest destA;     /* Destination for coroutine A */
   81283   SelectDest destB;     /* Destination for coroutine B */
   81284   int regAddrA;         /* Address register for select-A coroutine */
   81285   int regEofA;          /* Flag to indicate when select-A is complete */
   81286   int regAddrB;         /* Address register for select-B coroutine */
   81287   int regEofB;          /* Flag to indicate when select-B is complete */
   81288   int addrSelectA;      /* Address of the select-A coroutine */
   81289   int addrSelectB;      /* Address of the select-B coroutine */
   81290   int regOutA;          /* Address register for the output-A subroutine */
   81291   int regOutB;          /* Address register for the output-B subroutine */
   81292   int addrOutA;         /* Address of the output-A subroutine */
   81293   int addrOutB = 0;     /* Address of the output-B subroutine */
   81294   int addrEofA;         /* Address of the select-A-exhausted subroutine */
   81295   int addrEofB;         /* Address of the select-B-exhausted subroutine */
   81296   int addrAltB;         /* Address of the A<B subroutine */
   81297   int addrAeqB;         /* Address of the A==B subroutine */
   81298   int addrAgtB;         /* Address of the A>B subroutine */
   81299   int regLimitA;        /* Limit register for select-A */
   81300   int regLimitB;        /* Limit register for select-A */
   81301   int regPrev;          /* A range of registers to hold previous output */
   81302   int savedLimit;       /* Saved value of p->iLimit */
   81303   int savedOffset;      /* Saved value of p->iOffset */
   81304   int labelCmpr;        /* Label for the start of the merge algorithm */
   81305   int labelEnd;         /* Label for the end of the overall SELECT stmt */
   81306   int j1;               /* Jump instructions that get retargetted */
   81307   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
   81308   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
   81309   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
   81310   sqlite3 *db;          /* Database connection */
   81311   ExprList *pOrderBy;   /* The ORDER BY clause */
   81312   int nOrderBy;         /* Number of terms in the ORDER BY clause */
   81313   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
   81314 
   81315   assert( p->pOrderBy!=0 );
   81316   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
   81317   db = pParse->db;
   81318   v = pParse->pVdbe;
   81319   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
   81320   labelEnd = sqlite3VdbeMakeLabel(v);
   81321   labelCmpr = sqlite3VdbeMakeLabel(v);
   81322 
   81323 
   81324   /* Patch up the ORDER BY clause
   81325   */
   81326   op = p->op;
   81327   pPrior = p->pPrior;
   81328   assert( pPrior->pOrderBy==0 );
   81329   pOrderBy = p->pOrderBy;
   81330   assert( pOrderBy );
   81331   nOrderBy = pOrderBy->nExpr;
   81332 
   81333   /* For operators other than UNION ALL we have to make sure that
   81334   ** the ORDER BY clause covers every term of the result set.  Add
   81335   ** terms to the ORDER BY clause as necessary.
   81336   */
   81337   if( op!=TK_ALL ){
   81338     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
   81339       struct ExprList_item *pItem;
   81340       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
   81341         assert( pItem->iCol>0 );
   81342         if( pItem->iCol==i ) break;
   81343       }
   81344       if( j==nOrderBy ){
   81345         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
   81346         if( pNew==0 ) return SQLITE_NOMEM;
   81347         pNew->flags |= EP_IntValue;
   81348         pNew->u.iValue = i;
   81349         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
   81350         pOrderBy->a[nOrderBy++].iCol = (u16)i;
   81351       }
   81352     }
   81353   }
   81354 
   81355   /* Compute the comparison permutation and keyinfo that is used with
   81356   ** the permutation used to determine if the next
   81357   ** row of results comes from selectA or selectB.  Also add explicit
   81358   ** collations to the ORDER BY clause terms so that when the subqueries
   81359   ** to the right and the left are evaluated, they use the correct
   81360   ** collation.
   81361   */
   81362   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
   81363   if( aPermute ){
   81364     struct ExprList_item *pItem;
   81365     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
   81366       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
   81367       aPermute[i] = pItem->iCol - 1;
   81368     }
   81369     pKeyMerge =
   81370       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
   81371     if( pKeyMerge ){
   81372       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
   81373       pKeyMerge->nField = (u16)nOrderBy;
   81374       pKeyMerge->enc = ENC(db);
   81375       for(i=0; i<nOrderBy; i++){
   81376         CollSeq *pColl;
   81377         Expr *pTerm = pOrderBy->a[i].pExpr;
   81378         if( pTerm->flags & EP_ExpCollate ){
   81379           pColl = pTerm->pColl;
   81380         }else{
   81381           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
   81382           pTerm->flags |= EP_ExpCollate;
   81383           pTerm->pColl = pColl;
   81384         }
   81385         pKeyMerge->aColl[i] = pColl;
   81386         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
   81387       }
   81388     }
   81389   }else{
   81390     pKeyMerge = 0;
   81391   }
   81392 
   81393   /* Reattach the ORDER BY clause to the query.
   81394   */
   81395   p->pOrderBy = pOrderBy;
   81396   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
   81397 
   81398   /* Allocate a range of temporary registers and the KeyInfo needed
   81399   ** for the logic that removes duplicate result rows when the
   81400   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
   81401   */
   81402   if( op==TK_ALL ){
   81403     regPrev = 0;
   81404   }else{
   81405     int nExpr = p->pEList->nExpr;
   81406     assert( nOrderBy>=nExpr || db->mallocFailed );
   81407     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
   81408     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
   81409     pKeyDup = sqlite3DbMallocZero(db,
   81410                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
   81411     if( pKeyDup ){
   81412       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
   81413       pKeyDup->nField = (u16)nExpr;
   81414       pKeyDup->enc = ENC(db);
   81415       for(i=0; i<nExpr; i++){
   81416         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
   81417         pKeyDup->aSortOrder[i] = 0;
   81418       }
   81419     }
   81420   }
   81421 
   81422   /* Separate the left and the right query from one another
   81423   */
   81424   p->pPrior = 0;
   81425   pPrior->pRightmost = 0;
   81426   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
   81427   if( pPrior->pPrior==0 ){
   81428     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
   81429   }
   81430 
   81431   /* Compute the limit registers */
   81432   computeLimitRegisters(pParse, p, labelEnd);
   81433   if( p->iLimit && op==TK_ALL ){
   81434     regLimitA = ++pParse->nMem;
   81435     regLimitB = ++pParse->nMem;
   81436     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
   81437                                   regLimitA);
   81438     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
   81439   }else{
   81440     regLimitA = regLimitB = 0;
   81441   }
   81442   sqlite3ExprDelete(db, p->pLimit);
   81443   p->pLimit = 0;
   81444   sqlite3ExprDelete(db, p->pOffset);
   81445   p->pOffset = 0;
   81446 
   81447   regAddrA = ++pParse->nMem;
   81448   regEofA = ++pParse->nMem;
   81449   regAddrB = ++pParse->nMem;
   81450   regEofB = ++pParse->nMem;
   81451   regOutA = ++pParse->nMem;
   81452   regOutB = ++pParse->nMem;
   81453   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
   81454   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
   81455 
   81456   /* Jump past the various subroutines and coroutines to the main
   81457   ** merge loop
   81458   */
   81459   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
   81460   addrSelectA = sqlite3VdbeCurrentAddr(v);
   81461 
   81462 
   81463   /* Generate a coroutine to evaluate the SELECT statement to the
   81464   ** left of the compound operator - the "A" select.
   81465   */
   81466   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
   81467   pPrior->iLimit = regLimitA;
   81468   sqlite3Select(pParse, pPrior, &destA);
   81469   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
   81470   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
   81471   VdbeNoopComment((v, "End coroutine for left SELECT"));
   81472 
   81473   /* Generate a coroutine to evaluate the SELECT statement on
   81474   ** the right - the "B" select
   81475   */
   81476   addrSelectB = sqlite3VdbeCurrentAddr(v);
   81477   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
   81478   savedLimit = p->iLimit;
   81479   savedOffset = p->iOffset;
   81480   p->iLimit = regLimitB;
   81481   p->iOffset = 0;
   81482   sqlite3Select(pParse, p, &destB);
   81483   p->iLimit = savedLimit;
   81484   p->iOffset = savedOffset;
   81485   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
   81486   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
   81487   VdbeNoopComment((v, "End coroutine for right SELECT"));
   81488 
   81489   /* Generate a subroutine that outputs the current row of the A
   81490   ** select as the next output row of the compound select.
   81491   */
   81492   VdbeNoopComment((v, "Output routine for A"));
   81493   addrOutA = generateOutputSubroutine(pParse,
   81494                  p, &destA, pDest, regOutA,
   81495                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
   81496 
   81497   /* Generate a subroutine that outputs the current row of the B
   81498   ** select as the next output row of the compound select.
   81499   */
   81500   if( op==TK_ALL || op==TK_UNION ){
   81501     VdbeNoopComment((v, "Output routine for B"));
   81502     addrOutB = generateOutputSubroutine(pParse,
   81503                  p, &destB, pDest, regOutB,
   81504                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
   81505   }
   81506 
   81507   /* Generate a subroutine to run when the results from select A
   81508   ** are exhausted and only data in select B remains.
   81509   */
   81510   VdbeNoopComment((v, "eof-A subroutine"));
   81511   if( op==TK_EXCEPT || op==TK_INTERSECT ){
   81512     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
   81513   }else{
   81514     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
   81515     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
   81516     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
   81517     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
   81518   }
   81519 
   81520   /* Generate a subroutine to run when the results from select B
   81521   ** are exhausted and only data in select A remains.
   81522   */
   81523   if( op==TK_INTERSECT ){
   81524     addrEofB = addrEofA;
   81525   }else{
   81526     VdbeNoopComment((v, "eof-B subroutine"));
   81527     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
   81528     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
   81529     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
   81530     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
   81531   }
   81532 
   81533   /* Generate code to handle the case of A<B
   81534   */
   81535   VdbeNoopComment((v, "A-lt-B subroutine"));
   81536   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
   81537   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
   81538   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
   81539   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   81540 
   81541   /* Generate code to handle the case of A==B
   81542   */
   81543   if( op==TK_ALL ){
   81544     addrAeqB = addrAltB;
   81545   }else if( op==TK_INTERSECT ){
   81546     addrAeqB = addrAltB;
   81547     addrAltB++;
   81548   }else{
   81549     VdbeNoopComment((v, "A-eq-B subroutine"));
   81550     addrAeqB =
   81551     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
   81552     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
   81553     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   81554   }
   81555 
   81556   /* Generate code to handle the case of A>B
   81557   */
   81558   VdbeNoopComment((v, "A-gt-B subroutine"));
   81559   addrAgtB = sqlite3VdbeCurrentAddr(v);
   81560   if( op==TK_ALL || op==TK_UNION ){
   81561     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
   81562   }
   81563   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
   81564   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
   81565   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   81566 
   81567   /* This code runs once to initialize everything.
   81568   */
   81569   sqlite3VdbeJumpHere(v, j1);
   81570   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
   81571   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
   81572   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
   81573   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
   81574   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
   81575   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
   81576 
   81577   /* Implement the main merge loop
   81578   */
   81579   sqlite3VdbeResolveLabel(v, labelCmpr);
   81580   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
   81581   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
   81582                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
   81583   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
   81584 
   81585   /* Release temporary registers
   81586   */
   81587   if( regPrev ){
   81588     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
   81589   }
   81590 
   81591   /* Jump to the this point in order to terminate the query.
   81592   */
   81593   sqlite3VdbeResolveLabel(v, labelEnd);
   81594 
   81595   /* Set the number of output columns
   81596   */
   81597   if( pDest->eDest==SRT_Output ){
   81598     Select *pFirst = pPrior;
   81599     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   81600     generateColumnNames(pParse, 0, pFirst->pEList);
   81601   }
   81602 
   81603   /* Reassembly the compound query so that it will be freed correctly
   81604   ** by the calling function */
   81605   if( p->pPrior ){
   81606     sqlite3SelectDelete(db, p->pPrior);
   81607   }
   81608   p->pPrior = pPrior;
   81609 
   81610   /*** TBD:  Insert subroutine calls to close cursors on incomplete
   81611   **** subqueries ****/
   81612   return SQLITE_OK;
   81613 }
   81614 #endif
   81615 
   81616 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   81617 /* Forward Declarations */
   81618 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
   81619 static void substSelect(sqlite3*, Select *, int, ExprList *);
   81620 
   81621 /*
   81622 ** Scan through the expression pExpr.  Replace every reference to
   81623 ** a column in table number iTable with a copy of the iColumn-th
   81624 ** entry in pEList.  (But leave references to the ROWID column
   81625 ** unchanged.)
   81626 **
   81627 ** This routine is part of the flattening procedure.  A subquery
   81628 ** whose result set is defined by pEList appears as entry in the
   81629 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
   81630 ** FORM clause entry is iTable.  This routine make the necessary
   81631 ** changes to pExpr so that it refers directly to the source table
   81632 ** of the subquery rather the result set of the subquery.
   81633 */
   81634 static Expr *substExpr(
   81635   sqlite3 *db,        /* Report malloc errors to this connection */
   81636   Expr *pExpr,        /* Expr in which substitution occurs */
   81637   int iTable,         /* Table to be substituted */
   81638   ExprList *pEList    /* Substitute expressions */
   81639 ){
   81640   if( pExpr==0 ) return 0;
   81641   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
   81642     if( pExpr->iColumn<0 ){
   81643       pExpr->op = TK_NULL;
   81644     }else{
   81645       Expr *pNew;
   81646       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
   81647       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
   81648       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
   81649       if( pNew && pExpr->pColl ){
   81650         pNew->pColl = pExpr->pColl;
   81651       }
   81652       sqlite3ExprDelete(db, pExpr);
   81653       pExpr = pNew;
   81654     }
   81655   }else{
   81656     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
   81657     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
   81658     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   81659       substSelect(db, pExpr->x.pSelect, iTable, pEList);
   81660     }else{
   81661       substExprList(db, pExpr->x.pList, iTable, pEList);
   81662     }
   81663   }
   81664   return pExpr;
   81665 }
   81666 static void substExprList(
   81667   sqlite3 *db,         /* Report malloc errors here */
   81668   ExprList *pList,     /* List to scan and in which to make substitutes */
   81669   int iTable,          /* Table to be substituted */
   81670   ExprList *pEList     /* Substitute values */
   81671 ){
   81672   int i;
   81673   if( pList==0 ) return;
   81674   for(i=0; i<pList->nExpr; i++){
   81675     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
   81676   }
   81677 }
   81678 static void substSelect(
   81679   sqlite3 *db,         /* Report malloc errors here */
   81680   Select *p,           /* SELECT statement in which to make substitutions */
   81681   int iTable,          /* Table to be replaced */
   81682   ExprList *pEList     /* Substitute values */
   81683 ){
   81684   SrcList *pSrc;
   81685   struct SrcList_item *pItem;
   81686   int i;
   81687   if( !p ) return;
   81688   substExprList(db, p->pEList, iTable, pEList);
   81689   substExprList(db, p->pGroupBy, iTable, pEList);
   81690   substExprList(db, p->pOrderBy, iTable, pEList);
   81691   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
   81692   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
   81693   substSelect(db, p->pPrior, iTable, pEList);
   81694   pSrc = p->pSrc;
   81695   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
   81696   if( ALWAYS(pSrc) ){
   81697     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
   81698       substSelect(db, pItem->pSelect, iTable, pEList);
   81699     }
   81700   }
   81701 }
   81702 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
   81703 
   81704 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   81705 /*
   81706 ** This routine attempts to flatten subqueries in order to speed
   81707 ** execution.  It returns 1 if it makes changes and 0 if no flattening
   81708 ** occurs.
   81709 **
   81710 ** To understand the concept of flattening, consider the following
   81711 ** query:
   81712 **
   81713 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
   81714 **
   81715 ** The default way of implementing this query is to execute the
   81716 ** subquery first and store the results in a temporary table, then
   81717 ** run the outer query on that temporary table.  This requires two
   81718 ** passes over the data.  Furthermore, because the temporary table
   81719 ** has no indices, the WHERE clause on the outer query cannot be
   81720 ** optimized.
   81721 **
   81722 ** This routine attempts to rewrite queries such as the above into
   81723 ** a single flat select, like this:
   81724 **
   81725 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
   81726 **
   81727 ** The code generated for this simpification gives the same result
   81728 ** but only has to scan the data once.  And because indices might
   81729 ** exist on the table t1, a complete scan of the data might be
   81730 ** avoided.
   81731 **
   81732 ** Flattening is only attempted if all of the following are true:
   81733 **
   81734 **   (1)  The subquery and the outer query do not both use aggregates.
   81735 **
   81736 **   (2)  The subquery is not an aggregate or the outer query is not a join.
   81737 **
   81738 **   (3)  The subquery is not the right operand of a left outer join
   81739 **        (Originally ticket #306.  Strenghtened by ticket #3300)
   81740 **
   81741 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
   81742 **
   81743 **   (5)  The subquery is not DISTINCT or the outer query does not use
   81744 **        aggregates.
   81745 **
   81746 **   (6)  The subquery does not use aggregates or the outer query is not
   81747 **        DISTINCT.
   81748 **
   81749 **   (7)  The subquery has a FROM clause.
   81750 **
   81751 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
   81752 **
   81753 **   (9)  The subquery does not use LIMIT or the outer query does not use
   81754 **        aggregates.
   81755 **
   81756 **  (10)  The subquery does not use aggregates or the outer query does not
   81757 **        use LIMIT.
   81758 **
   81759 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
   81760 **
   81761 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
   81762 **        a separate restriction deriving from ticket #350.
   81763 **
   81764 **  (13)  The subquery and outer query do not both use LIMIT
   81765 **
   81766 **  (14)  The subquery does not use OFFSET
   81767 **
   81768 **  (15)  The outer query is not part of a compound select or the
   81769 **        subquery does not have both an ORDER BY and a LIMIT clause.
   81770 **        (See ticket #2339)
   81771 **
   81772 **  (16)  The outer query is not an aggregate or the subquery does
   81773 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
   81774 **        until we introduced the group_concat() function.
   81775 **
   81776 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
   81777 **        compound clause made up entirely of non-aggregate queries, and
   81778 **        the parent query:
   81779 **
   81780 **          * is not itself part of a compound select,
   81781 **          * is not an aggregate or DISTINCT query, and
   81782 **          * has no other tables or sub-selects in the FROM clause.
   81783 **
   81784 **        The parent and sub-query may contain WHERE clauses. Subject to
   81785 **        rules (11), (13) and (14), they may also contain ORDER BY,
   81786 **        LIMIT and OFFSET clauses.
   81787 **
   81788 **  (18)  If the sub-query is a compound select, then all terms of the
   81789 **        ORDER by clause of the parent must be simple references to
   81790 **        columns of the sub-query.
   81791 **
   81792 **  (19)  The subquery does not use LIMIT or the outer query does not
   81793 **        have a WHERE clause.
   81794 **
   81795 **  (20)  If the sub-query is a compound select, then it must not use
   81796 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
   81797 **        somewhat by saying that the terms of the ORDER BY clause must
   81798 **        appear as unmodified result columns in the outer query.  But
   81799 **        have other optimizations in mind to deal with that case.
   81800 **
   81801 ** In this routine, the "p" parameter is a pointer to the outer query.
   81802 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
   81803 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
   81804 **
   81805 ** If flattening is not attempted, this routine is a no-op and returns 0.
   81806 ** If flattening is attempted this routine returns 1.
   81807 **
   81808 ** All of the expression analysis must occur on both the outer query and
   81809 ** the subquery before this routine runs.
   81810 */
   81811 static int flattenSubquery(
   81812   Parse *pParse,       /* Parsing context */
   81813   Select *p,           /* The parent or outer SELECT statement */
   81814   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
   81815   int isAgg,           /* True if outer SELECT uses aggregate functions */
   81816   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
   81817 ){
   81818   const char *zSavedAuthContext = pParse->zAuthContext;
   81819   Select *pParent;
   81820   Select *pSub;       /* The inner query or "subquery" */
   81821   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
   81822   SrcList *pSrc;      /* The FROM clause of the outer query */
   81823   SrcList *pSubSrc;   /* The FROM clause of the subquery */
   81824   ExprList *pList;    /* The result set of the outer query */
   81825   int iParent;        /* VDBE cursor number of the pSub result set temp table */
   81826   int i;              /* Loop counter */
   81827   Expr *pWhere;                    /* The WHERE clause */
   81828   struct SrcList_item *pSubitem;   /* The subquery */
   81829   sqlite3 *db = pParse->db;
   81830 
   81831   /* Check to see if flattening is permitted.  Return 0 if not.
   81832   */
   81833   assert( p!=0 );
   81834   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
   81835   if( db->flags & SQLITE_QueryFlattener ) return 0;
   81836   pSrc = p->pSrc;
   81837   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
   81838   pSubitem = &pSrc->a[iFrom];
   81839   iParent = pSubitem->iCursor;
   81840   pSub = pSubitem->pSelect;
   81841   assert( pSub!=0 );
   81842   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
   81843   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
   81844   pSubSrc = pSub->pSrc;
   81845   assert( pSubSrc );
   81846   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
   81847   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
   81848   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
   81849   ** became arbitrary expressions, we were forced to add restrictions (13)
   81850   ** and (14). */
   81851   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
   81852   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
   81853   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
   81854     return 0;                                            /* Restriction (15) */
   81855   }
   81856   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
   81857   if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit)
   81858          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
   81859      return 0;
   81860   }
   81861   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
   81862      return 0;         /* Restriction (6)  */
   81863   }
   81864   if( p->pOrderBy && pSub->pOrderBy ){
   81865      return 0;                                           /* Restriction (11) */
   81866   }
   81867   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
   81868   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
   81869 
   81870   /* OBSOLETE COMMENT 1:
   81871   ** Restriction 3:  If the subquery is a join, make sure the subquery is
   81872   ** not used as the right operand of an outer join.  Examples of why this
   81873   ** is not allowed:
   81874   **
   81875   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
   81876   **
   81877   ** If we flatten the above, we would get
   81878   **
   81879   **         (t1 LEFT OUTER JOIN t2) JOIN t3
   81880   **
   81881   ** which is not at all the same thing.
   81882   **
   81883   ** OBSOLETE COMMENT 2:
   81884   ** Restriction 12:  If the subquery is the right operand of a left outer
   81885   ** join, make sure the subquery has no WHERE clause.
   81886   ** An examples of why this is not allowed:
   81887   **
   81888   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
   81889   **
   81890   ** If we flatten the above, we would get
   81891   **
   81892   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
   81893   **
   81894   ** But the t2.x>0 test will always fail on a NULL row of t2, which
   81895   ** effectively converts the OUTER JOIN into an INNER JOIN.
   81896   **
   81897   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
   81898   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
   81899   ** is fraught with danger.  Best to avoid the whole thing.  If the
   81900   ** subquery is the right term of a LEFT JOIN, then do not flatten.
   81901   */
   81902   if( (pSubitem->jointype & JT_OUTER)!=0 ){
   81903     return 0;
   81904   }
   81905 
   81906   /* Restriction 17: If the sub-query is a compound SELECT, then it must
   81907   ** use only the UNION ALL operator. And none of the simple select queries
   81908   ** that make up the compound SELECT are allowed to be aggregate or distinct
   81909   ** queries.
   81910   */
   81911   if( pSub->pPrior ){
   81912     if( pSub->pOrderBy ){
   81913       return 0;  /* Restriction 20 */
   81914     }
   81915     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
   81916       return 0;
   81917     }
   81918     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
   81919       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
   81920       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
   81921       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
   81922        || (pSub1->pPrior && pSub1->op!=TK_ALL)
   81923        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
   81924       ){
   81925         return 0;
   81926       }
   81927     }
   81928 
   81929     /* Restriction 18. */
   81930     if( p->pOrderBy ){
   81931       int ii;
   81932       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
   81933         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
   81934       }
   81935     }
   81936   }
   81937 
   81938   /***** If we reach this point, flattening is permitted. *****/
   81939 
   81940   /* Authorize the subquery */
   81941   pParse->zAuthContext = pSubitem->zName;
   81942   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
   81943   pParse->zAuthContext = zSavedAuthContext;
   81944 
   81945   /* If the sub-query is a compound SELECT statement, then (by restrictions
   81946   ** 17 and 18 above) it must be a UNION ALL and the parent query must
   81947   ** be of the form:
   81948   **
   81949   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
   81950   **
   81951   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
   81952   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
   81953   ** OFFSET clauses and joins them to the left-hand-side of the original
   81954   ** using UNION ALL operators. In this case N is the number of simple
   81955   ** select statements in the compound sub-query.
   81956   **
   81957   ** Example:
   81958   **
   81959   **     SELECT a+1 FROM (
   81960   **        SELECT x FROM tab
   81961   **        UNION ALL
   81962   **        SELECT y FROM tab
   81963   **        UNION ALL
   81964   **        SELECT abs(z*2) FROM tab2
   81965   **     ) WHERE a!=5 ORDER BY 1
   81966   **
   81967   ** Transformed into:
   81968   **
   81969   **     SELECT x+1 FROM tab WHERE x+1!=5
   81970   **     UNION ALL
   81971   **     SELECT y+1 FROM tab WHERE y+1!=5
   81972   **     UNION ALL
   81973   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
   81974   **     ORDER BY 1
   81975   **
   81976   ** We call this the "compound-subquery flattening".
   81977   */
   81978   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
   81979     Select *pNew;
   81980     ExprList *pOrderBy = p->pOrderBy;
   81981     Expr *pLimit = p->pLimit;
   81982     Select *pPrior = p->pPrior;
   81983     p->pOrderBy = 0;
   81984     p->pSrc = 0;
   81985     p->pPrior = 0;
   81986     p->pLimit = 0;
   81987     pNew = sqlite3SelectDup(db, p, 0);
   81988     p->pLimit = pLimit;
   81989     p->pOrderBy = pOrderBy;
   81990     p->pSrc = pSrc;
   81991     p->op = TK_ALL;
   81992     p->pRightmost = 0;
   81993     if( pNew==0 ){
   81994       pNew = pPrior;
   81995     }else{
   81996       pNew->pPrior = pPrior;
   81997       pNew->pRightmost = 0;
   81998     }
   81999     p->pPrior = pNew;
   82000     if( db->mallocFailed ) return 1;
   82001   }
   82002 
   82003   /* Begin flattening the iFrom-th entry of the FROM clause
   82004   ** in the outer query.
   82005   */
   82006   pSub = pSub1 = pSubitem->pSelect;
   82007 
   82008   /* Delete the transient table structure associated with the
   82009   ** subquery
   82010   */
   82011   sqlite3DbFree(db, pSubitem->zDatabase);
   82012   sqlite3DbFree(db, pSubitem->zName);
   82013   sqlite3DbFree(db, pSubitem->zAlias);
   82014   pSubitem->zDatabase = 0;
   82015   pSubitem->zName = 0;
   82016   pSubitem->zAlias = 0;
   82017   pSubitem->pSelect = 0;
   82018 
   82019   /* Defer deleting the Table object associated with the
   82020   ** subquery until code generation is
   82021   ** complete, since there may still exist Expr.pTab entries that
   82022   ** refer to the subquery even after flattening.  Ticket #3346.
   82023   **
   82024   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
   82025   */
   82026   if( ALWAYS(pSubitem->pTab!=0) ){
   82027     Table *pTabToDel = pSubitem->pTab;
   82028     if( pTabToDel->nRef==1 ){
   82029       Parse *pToplevel = sqlite3ParseToplevel(pParse);
   82030       pTabToDel->pNextZombie = pToplevel->pZombieTab;
   82031       pToplevel->pZombieTab = pTabToDel;
   82032     }else{
   82033       pTabToDel->nRef--;
   82034     }
   82035     pSubitem->pTab = 0;
   82036   }
   82037 
   82038   /* The following loop runs once for each term in a compound-subquery
   82039   ** flattening (as described above).  If we are doing a different kind
   82040   ** of flattening - a flattening other than a compound-subquery flattening -
   82041   ** then this loop only runs once.
   82042   **
   82043   ** This loop moves all of the FROM elements of the subquery into the
   82044   ** the FROM clause of the outer query.  Before doing this, remember
   82045   ** the cursor number for the original outer query FROM element in
   82046   ** iParent.  The iParent cursor will never be used.  Subsequent code
   82047   ** will scan expressions looking for iParent references and replace
   82048   ** those references with expressions that resolve to the subquery FROM
   82049   ** elements we are now copying in.
   82050   */
   82051   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
   82052     int nSubSrc;
   82053     u8 jointype = 0;
   82054     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
   82055     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
   82056     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
   82057 
   82058     if( pSrc ){
   82059       assert( pParent==p );  /* First time through the loop */
   82060       jointype = pSubitem->jointype;
   82061     }else{
   82062       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
   82063       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   82064       if( pSrc==0 ){
   82065         assert( db->mallocFailed );
   82066         break;
   82067       }
   82068     }
   82069 
   82070     /* The subquery uses a single slot of the FROM clause of the outer
   82071     ** query.  If the subquery has more than one element in its FROM clause,
   82072     ** then expand the outer query to make space for it to hold all elements
   82073     ** of the subquery.
   82074     **
   82075     ** Example:
   82076     **
   82077     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
   82078     **
   82079     ** The outer query has 3 slots in its FROM clause.  One slot of the
   82080     ** outer query (the middle slot) is used by the subquery.  The next
   82081     ** block of code will expand the out query to 4 slots.  The middle
   82082     ** slot is expanded to two slots in order to make space for the
   82083     ** two elements in the FROM clause of the subquery.
   82084     */
   82085     if( nSubSrc>1 ){
   82086       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
   82087       if( db->mallocFailed ){
   82088         break;
   82089       }
   82090     }
   82091 
   82092     /* Transfer the FROM clause terms from the subquery into the
   82093     ** outer query.
   82094     */
   82095     for(i=0; i<nSubSrc; i++){
   82096       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
   82097       pSrc->a[i+iFrom] = pSubSrc->a[i];
   82098       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
   82099     }
   82100     pSrc->a[iFrom].jointype = jointype;
   82101 
   82102     /* Now begin substituting subquery result set expressions for
   82103     ** references to the iParent in the outer query.
   82104     **
   82105     ** Example:
   82106     **
   82107     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
   82108     **   \                     \_____________ subquery __________/          /
   82109     **    \_____________________ outer query ______________________________/
   82110     **
   82111     ** We look at every expression in the outer query and every place we see
   82112     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
   82113     */
   82114     pList = pParent->pEList;
   82115     for(i=0; i<pList->nExpr; i++){
   82116       if( pList->a[i].zName==0 ){
   82117         const char *zSpan = pList->a[i].zSpan;
   82118         if( ALWAYS(zSpan) ){
   82119           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
   82120         }
   82121       }
   82122     }
   82123     substExprList(db, pParent->pEList, iParent, pSub->pEList);
   82124     if( isAgg ){
   82125       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
   82126       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
   82127     }
   82128     if( pSub->pOrderBy ){
   82129       assert( pParent->pOrderBy==0 );
   82130       pParent->pOrderBy = pSub->pOrderBy;
   82131       pSub->pOrderBy = 0;
   82132     }else if( pParent->pOrderBy ){
   82133       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
   82134     }
   82135     if( pSub->pWhere ){
   82136       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
   82137     }else{
   82138       pWhere = 0;
   82139     }
   82140     if( subqueryIsAgg ){
   82141       assert( pParent->pHaving==0 );
   82142       pParent->pHaving = pParent->pWhere;
   82143       pParent->pWhere = pWhere;
   82144       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
   82145       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
   82146                                   sqlite3ExprDup(db, pSub->pHaving, 0));
   82147       assert( pParent->pGroupBy==0 );
   82148       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
   82149     }else{
   82150       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
   82151       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
   82152     }
   82153 
   82154     /* The flattened query is distinct if either the inner or the
   82155     ** outer query is distinct.
   82156     */
   82157     pParent->selFlags |= pSub->selFlags & SF_Distinct;
   82158 
   82159     /*
   82160     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
   82161     **
   82162     ** One is tempted to try to add a and b to combine the limits.  But this
   82163     ** does not work if either limit is negative.
   82164     */
   82165     if( pSub->pLimit ){
   82166       pParent->pLimit = pSub->pLimit;
   82167       pSub->pLimit = 0;
   82168     }
   82169   }
   82170 
   82171   /* Finially, delete what is left of the subquery and return
   82172   ** success.
   82173   */
   82174   sqlite3SelectDelete(db, pSub1);
   82175 
   82176   return 1;
   82177 }
   82178 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
   82179 
   82180 /*
   82181 ** Analyze the SELECT statement passed as an argument to see if it
   82182 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
   82183 ** it is, or 0 otherwise. At present, a query is considered to be
   82184 ** a min()/max() query if:
   82185 **
   82186 **   1. There is a single object in the FROM clause.
   82187 **
   82188 **   2. There is a single expression in the result set, and it is
   82189 **      either min(x) or max(x), where x is a column reference.
   82190 */
   82191 static u8 minMaxQuery(Select *p){
   82192   Expr *pExpr;
   82193   ExprList *pEList = p->pEList;
   82194 
   82195   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
   82196   pExpr = pEList->a[0].pExpr;
   82197   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
   82198   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
   82199   pEList = pExpr->x.pList;
   82200   if( pEList==0 || pEList->nExpr!=1 ) return 0;
   82201   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
   82202   assert( !ExprHasProperty(pExpr, EP_IntValue) );
   82203   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
   82204     return WHERE_ORDERBY_MIN;
   82205   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
   82206     return WHERE_ORDERBY_MAX;
   82207   }
   82208   return WHERE_ORDERBY_NORMAL;
   82209 }
   82210 
   82211 /*
   82212 ** The select statement passed as the first argument is an aggregate query.
   82213 ** The second argment is the associated aggregate-info object. This
   82214 ** function tests if the SELECT is of the form:
   82215 **
   82216 **   SELECT count(*) FROM <tbl>
   82217 **
   82218 ** where table is a database table, not a sub-select or view. If the query
   82219 ** does match this pattern, then a pointer to the Table object representing
   82220 ** <tbl> is returned. Otherwise, 0 is returned.
   82221 */
   82222 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
   82223   Table *pTab;
   82224   Expr *pExpr;
   82225 
   82226   assert( !p->pGroupBy );
   82227 
   82228   if( p->pWhere || p->pEList->nExpr!=1
   82229    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
   82230   ){
   82231     return 0;
   82232   }
   82233   pTab = p->pSrc->a[0].pTab;
   82234   pExpr = p->pEList->a[0].pExpr;
   82235   assert( pTab && !pTab->pSelect && pExpr );
   82236 
   82237   if( IsVirtual(pTab) ) return 0;
   82238   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
   82239   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
   82240   if( pExpr->flags&EP_Distinct ) return 0;
   82241 
   82242   return pTab;
   82243 }
   82244 
   82245 /*
   82246 ** If the source-list item passed as an argument was augmented with an
   82247 ** INDEXED BY clause, then try to locate the specified index. If there
   82248 ** was such a clause and the named index cannot be found, return
   82249 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
   82250 ** pFrom->pIndex and return SQLITE_OK.
   82251 */
   82252 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
   82253   if( pFrom->pTab && pFrom->zIndex ){
   82254     Table *pTab = pFrom->pTab;
   82255     char *zIndex = pFrom->zIndex;
   82256     Index *pIdx;
   82257     for(pIdx=pTab->pIndex;
   82258         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
   82259         pIdx=pIdx->pNext
   82260     );
   82261     if( !pIdx ){
   82262       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
   82263       return SQLITE_ERROR;
   82264     }
   82265     pFrom->pIndex = pIdx;
   82266   }
   82267   return SQLITE_OK;
   82268 }
   82269 
   82270 /*
   82271 ** This routine is a Walker callback for "expanding" a SELECT statement.
   82272 ** "Expanding" means to do the following:
   82273 **
   82274 **    (1)  Make sure VDBE cursor numbers have been assigned to every
   82275 **         element of the FROM clause.
   82276 **
   82277 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
   82278 **         defines FROM clause.  When views appear in the FROM clause,
   82279 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
   82280 **         that implements the view.  A copy is made of the view's SELECT
   82281 **         statement so that we can freely modify or delete that statement
   82282 **         without worrying about messing up the presistent representation
   82283 **         of the view.
   82284 **
   82285 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
   82286 **         on joins and the ON and USING clause of joins.
   82287 **
   82288 **    (4)  Scan the list of columns in the result set (pEList) looking
   82289 **         for instances of the "*" operator or the TABLE.* operator.
   82290 **         If found, expand each "*" to be every column in every table
   82291 **         and TABLE.* to be every column in TABLE.
   82292 **
   82293 */
   82294 static int selectExpander(Walker *pWalker, Select *p){
   82295   Parse *pParse = pWalker->pParse;
   82296   int i, j, k;
   82297   SrcList *pTabList;
   82298   ExprList *pEList;
   82299   struct SrcList_item *pFrom;
   82300   sqlite3 *db = pParse->db;
   82301 
   82302   if( db->mallocFailed  ){
   82303     return WRC_Abort;
   82304   }
   82305   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
   82306     return WRC_Prune;
   82307   }
   82308   p->selFlags |= SF_Expanded;
   82309   pTabList = p->pSrc;
   82310   pEList = p->pEList;
   82311 
   82312   /* Make sure cursor numbers have been assigned to all entries in
   82313   ** the FROM clause of the SELECT statement.
   82314   */
   82315   sqlite3SrcListAssignCursors(pParse, pTabList);
   82316 
   82317   /* Look up every table named in the FROM clause of the select.  If
   82318   ** an entry of the FROM clause is a subquery instead of a table or view,
   82319   ** then create a transient table structure to describe the subquery.
   82320   */
   82321   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   82322     Table *pTab;
   82323     if( pFrom->pTab!=0 ){
   82324       /* This statement has already been prepared.  There is no need
   82325       ** to go further. */
   82326       assert( i==0 );
   82327       return WRC_Prune;
   82328     }
   82329     if( pFrom->zName==0 ){
   82330 #ifndef SQLITE_OMIT_SUBQUERY
   82331       Select *pSel = pFrom->pSelect;
   82332       /* A sub-query in the FROM clause of a SELECT */
   82333       assert( pSel!=0 );
   82334       assert( pFrom->pTab==0 );
   82335       sqlite3WalkSelect(pWalker, pSel);
   82336       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
   82337       if( pTab==0 ) return WRC_Abort;
   82338       pTab->dbMem = db->lookaside.bEnabled ? db : 0;
   82339       pTab->nRef = 1;
   82340       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
   82341       while( pSel->pPrior ){ pSel = pSel->pPrior; }
   82342       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
   82343       pTab->iPKey = -1;
   82344       pTab->tabFlags |= TF_Ephemeral;
   82345 #endif
   82346     }else{
   82347       /* An ordinary table or view name in the FROM clause */
   82348       assert( pFrom->pTab==0 );
   82349       pFrom->pTab = pTab =
   82350         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
   82351       if( pTab==0 ) return WRC_Abort;
   82352       pTab->nRef++;
   82353 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
   82354       if( pTab->pSelect || IsVirtual(pTab) ){
   82355         /* We reach here if the named table is a really a view */
   82356         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
   82357         assert( pFrom->pSelect==0 );
   82358         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
   82359         sqlite3WalkSelect(pWalker, pFrom->pSelect);
   82360       }
   82361 #endif
   82362     }
   82363 
   82364     /* Locate the index named by the INDEXED BY clause, if any. */
   82365     if( sqlite3IndexedByLookup(pParse, pFrom) ){
   82366       return WRC_Abort;
   82367     }
   82368   }
   82369 
   82370   /* Process NATURAL keywords, and ON and USING clauses of joins.
   82371   */
   82372   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
   82373     return WRC_Abort;
   82374   }
   82375 
   82376   /* For every "*" that occurs in the column list, insert the names of
   82377   ** all columns in all tables.  And for every TABLE.* insert the names
   82378   ** of all columns in TABLE.  The parser inserted a special expression
   82379   ** with the TK_ALL operator for each "*" that it found in the column list.
   82380   ** The following code just has to locate the TK_ALL expressions and expand
   82381   ** each one to the list of all columns in all tables.
   82382   **
   82383   ** The first loop just checks to see if there are any "*" operators
   82384   ** that need expanding.
   82385   */
   82386   for(k=0; k<pEList->nExpr; k++){
   82387     Expr *pE = pEList->a[k].pExpr;
   82388     if( pE->op==TK_ALL ) break;
   82389     assert( pE->op!=TK_DOT || pE->pRight!=0 );
   82390     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
   82391     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
   82392   }
   82393   if( k<pEList->nExpr ){
   82394     /*
   82395     ** If we get here it means the result set contains one or more "*"
   82396     ** operators that need to be expanded.  Loop through each expression
   82397     ** in the result set and expand them one by one.
   82398     */
   82399     struct ExprList_item *a = pEList->a;
   82400     ExprList *pNew = 0;
   82401     int flags = pParse->db->flags;
   82402     int longNames = (flags & SQLITE_FullColNames)!=0
   82403                       && (flags & SQLITE_ShortColNames)==0;
   82404 
   82405     for(k=0; k<pEList->nExpr; k++){
   82406       Expr *pE = a[k].pExpr;
   82407       assert( pE->op!=TK_DOT || pE->pRight!=0 );
   82408       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
   82409         /* This particular expression does not need to be expanded.
   82410         */
   82411         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
   82412         if( pNew ){
   82413           pNew->a[pNew->nExpr-1].zName = a[k].zName;
   82414           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
   82415           a[k].zName = 0;
   82416           a[k].zSpan = 0;
   82417         }
   82418         a[k].pExpr = 0;
   82419       }else{
   82420         /* This expression is a "*" or a "TABLE.*" and needs to be
   82421         ** expanded. */
   82422         int tableSeen = 0;      /* Set to 1 when TABLE matches */
   82423         char *zTName;            /* text of name of TABLE */
   82424         if( pE->op==TK_DOT ){
   82425           assert( pE->pLeft!=0 );
   82426           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
   82427           zTName = pE->pLeft->u.zToken;
   82428         }else{
   82429           zTName = 0;
   82430         }
   82431         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   82432           Table *pTab = pFrom->pTab;
   82433           char *zTabName = pFrom->zAlias;
   82434           if( zTabName==0 ){
   82435             zTabName = pTab->zName;
   82436           }
   82437           if( db->mallocFailed ) break;
   82438           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
   82439             continue;
   82440           }
   82441           tableSeen = 1;
   82442           for(j=0; j<pTab->nCol; j++){
   82443             Expr *pExpr, *pRight;
   82444             char *zName = pTab->aCol[j].zName;
   82445             char *zColname;  /* The computed column name */
   82446             char *zToFree;   /* Malloced string that needs to be freed */
   82447             Token sColname;  /* Computed column name as a token */
   82448 
   82449             /* If a column is marked as 'hidden' (currently only possible
   82450             ** for virtual tables), do not include it in the expanded
   82451             ** result-set list.
   82452             */
   82453             if( IsHiddenColumn(&pTab->aCol[j]) ){
   82454               assert(IsVirtual(pTab));
   82455               continue;
   82456             }
   82457 
   82458             if( i>0 && zTName==0 ){
   82459               if( (pFrom->jointype & JT_NATURAL)!=0
   82460                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
   82461               ){
   82462                 /* In a NATURAL join, omit the join columns from the
   82463                 ** table to the right of the join */
   82464                 continue;
   82465               }
   82466               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
   82467                 /* In a join with a USING clause, omit columns in the
   82468                 ** using clause from the table on the right. */
   82469                 continue;
   82470               }
   82471             }
   82472             pRight = sqlite3Expr(db, TK_ID, zName);
   82473             zColname = zName;
   82474             zToFree = 0;
   82475             if( longNames || pTabList->nSrc>1 ){
   82476               Expr *pLeft;
   82477               pLeft = sqlite3Expr(db, TK_ID, zTabName);
   82478               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
   82479               if( longNames ){
   82480                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
   82481                 zToFree = zColname;
   82482               }
   82483             }else{
   82484               pExpr = pRight;
   82485             }
   82486             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
   82487             sColname.z = zColname;
   82488             sColname.n = sqlite3Strlen30(zColname);
   82489             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
   82490             sqlite3DbFree(db, zToFree);
   82491           }
   82492         }
   82493         if( !tableSeen ){
   82494           if( zTName ){
   82495             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
   82496           }else{
   82497             sqlite3ErrorMsg(pParse, "no tables specified");
   82498           }
   82499         }
   82500       }
   82501     }
   82502     sqlite3ExprListDelete(db, pEList);
   82503     p->pEList = pNew;
   82504   }
   82505 #if SQLITE_MAX_COLUMN
   82506   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   82507     sqlite3ErrorMsg(pParse, "too many columns in result set");
   82508   }
   82509 #endif
   82510   return WRC_Continue;
   82511 }
   82512 
   82513 /*
   82514 ** No-op routine for the parse-tree walker.
   82515 **
   82516 ** When this routine is the Walker.xExprCallback then expression trees
   82517 ** are walked without any actions being taken at each node.  Presumably,
   82518 ** when this routine is used for Walker.xExprCallback then
   82519 ** Walker.xSelectCallback is set to do something useful for every
   82520 ** subquery in the parser tree.
   82521 */
   82522 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
   82523   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   82524   return WRC_Continue;
   82525 }
   82526 
   82527 /*
   82528 ** This routine "expands" a SELECT statement and all of its subqueries.
   82529 ** For additional information on what it means to "expand" a SELECT
   82530 ** statement, see the comment on the selectExpand worker callback above.
   82531 **
   82532 ** Expanding a SELECT statement is the first step in processing a
   82533 ** SELECT statement.  The SELECT statement must be expanded before
   82534 ** name resolution is performed.
   82535 **
   82536 ** If anything goes wrong, an error message is written into pParse.
   82537 ** The calling function can detect the problem by looking at pParse->nErr
   82538 ** and/or pParse->db->mallocFailed.
   82539 */
   82540 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
   82541   Walker w;
   82542   w.xSelectCallback = selectExpander;
   82543   w.xExprCallback = exprWalkNoop;
   82544   w.pParse = pParse;
   82545   sqlite3WalkSelect(&w, pSelect);
   82546 }
   82547 
   82548 
   82549 #ifndef SQLITE_OMIT_SUBQUERY
   82550 /*
   82551 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
   82552 ** interface.
   82553 **
   82554 ** For each FROM-clause subquery, add Column.zType and Column.zColl
   82555 ** information to the Table structure that represents the result set
   82556 ** of that subquery.
   82557 **
   82558 ** The Table structure that represents the result set was constructed
   82559 ** by selectExpander() but the type and collation information was omitted
   82560 ** at that point because identifiers had not yet been resolved.  This
   82561 ** routine is called after identifier resolution.
   82562 */
   82563 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
   82564   Parse *pParse;
   82565   int i;
   82566   SrcList *pTabList;
   82567   struct SrcList_item *pFrom;
   82568 
   82569   assert( p->selFlags & SF_Resolved );
   82570   assert( (p->selFlags & SF_HasTypeInfo)==0 );
   82571   p->selFlags |= SF_HasTypeInfo;
   82572   pParse = pWalker->pParse;
   82573   pTabList = p->pSrc;
   82574   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   82575     Table *pTab = pFrom->pTab;
   82576     if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
   82577       /* A sub-query in the FROM clause of a SELECT */
   82578       Select *pSel = pFrom->pSelect;
   82579       assert( pSel );
   82580       while( pSel->pPrior ) pSel = pSel->pPrior;
   82581       selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
   82582     }
   82583   }
   82584   return WRC_Continue;
   82585 }
   82586 #endif
   82587 
   82588 
   82589 /*
   82590 ** This routine adds datatype and collating sequence information to
   82591 ** the Table structures of all FROM-clause subqueries in a
   82592 ** SELECT statement.
   82593 **
   82594 ** Use this routine after name resolution.
   82595 */
   82596 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
   82597 #ifndef SQLITE_OMIT_SUBQUERY
   82598   Walker w;
   82599   w.xSelectCallback = selectAddSubqueryTypeInfo;
   82600   w.xExprCallback = exprWalkNoop;
   82601   w.pParse = pParse;
   82602   sqlite3WalkSelect(&w, pSelect);
   82603 #endif
   82604 }
   82605 
   82606 
   82607 /*
   82608 ** This routine sets of a SELECT statement for processing.  The
   82609 ** following is accomplished:
   82610 **
   82611 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
   82612 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
   82613 **     *  ON and USING clauses are shifted into WHERE statements
   82614 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
   82615 **     *  Identifiers in expression are matched to tables.
   82616 **
   82617 ** This routine acts recursively on all subqueries within the SELECT.
   82618 */
   82619 SQLITE_PRIVATE void sqlite3SelectPrep(
   82620   Parse *pParse,         /* The parser context */
   82621   Select *p,             /* The SELECT statement being coded. */
   82622   NameContext *pOuterNC  /* Name context for container */
   82623 ){
   82624   sqlite3 *db;
   82625   if( NEVER(p==0) ) return;
   82626   db = pParse->db;
   82627   if( p->selFlags & SF_HasTypeInfo ) return;
   82628   sqlite3SelectExpand(pParse, p);
   82629   if( pParse->nErr || db->mallocFailed ) return;
   82630   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
   82631   if( pParse->nErr || db->mallocFailed ) return;
   82632   sqlite3SelectAddTypeInfo(pParse, p);
   82633 }
   82634 
   82635 /*
   82636 ** Reset the aggregate accumulator.
   82637 **
   82638 ** The aggregate accumulator is a set of memory cells that hold
   82639 ** intermediate results while calculating an aggregate.  This
   82640 ** routine simply stores NULLs in all of those memory cells.
   82641 */
   82642 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
   82643   Vdbe *v = pParse->pVdbe;
   82644   int i;
   82645   struct AggInfo_func *pFunc;
   82646   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
   82647     return;
   82648   }
   82649   for(i=0; i<pAggInfo->nColumn; i++){
   82650     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
   82651   }
   82652   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
   82653     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
   82654     if( pFunc->iDistinct>=0 ){
   82655       Expr *pE = pFunc->pExpr;
   82656       assert( !ExprHasProperty(pE, EP_xIsSelect) );
   82657       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
   82658         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
   82659            "argument");
   82660         pFunc->iDistinct = -1;
   82661       }else{
   82662         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
   82663         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
   82664                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
   82665       }
   82666     }
   82667   }
   82668 }
   82669 
   82670 /*
   82671 ** Invoke the OP_AggFinalize opcode for every aggregate function
   82672 ** in the AggInfo structure.
   82673 */
   82674 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
   82675   Vdbe *v = pParse->pVdbe;
   82676   int i;
   82677   struct AggInfo_func *pF;
   82678   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
   82679     ExprList *pList = pF->pExpr->x.pList;
   82680     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
   82681     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
   82682                       (void*)pF->pFunc, P4_FUNCDEF);
   82683   }
   82684 }
   82685 
   82686 /*
   82687 ** Update the accumulator memory cells for an aggregate based on
   82688 ** the current cursor position.
   82689 */
   82690 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
   82691   Vdbe *v = pParse->pVdbe;
   82692   int i;
   82693   struct AggInfo_func *pF;
   82694   struct AggInfo_col *pC;
   82695 
   82696   pAggInfo->directMode = 1;
   82697   sqlite3ExprCacheClear(pParse);
   82698   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
   82699     int nArg;
   82700     int addrNext = 0;
   82701     int regAgg;
   82702     ExprList *pList = pF->pExpr->x.pList;
   82703     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
   82704     if( pList ){
   82705       nArg = pList->nExpr;
   82706       regAgg = sqlite3GetTempRange(pParse, nArg);
   82707       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
   82708     }else{
   82709       nArg = 0;
   82710       regAgg = 0;
   82711     }
   82712     if( pF->iDistinct>=0 ){
   82713       addrNext = sqlite3VdbeMakeLabel(v);
   82714       assert( nArg==1 );
   82715       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
   82716     }
   82717     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
   82718       CollSeq *pColl = 0;
   82719       struct ExprList_item *pItem;
   82720       int j;
   82721       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
   82722       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
   82723         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
   82724       }
   82725       if( !pColl ){
   82726         pColl = pParse->db->pDfltColl;
   82727       }
   82728       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
   82729     }
   82730     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
   82731                       (void*)pF->pFunc, P4_FUNCDEF);
   82732     sqlite3VdbeChangeP5(v, (u8)nArg);
   82733     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
   82734     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
   82735     if( addrNext ){
   82736       sqlite3VdbeResolveLabel(v, addrNext);
   82737       sqlite3ExprCacheClear(pParse);
   82738     }
   82739   }
   82740   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
   82741     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
   82742   }
   82743   pAggInfo->directMode = 0;
   82744   sqlite3ExprCacheClear(pParse);
   82745 }
   82746 
   82747 /*
   82748 ** Generate code for the SELECT statement given in the p argument.
   82749 **
   82750 ** The results are distributed in various ways depending on the
   82751 ** contents of the SelectDest structure pointed to by argument pDest
   82752 ** as follows:
   82753 **
   82754 **     pDest->eDest    Result
   82755 **     ------------    -------------------------------------------
   82756 **     SRT_Output      Generate a row of output (using the OP_ResultRow
   82757 **                     opcode) for each row in the result set.
   82758 **
   82759 **     SRT_Mem         Only valid if the result is a single column.
   82760 **                     Store the first column of the first result row
   82761 **                     in register pDest->iParm then abandon the rest
   82762 **                     of the query.  This destination implies "LIMIT 1".
   82763 **
   82764 **     SRT_Set         The result must be a single column.  Store each
   82765 **                     row of result as the key in table pDest->iParm.
   82766 **                     Apply the affinity pDest->affinity before storing
   82767 **                     results.  Used to implement "IN (SELECT ...)".
   82768 **
   82769 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
   82770 **
   82771 **     SRT_Except      Remove results from the temporary table pDest->iParm.
   82772 **
   82773 **     SRT_Table       Store results in temporary table pDest->iParm.
   82774 **                     This is like SRT_EphemTab except that the table
   82775 **                     is assumed to already be open.
   82776 **
   82777 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
   82778 **                     the result there. The cursor is left open after
   82779 **                     returning.  This is like SRT_Table except that
   82780 **                     this destination uses OP_OpenEphemeral to create
   82781 **                     the table first.
   82782 **
   82783 **     SRT_Coroutine   Generate a co-routine that returns a new row of
   82784 **                     results each time it is invoked.  The entry point
   82785 **                     of the co-routine is stored in register pDest->iParm.
   82786 **
   82787 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
   82788 **                     set is not empty.
   82789 **
   82790 **     SRT_Discard     Throw the results away.  This is used by SELECT
   82791 **                     statements within triggers whose only purpose is
   82792 **                     the side-effects of functions.
   82793 **
   82794 ** This routine returns the number of errors.  If any errors are
   82795 ** encountered, then an appropriate error message is left in
   82796 ** pParse->zErrMsg.
   82797 **
   82798 ** This routine does NOT free the Select structure passed in.  The
   82799 ** calling function needs to do that.
   82800 */
   82801 SQLITE_PRIVATE int sqlite3Select(
   82802   Parse *pParse,         /* The parser context */
   82803   Select *p,             /* The SELECT statement being coded. */
   82804   SelectDest *pDest      /* What to do with the query results */
   82805 ){
   82806   int i, j;              /* Loop counters */
   82807   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
   82808   Vdbe *v;               /* The virtual machine under construction */
   82809   int isAgg;             /* True for select lists like "count(*)" */
   82810   ExprList *pEList;      /* List of columns to extract. */
   82811   SrcList *pTabList;     /* List of tables to select from */
   82812   Expr *pWhere;          /* The WHERE clause.  May be NULL */
   82813   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
   82814   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
   82815   Expr *pHaving;         /* The HAVING clause.  May be NULL */
   82816   int isDistinct;        /* True if the DISTINCT keyword is present */
   82817   int distinct;          /* Table to use for the distinct set */
   82818   int rc = 1;            /* Value to return from this function */
   82819   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
   82820   AggInfo sAggInfo;      /* Information used by aggregate queries */
   82821   int iEnd;              /* Address of the end of the query */
   82822   sqlite3 *db;           /* The database connection */
   82823 
   82824   db = pParse->db;
   82825   if( p==0 || db->mallocFailed || pParse->nErr ){
   82826     return 1;
   82827   }
   82828   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
   82829   memset(&sAggInfo, 0, sizeof(sAggInfo));
   82830 
   82831   if( IgnorableOrderby(pDest) ){
   82832     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
   82833            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
   82834     /* If ORDER BY makes no difference in the output then neither does
   82835     ** DISTINCT so it can be removed too. */
   82836     sqlite3ExprListDelete(db, p->pOrderBy);
   82837     p->pOrderBy = 0;
   82838     p->selFlags &= ~SF_Distinct;
   82839   }
   82840   sqlite3SelectPrep(pParse, p, 0);
   82841   pOrderBy = p->pOrderBy;
   82842   pTabList = p->pSrc;
   82843   pEList = p->pEList;
   82844   if( pParse->nErr || db->mallocFailed ){
   82845     goto select_end;
   82846   }
   82847   isAgg = (p->selFlags & SF_Aggregate)!=0;
   82848   assert( pEList!=0 );
   82849 
   82850   /* Begin generating code.
   82851   */
   82852   v = sqlite3GetVdbe(pParse);
   82853   if( v==0 ) goto select_end;
   82854 
   82855   /* Generate code for all sub-queries in the FROM clause
   82856   */
   82857 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   82858   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
   82859     struct SrcList_item *pItem = &pTabList->a[i];
   82860     SelectDest dest;
   82861     Select *pSub = pItem->pSelect;
   82862     int isAggSub;
   82863 
   82864     if( pSub==0 || pItem->isPopulated ) continue;
   82865 
   82866     /* Increment Parse.nHeight by the height of the largest expression
   82867     ** tree refered to by this, the parent select. The child select
   82868     ** may contain expression trees of at most
   82869     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
   82870     ** more conservative than necessary, but much easier than enforcing
   82871     ** an exact limit.
   82872     */
   82873     pParse->nHeight += sqlite3SelectExprHeight(p);
   82874 
   82875     /* Check to see if the subquery can be absorbed into the parent. */
   82876     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
   82877     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
   82878       if( isAggSub ){
   82879         isAgg = 1;
   82880         p->selFlags |= SF_Aggregate;
   82881       }
   82882       i = -1;
   82883     }else{
   82884       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
   82885       assert( pItem->isPopulated==0 );
   82886       sqlite3Select(pParse, pSub, &dest);
   82887       pItem->isPopulated = 1;
   82888     }
   82889     if( /*pParse->nErr ||*/ db->mallocFailed ){
   82890       goto select_end;
   82891     }
   82892     pParse->nHeight -= sqlite3SelectExprHeight(p);
   82893     pTabList = p->pSrc;
   82894     if( !IgnorableOrderby(pDest) ){
   82895       pOrderBy = p->pOrderBy;
   82896     }
   82897   }
   82898   pEList = p->pEList;
   82899 #endif
   82900   pWhere = p->pWhere;
   82901   pGroupBy = p->pGroupBy;
   82902   pHaving = p->pHaving;
   82903   isDistinct = (p->selFlags & SF_Distinct)!=0;
   82904 
   82905 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   82906   /* If there is are a sequence of queries, do the earlier ones first.
   82907   */
   82908   if( p->pPrior ){
   82909     if( p->pRightmost==0 ){
   82910       Select *pLoop, *pRight = 0;
   82911       int cnt = 0;
   82912       int mxSelect;
   82913       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
   82914         pLoop->pRightmost = p;
   82915         pLoop->pNext = pRight;
   82916         pRight = pLoop;
   82917       }
   82918       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
   82919       if( mxSelect && cnt>mxSelect ){
   82920         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
   82921         return 1;
   82922       }
   82923     }
   82924     return multiSelect(pParse, p, pDest);
   82925   }
   82926 #endif
   82927 
   82928   /* If writing to memory or generating a set
   82929   ** only a single column may be output.
   82930   */
   82931 #ifndef SQLITE_OMIT_SUBQUERY
   82932   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
   82933     goto select_end;
   82934   }
   82935 #endif
   82936 
   82937   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
   82938   ** GROUP BY might use an index, DISTINCT never does.
   82939   */
   82940   assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
   82941   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
   82942     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
   82943     pGroupBy = p->pGroupBy;
   82944     p->selFlags &= ~SF_Distinct;
   82945     isDistinct = 0;
   82946   }
   82947 
   82948   /* If there is an ORDER BY clause, then this sorting
   82949   ** index might end up being unused if the data can be
   82950   ** extracted in pre-sorted order.  If that is the case, then the
   82951   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
   82952   ** we figure out that the sorting index is not needed.  The addrSortIndex
   82953   ** variable is used to facilitate that change.
   82954   */
   82955   if( pOrderBy ){
   82956     KeyInfo *pKeyInfo;
   82957     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
   82958     pOrderBy->iECursor = pParse->nTab++;
   82959     p->addrOpenEphm[2] = addrSortIndex =
   82960       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
   82961                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
   82962                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
   82963   }else{
   82964     addrSortIndex = -1;
   82965   }
   82966 
   82967   /* If the output is destined for a temporary table, open that table.
   82968   */
   82969   if( pDest->eDest==SRT_EphemTab ){
   82970     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
   82971   }
   82972 
   82973   /* Set the limiter.
   82974   */
   82975   iEnd = sqlite3VdbeMakeLabel(v);
   82976   computeLimitRegisters(pParse, p, iEnd);
   82977 
   82978   /* Open a virtual index to use for the distinct set.
   82979   */
   82980   if( isDistinct ){
   82981     KeyInfo *pKeyInfo;
   82982     assert( isAgg || pGroupBy );
   82983     distinct = pParse->nTab++;
   82984     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
   82985     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
   82986                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
   82987   }else{
   82988     distinct = -1;
   82989   }
   82990 
   82991   /* Aggregate and non-aggregate queries are handled differently */
   82992   if( !isAgg && pGroupBy==0 ){
   82993     /* This case is for non-aggregate queries
   82994     ** Begin the database scan
   82995     */
   82996     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
   82997     if( pWInfo==0 ) goto select_end;
   82998 
   82999     /* If sorting index that was created by a prior OP_OpenEphemeral
   83000     ** instruction ended up not being needed, then change the OP_OpenEphemeral
   83001     ** into an OP_Noop.
   83002     */
   83003     if( addrSortIndex>=0 && pOrderBy==0 ){
   83004       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
   83005       p->addrOpenEphm[2] = -1;
   83006     }
   83007 
   83008     /* Use the standard inner loop
   83009     */
   83010     assert(!isDistinct);
   83011     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
   83012                     pWInfo->iContinue, pWInfo->iBreak);
   83013 
   83014     /* End the database scan loop.
   83015     */
   83016     sqlite3WhereEnd(pWInfo);
   83017   }else{
   83018     /* This is the processing for aggregate queries */
   83019     NameContext sNC;    /* Name context for processing aggregate information */
   83020     int iAMem;          /* First Mem address for storing current GROUP BY */
   83021     int iBMem;          /* First Mem address for previous GROUP BY */
   83022     int iUseFlag;       /* Mem address holding flag indicating that at least
   83023                         ** one row of the input to the aggregator has been
   83024                         ** processed */
   83025     int iAbortFlag;     /* Mem address which causes query abort if positive */
   83026     int groupBySort;    /* Rows come from source in GROUP BY order */
   83027     int addrEnd;        /* End of processing for this SELECT */
   83028 
   83029     /* Remove any and all aliases between the result set and the
   83030     ** GROUP BY clause.
   83031     */
   83032     if( pGroupBy ){
   83033       int k;                        /* Loop counter */
   83034       struct ExprList_item *pItem;  /* For looping over expression in a list */
   83035 
   83036       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
   83037         pItem->iAlias = 0;
   83038       }
   83039       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
   83040         pItem->iAlias = 0;
   83041       }
   83042     }
   83043 
   83044 
   83045     /* Create a label to jump to when we want to abort the query */
   83046     addrEnd = sqlite3VdbeMakeLabel(v);
   83047 
   83048     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
   83049     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
   83050     ** SELECT statement.
   83051     */
   83052     memset(&sNC, 0, sizeof(sNC));
   83053     sNC.pParse = pParse;
   83054     sNC.pSrcList = pTabList;
   83055     sNC.pAggInfo = &sAggInfo;
   83056     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
   83057     sAggInfo.pGroupBy = pGroupBy;
   83058     sqlite3ExprAnalyzeAggList(&sNC, pEList);
   83059     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
   83060     if( pHaving ){
   83061       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
   83062     }
   83063     sAggInfo.nAccumulator = sAggInfo.nColumn;
   83064     for(i=0; i<sAggInfo.nFunc; i++){
   83065       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
   83066       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
   83067     }
   83068     if( db->mallocFailed ) goto select_end;
   83069 
   83070     /* Processing for aggregates with GROUP BY is very different and
   83071     ** much more complex than aggregates without a GROUP BY.
   83072     */
   83073     if( pGroupBy ){
   83074       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
   83075       int j1;             /* A-vs-B comparision jump */
   83076       int addrOutputRow;  /* Start of subroutine that outputs a result row */
   83077       int regOutputRow;   /* Return address register for output subroutine */
   83078       int addrSetAbort;   /* Set the abort flag and return */
   83079       int addrTopOfLoop;  /* Top of the input loop */
   83080       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
   83081       int addrReset;      /* Subroutine for resetting the accumulator */
   83082       int regReset;       /* Return address register for reset subroutine */
   83083 
   83084       /* If there is a GROUP BY clause we might need a sorting index to
   83085       ** implement it.  Allocate that sorting index now.  If it turns out
   83086       ** that we do not need it after all, the OpenEphemeral instruction
   83087       ** will be converted into a Noop.
   83088       */
   83089       sAggInfo.sortingIdx = pParse->nTab++;
   83090       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
   83091       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
   83092           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
   83093           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
   83094 
   83095       /* Initialize memory locations used by GROUP BY aggregate processing
   83096       */
   83097       iUseFlag = ++pParse->nMem;
   83098       iAbortFlag = ++pParse->nMem;
   83099       regOutputRow = ++pParse->nMem;
   83100       addrOutputRow = sqlite3VdbeMakeLabel(v);
   83101       regReset = ++pParse->nMem;
   83102       addrReset = sqlite3VdbeMakeLabel(v);
   83103       iAMem = pParse->nMem + 1;
   83104       pParse->nMem += pGroupBy->nExpr;
   83105       iBMem = pParse->nMem + 1;
   83106       pParse->nMem += pGroupBy->nExpr;
   83107       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
   83108       VdbeComment((v, "clear abort flag"));
   83109       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
   83110       VdbeComment((v, "indicate accumulator empty"));
   83111 
   83112       /* Begin a loop that will extract all source rows in GROUP BY order.
   83113       ** This might involve two separate loops with an OP_Sort in between, or
   83114       ** it might be a single loop that uses an index to extract information
   83115       ** in the right order to begin with.
   83116       */
   83117       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
   83118       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
   83119       if( pWInfo==0 ) goto select_end;
   83120       if( pGroupBy==0 ){
   83121         /* The optimizer is able to deliver rows in group by order so
   83122         ** we do not have to sort.  The OP_OpenEphemeral table will be
   83123         ** cancelled later because we still need to use the pKeyInfo
   83124         */
   83125         pGroupBy = p->pGroupBy;
   83126         groupBySort = 0;
   83127       }else{
   83128         /* Rows are coming out in undetermined order.  We have to push
   83129         ** each row into a sorting index, terminate the first loop,
   83130         ** then loop over the sorting index in order to get the output
   83131         ** in sorted order
   83132         */
   83133         int regBase;
   83134         int regRecord;
   83135         int nCol;
   83136         int nGroupBy;
   83137 
   83138         groupBySort = 1;
   83139         nGroupBy = pGroupBy->nExpr;
   83140         nCol = nGroupBy + 1;
   83141         j = nGroupBy+1;
   83142         for(i=0; i<sAggInfo.nColumn; i++){
   83143           if( sAggInfo.aCol[i].iSorterColumn>=j ){
   83144             nCol++;
   83145             j++;
   83146           }
   83147         }
   83148         regBase = sqlite3GetTempRange(pParse, nCol);
   83149         sqlite3ExprCacheClear(pParse);
   83150         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
   83151         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
   83152         j = nGroupBy+1;
   83153         for(i=0; i<sAggInfo.nColumn; i++){
   83154           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
   83155           if( pCol->iSorterColumn>=j ){
   83156             int r1 = j + regBase;
   83157             int r2;
   83158 
   83159             r2 = sqlite3ExprCodeGetColumn(pParse,
   83160                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
   83161             if( r1!=r2 ){
   83162               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
   83163             }
   83164             j++;
   83165           }
   83166         }
   83167         regRecord = sqlite3GetTempReg(pParse);
   83168         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
   83169         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
   83170         sqlite3ReleaseTempReg(pParse, regRecord);
   83171         sqlite3ReleaseTempRange(pParse, regBase, nCol);
   83172         sqlite3WhereEnd(pWInfo);
   83173         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
   83174         VdbeComment((v, "GROUP BY sort"));
   83175         sAggInfo.useSortingIdx = 1;
   83176         sqlite3ExprCacheClear(pParse);
   83177       }
   83178 
   83179       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
   83180       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
   83181       ** Then compare the current GROUP BY terms against the GROUP BY terms
   83182       ** from the previous row currently stored in a0, a1, a2...
   83183       */
   83184       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
   83185       sqlite3ExprCacheClear(pParse);
   83186       for(j=0; j<pGroupBy->nExpr; j++){
   83187         if( groupBySort ){
   83188           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
   83189         }else{
   83190           sAggInfo.directMode = 1;
   83191           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
   83192         }
   83193       }
   83194       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
   83195                           (char*)pKeyInfo, P4_KEYINFO);
   83196       j1 = sqlite3VdbeCurrentAddr(v);
   83197       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
   83198 
   83199       /* Generate code that runs whenever the GROUP BY changes.
   83200       ** Changes in the GROUP BY are detected by the previous code
   83201       ** block.  If there were no changes, this block is skipped.
   83202       **
   83203       ** This code copies current group by terms in b0,b1,b2,...
   83204       ** over to a0,a1,a2.  It then calls the output subroutine
   83205       ** and resets the aggregate accumulator registers in preparation
   83206       ** for the next GROUP BY batch.
   83207       */
   83208       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
   83209       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
   83210       VdbeComment((v, "output one row"));
   83211       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
   83212       VdbeComment((v, "check abort flag"));
   83213       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
   83214       VdbeComment((v, "reset accumulator"));
   83215 
   83216       /* Update the aggregate accumulators based on the content of
   83217       ** the current row
   83218       */
   83219       sqlite3VdbeJumpHere(v, j1);
   83220       updateAccumulator(pParse, &sAggInfo);
   83221       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
   83222       VdbeComment((v, "indicate data in accumulator"));
   83223 
   83224       /* End of the loop
   83225       */
   83226       if( groupBySort ){
   83227         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
   83228       }else{
   83229         sqlite3WhereEnd(pWInfo);
   83230         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
   83231       }
   83232 
   83233       /* Output the final row of result
   83234       */
   83235       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
   83236       VdbeComment((v, "output final row"));
   83237 
   83238       /* Jump over the subroutines
   83239       */
   83240       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
   83241 
   83242       /* Generate a subroutine that outputs a single row of the result
   83243       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
   83244       ** is less than or equal to zero, the subroutine is a no-op.  If
   83245       ** the processing calls for the query to abort, this subroutine
   83246       ** increments the iAbortFlag memory location before returning in
   83247       ** order to signal the caller to abort.
   83248       */
   83249       addrSetAbort = sqlite3VdbeCurrentAddr(v);
   83250       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
   83251       VdbeComment((v, "set abort flag"));
   83252       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   83253       sqlite3VdbeResolveLabel(v, addrOutputRow);
   83254       addrOutputRow = sqlite3VdbeCurrentAddr(v);
   83255       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
   83256       VdbeComment((v, "Groupby result generator entry point"));
   83257       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   83258       finalizeAggFunctions(pParse, &sAggInfo);
   83259       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
   83260       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
   83261                       distinct, pDest,
   83262                       addrOutputRow+1, addrSetAbort);
   83263       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   83264       VdbeComment((v, "end groupby result generator"));
   83265 
   83266       /* Generate a subroutine that will reset the group-by accumulator
   83267       */
   83268       sqlite3VdbeResolveLabel(v, addrReset);
   83269       resetAccumulator(pParse, &sAggInfo);
   83270       sqlite3VdbeAddOp1(v, OP_Return, regReset);
   83271 
   83272     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
   83273     else {
   83274       ExprList *pDel = 0;
   83275 #ifndef SQLITE_OMIT_BTREECOUNT
   83276       Table *pTab;
   83277       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
   83278         /* If isSimpleCount() returns a pointer to a Table structure, then
   83279         ** the SQL statement is of the form:
   83280         **
   83281         **   SELECT count(*) FROM <tbl>
   83282         **
   83283         ** where the Table structure returned represents table <tbl>.
   83284         **
   83285         ** This statement is so common that it is optimized specially. The
   83286         ** OP_Count instruction is executed either on the intkey table that
   83287         ** contains the data for table <tbl> or on one of its indexes. It
   83288         ** is better to execute the op on an index, as indexes are almost
   83289         ** always spread across less pages than their corresponding tables.
   83290         */
   83291         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   83292         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
   83293         Index *pIdx;                         /* Iterator variable */
   83294         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
   83295         Index *pBest = 0;                    /* Best index found so far */
   83296         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
   83297 
   83298         sqlite3CodeVerifySchema(pParse, iDb);
   83299         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   83300 
   83301         /* Search for the index that has the least amount of columns. If
   83302         ** there is such an index, and it has less columns than the table
   83303         ** does, then we can assume that it consumes less space on disk and
   83304         ** will therefore be cheaper to scan to determine the query result.
   83305         ** In this case set iRoot to the root page number of the index b-tree
   83306         ** and pKeyInfo to the KeyInfo structure required to navigate the
   83307         ** index.
   83308         **
   83309         ** In practice the KeyInfo structure will not be used. It is only
   83310         ** passed to keep OP_OpenRead happy.
   83311         */
   83312         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   83313           if( !pBest || pIdx->nColumn<pBest->nColumn ){
   83314             pBest = pIdx;
   83315           }
   83316         }
   83317         if( pBest && pBest->nColumn<pTab->nCol ){
   83318           iRoot = pBest->tnum;
   83319           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
   83320         }
   83321 
   83322         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
   83323         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
   83324         if( pKeyInfo ){
   83325           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
   83326         }
   83327         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
   83328         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
   83329       }else
   83330 #endif /* SQLITE_OMIT_BTREECOUNT */
   83331       {
   83332         /* Check if the query is of one of the following forms:
   83333         **
   83334         **   SELECT min(x) FROM ...
   83335         **   SELECT max(x) FROM ...
   83336         **
   83337         ** If it is, then ask the code in where.c to attempt to sort results
   83338         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
   83339         ** If where.c is able to produce results sorted in this order, then
   83340         ** add vdbe code to break out of the processing loop after the
   83341         ** first iteration (since the first iteration of the loop is
   83342         ** guaranteed to operate on the row with the minimum or maximum
   83343         ** value of x, the only row required).
   83344         **
   83345         ** A special flag must be passed to sqlite3WhereBegin() to slightly
   83346         ** modify behaviour as follows:
   83347         **
   83348         **   + If the query is a "SELECT min(x)", then the loop coded by
   83349         **     where.c should not iterate over any values with a NULL value
   83350         **     for x.
   83351         **
   83352         **   + The optimizer code in where.c (the thing that decides which
   83353         **     index or indices to use) should place a different priority on
   83354         **     satisfying the 'ORDER BY' clause than it does in other cases.
   83355         **     Refer to code and comments in where.c for details.
   83356         */
   83357         ExprList *pMinMax = 0;
   83358         u8 flag = minMaxQuery(p);
   83359         if( flag ){
   83360           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
   83361           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
   83362           pDel = pMinMax;
   83363           if( pMinMax && !db->mallocFailed ){
   83364             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
   83365             pMinMax->a[0].pExpr->op = TK_COLUMN;
   83366           }
   83367         }
   83368 
   83369         /* This case runs if the aggregate has no GROUP BY clause.  The
   83370         ** processing is much simpler since there is only a single row
   83371         ** of output.
   83372         */
   83373         resetAccumulator(pParse, &sAggInfo);
   83374         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
   83375         if( pWInfo==0 ){
   83376           sqlite3ExprListDelete(db, pDel);
   83377           goto select_end;
   83378         }
   83379         updateAccumulator(pParse, &sAggInfo);
   83380         if( !pMinMax && flag ){
   83381           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
   83382           VdbeComment((v, "%s() by index",
   83383                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
   83384         }
   83385         sqlite3WhereEnd(pWInfo);
   83386         finalizeAggFunctions(pParse, &sAggInfo);
   83387       }
   83388 
   83389       pOrderBy = 0;
   83390       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
   83391       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
   83392                       pDest, addrEnd, addrEnd);
   83393       sqlite3ExprListDelete(db, pDel);
   83394     }
   83395     sqlite3VdbeResolveLabel(v, addrEnd);
   83396 
   83397   } /* endif aggregate query */
   83398 
   83399   /* If there is an ORDER BY clause, then we need to sort the results
   83400   ** and send them to the callback one by one.
   83401   */
   83402   if( pOrderBy ){
   83403     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
   83404   }
   83405 
   83406   /* Jump here to skip this query
   83407   */
   83408   sqlite3VdbeResolveLabel(v, iEnd);
   83409 
   83410   /* The SELECT was successfully coded.   Set the return code to 0
   83411   ** to indicate no errors.
   83412   */
   83413   rc = 0;
   83414 
   83415   /* Control jumps to here if an error is encountered above, or upon
   83416   ** successful coding of the SELECT.
   83417   */
   83418 select_end:
   83419 
   83420   /* Identify column names if results of the SELECT are to be output.
   83421   */
   83422   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
   83423     generateColumnNames(pParse, pTabList, pEList);
   83424   }
   83425 
   83426   sqlite3DbFree(db, sAggInfo.aCol);
   83427   sqlite3DbFree(db, sAggInfo.aFunc);
   83428   return rc;
   83429 }
   83430 
   83431 #if defined(SQLITE_DEBUG)
   83432 /*
   83433 *******************************************************************************
   83434 ** The following code is used for testing and debugging only.  The code
   83435 ** that follows does not appear in normal builds.
   83436 **
   83437 ** These routines are used to print out the content of all or part of a
   83438 ** parse structures such as Select or Expr.  Such printouts are useful
   83439 ** for helping to understand what is happening inside the code generator
   83440 ** during the execution of complex SELECT statements.
   83441 **
   83442 ** These routine are not called anywhere from within the normal
   83443 ** code base.  Then are intended to be called from within the debugger
   83444 ** or from temporary "printf" statements inserted for debugging.
   83445 */
   83446 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
   83447   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
   83448     sqlite3DebugPrintf("(%s", p->u.zToken);
   83449   }else{
   83450     sqlite3DebugPrintf("(%d", p->op);
   83451   }
   83452   if( p->pLeft ){
   83453     sqlite3DebugPrintf(" ");
   83454     sqlite3PrintExpr(p->pLeft);
   83455   }
   83456   if( p->pRight ){
   83457     sqlite3DebugPrintf(" ");
   83458     sqlite3PrintExpr(p->pRight);
   83459   }
   83460   sqlite3DebugPrintf(")");
   83461 }
   83462 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
   83463   int i;
   83464   for(i=0; i<pList->nExpr; i++){
   83465     sqlite3PrintExpr(pList->a[i].pExpr);
   83466     if( i<pList->nExpr-1 ){
   83467       sqlite3DebugPrintf(", ");
   83468     }
   83469   }
   83470 }
   83471 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
   83472   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
   83473   sqlite3PrintExprList(p->pEList);
   83474   sqlite3DebugPrintf("\n");
   83475   if( p->pSrc ){
   83476     char *zPrefix;
   83477     int i;
   83478     zPrefix = "FROM";
   83479     for(i=0; i<p->pSrc->nSrc; i++){
   83480       struct SrcList_item *pItem = &p->pSrc->a[i];
   83481       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
   83482       zPrefix = "";
   83483       if( pItem->pSelect ){
   83484         sqlite3DebugPrintf("(\n");
   83485         sqlite3PrintSelect(pItem->pSelect, indent+10);
   83486         sqlite3DebugPrintf("%*s)", indent+8, "");
   83487       }else if( pItem->zName ){
   83488         sqlite3DebugPrintf("%s", pItem->zName);
   83489       }
   83490       if( pItem->pTab ){
   83491         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
   83492       }
   83493       if( pItem->zAlias ){
   83494         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
   83495       }
   83496       if( i<p->pSrc->nSrc-1 ){
   83497         sqlite3DebugPrintf(",");
   83498       }
   83499       sqlite3DebugPrintf("\n");
   83500     }
   83501   }
   83502   if( p->pWhere ){
   83503     sqlite3DebugPrintf("%*s WHERE ", indent, "");
   83504     sqlite3PrintExpr(p->pWhere);
   83505     sqlite3DebugPrintf("\n");
   83506   }
   83507   if( p->pGroupBy ){
   83508     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
   83509     sqlite3PrintExprList(p->pGroupBy);
   83510     sqlite3DebugPrintf("\n");
   83511   }
   83512   if( p->pHaving ){
   83513     sqlite3DebugPrintf("%*s HAVING ", indent, "");
   83514     sqlite3PrintExpr(p->pHaving);
   83515     sqlite3DebugPrintf("\n");
   83516   }
   83517   if( p->pOrderBy ){
   83518     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
   83519     sqlite3PrintExprList(p->pOrderBy);
   83520     sqlite3DebugPrintf("\n");
   83521   }
   83522 }
   83523 /* End of the structure debug printing code
   83524 *****************************************************************************/
   83525 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
   83526 
   83527 /************** End of select.c **********************************************/
   83528 /************** Begin file table.c *******************************************/
   83529 /*
   83530 ** 2001 September 15
   83531 **
   83532 ** The author disclaims copyright to this source code.  In place of
   83533 ** a legal notice, here is a blessing:
   83534 **
   83535 **    May you do good and not evil.
   83536 **    May you find forgiveness for yourself and forgive others.
   83537 **    May you share freely, never taking more than you give.
   83538 **
   83539 *************************************************************************
   83540 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
   83541 ** interface routines.  These are just wrappers around the main
   83542 ** interface routine of sqlite3_exec().
   83543 **
   83544 ** These routines are in a separate files so that they will not be linked
   83545 ** if they are not used.
   83546 */
   83547 
   83548 #ifndef SQLITE_OMIT_GET_TABLE
   83549 
   83550 /*
   83551 ** This structure is used to pass data from sqlite3_get_table() through
   83552 ** to the callback function is uses to build the result.
   83553 */
   83554 typedef struct TabResult {
   83555   char **azResult;   /* Accumulated output */
   83556   char *zErrMsg;     /* Error message text, if an error occurs */
   83557   int nAlloc;        /* Slots allocated for azResult[] */
   83558   int nRow;          /* Number of rows in the result */
   83559   int nColumn;       /* Number of columns in the result */
   83560   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
   83561   int rc;            /* Return code from sqlite3_exec() */
   83562 } TabResult;
   83563 
   83564 /*
   83565 ** This routine is called once for each row in the result table.  Its job
   83566 ** is to fill in the TabResult structure appropriately, allocating new
   83567 ** memory as necessary.
   83568 */
   83569 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
   83570   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
   83571   int need;                         /* Slots needed in p->azResult[] */
   83572   int i;                            /* Loop counter */
   83573   char *z;                          /* A single column of result */
   83574 
   83575   /* Make sure there is enough space in p->azResult to hold everything
   83576   ** we need to remember from this invocation of the callback.
   83577   */
   83578   if( p->nRow==0 && argv!=0 ){
   83579     need = nCol*2;
   83580   }else{
   83581     need = nCol;
   83582   }
   83583   if( p->nData + need > p->nAlloc ){
   83584     char **azNew;
   83585     p->nAlloc = p->nAlloc*2 + need;
   83586     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
   83587     if( azNew==0 ) goto malloc_failed;
   83588     p->azResult = azNew;
   83589   }
   83590 
   83591   /* If this is the first row, then generate an extra row containing
   83592   ** the names of all columns.
   83593   */
   83594   if( p->nRow==0 ){
   83595     p->nColumn = nCol;
   83596     for(i=0; i<nCol; i++){
   83597       z = sqlite3_mprintf("%s", colv[i]);
   83598       if( z==0 ) goto malloc_failed;
   83599       p->azResult[p->nData++] = z;
   83600     }
   83601   }else if( p->nColumn!=nCol ){
   83602     sqlite3_free(p->zErrMsg);
   83603     p->zErrMsg = sqlite3_mprintf(
   83604        "sqlite3_get_table() called with two or more incompatible queries"
   83605     );
   83606     p->rc = SQLITE_ERROR;
   83607     return 1;
   83608   }
   83609 
   83610   /* Copy over the row data
   83611   */
   83612   if( argv!=0 ){
   83613     for(i=0; i<nCol; i++){
   83614       if( argv[i]==0 ){
   83615         z = 0;
   83616       }else{
   83617         int n = sqlite3Strlen30(argv[i])+1;
   83618         z = sqlite3_malloc( n );
   83619         if( z==0 ) goto malloc_failed;
   83620         memcpy(z, argv[i], n);
   83621       }
   83622       p->azResult[p->nData++] = z;
   83623     }
   83624     p->nRow++;
   83625   }
   83626   return 0;
   83627 
   83628 malloc_failed:
   83629   p->rc = SQLITE_NOMEM;
   83630   return 1;
   83631 }
   83632 
   83633 /*
   83634 ** Query the database.  But instead of invoking a callback for each row,
   83635 ** malloc() for space to hold the result and return the entire results
   83636 ** at the conclusion of the call.
   83637 **
   83638 ** The result that is written to ***pazResult is held in memory obtained
   83639 ** from malloc().  But the caller cannot free this memory directly.
   83640 ** Instead, the entire table should be passed to sqlite3_free_table() when
   83641 ** the calling procedure is finished using it.
   83642 */
   83643 SQLITE_API int sqlite3_get_table(
   83644   sqlite3 *db,                /* The database on which the SQL executes */
   83645   const char *zSql,           /* The SQL to be executed */
   83646   char ***pazResult,          /* Write the result table here */
   83647   int *pnRow,                 /* Write the number of rows in the result here */
   83648   int *pnColumn,              /* Write the number of columns of result here */
   83649   char **pzErrMsg             /* Write error messages here */
   83650 ){
   83651   int rc;
   83652   TabResult res;
   83653 
   83654   *pazResult = 0;
   83655   if( pnColumn ) *pnColumn = 0;
   83656   if( pnRow ) *pnRow = 0;
   83657   if( pzErrMsg ) *pzErrMsg = 0;
   83658   res.zErrMsg = 0;
   83659   res.nRow = 0;
   83660   res.nColumn = 0;
   83661   res.nData = 1;
   83662   res.nAlloc = 20;
   83663   res.rc = SQLITE_OK;
   83664   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
   83665   if( res.azResult==0 ){
   83666      db->errCode = SQLITE_NOMEM;
   83667      return SQLITE_NOMEM;
   83668   }
   83669   res.azResult[0] = 0;
   83670   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
   83671   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
   83672   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
   83673   if( (rc&0xff)==SQLITE_ABORT ){
   83674     sqlite3_free_table(&res.azResult[1]);
   83675     if( res.zErrMsg ){
   83676       if( pzErrMsg ){
   83677         sqlite3_free(*pzErrMsg);
   83678         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
   83679       }
   83680       sqlite3_free(res.zErrMsg);
   83681     }
   83682     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
   83683     return res.rc;
   83684   }
   83685   sqlite3_free(res.zErrMsg);
   83686   if( rc!=SQLITE_OK ){
   83687     sqlite3_free_table(&res.azResult[1]);
   83688     return rc;
   83689   }
   83690   if( res.nAlloc>res.nData ){
   83691     char **azNew;
   83692     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
   83693     if( azNew==0 ){
   83694       sqlite3_free_table(&res.azResult[1]);
   83695       db->errCode = SQLITE_NOMEM;
   83696       return SQLITE_NOMEM;
   83697     }
   83698     res.azResult = azNew;
   83699   }
   83700   *pazResult = &res.azResult[1];
   83701   if( pnColumn ) *pnColumn = res.nColumn;
   83702   if( pnRow ) *pnRow = res.nRow;
   83703   return rc;
   83704 }
   83705 
   83706 /*
   83707 ** This routine frees the space the sqlite3_get_table() malloced.
   83708 */
   83709 SQLITE_API void sqlite3_free_table(
   83710   char **azResult            /* Result returned from from sqlite3_get_table() */
   83711 ){
   83712   if( azResult ){
   83713     int i, n;
   83714     azResult--;
   83715     assert( azResult!=0 );
   83716     n = SQLITE_PTR_TO_INT(azResult[0]);
   83717     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
   83718     sqlite3_free(azResult);
   83719   }
   83720 }
   83721 
   83722 #endif /* SQLITE_OMIT_GET_TABLE */
   83723 
   83724 /************** End of table.c ***********************************************/
   83725 /************** Begin file trigger.c *****************************************/
   83726 /*
   83727 **
   83728 ** The author disclaims copyright to this source code.  In place of
   83729 ** a legal notice, here is a blessing:
   83730 **
   83731 **    May you do good and not evil.
   83732 **    May you find forgiveness for yourself and forgive others.
   83733 **    May you share freely, never taking more than you give.
   83734 **
   83735 *************************************************************************
   83736 ** This file contains the implementation for TRIGGERs
   83737 */
   83738 
   83739 #ifndef SQLITE_OMIT_TRIGGER
   83740 /*
   83741 ** Delete a linked list of TriggerStep structures.
   83742 */
   83743 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
   83744   while( pTriggerStep ){
   83745     TriggerStep * pTmp = pTriggerStep;
   83746     pTriggerStep = pTriggerStep->pNext;
   83747 
   83748     sqlite3ExprDelete(db, pTmp->pWhere);
   83749     sqlite3ExprListDelete(db, pTmp->pExprList);
   83750     sqlite3SelectDelete(db, pTmp->pSelect);
   83751     sqlite3IdListDelete(db, pTmp->pIdList);
   83752 
   83753     sqlite3DbFree(db, pTmp);
   83754   }
   83755 }
   83756 
   83757 /*
   83758 ** Given table pTab, return a list of all the triggers attached to
   83759 ** the table. The list is connected by Trigger.pNext pointers.
   83760 **
   83761 ** All of the triggers on pTab that are in the same database as pTab
   83762 ** are already attached to pTab->pTrigger.  But there might be additional
   83763 ** triggers on pTab in the TEMP schema.  This routine prepends all
   83764 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
   83765 ** and returns the combined list.
   83766 **
   83767 ** To state it another way:  This routine returns a list of all triggers
   83768 ** that fire off of pTab.  The list will include any TEMP triggers on
   83769 ** pTab as well as the triggers lised in pTab->pTrigger.
   83770 */
   83771 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
   83772   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
   83773   Trigger *pList = 0;                  /* List of triggers to return */
   83774 
   83775   if( pParse->disableTriggers ){
   83776     return 0;
   83777   }
   83778 
   83779   if( pTmpSchema!=pTab->pSchema ){
   83780     HashElem *p;
   83781     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
   83782       Trigger *pTrig = (Trigger *)sqliteHashData(p);
   83783       if( pTrig->pTabSchema==pTab->pSchema
   83784        && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
   83785       ){
   83786         pTrig->pNext = (pList ? pList : pTab->pTrigger);
   83787         pList = pTrig;
   83788       }
   83789     }
   83790   }
   83791 
   83792   return (pList ? pList : pTab->pTrigger);
   83793 }
   83794 
   83795 /*
   83796 ** This is called by the parser when it sees a CREATE TRIGGER statement
   83797 ** up to the point of the BEGIN before the trigger actions.  A Trigger
   83798 ** structure is generated based on the information available and stored
   83799 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
   83800 ** sqlite3FinishTrigger() function is called to complete the trigger
   83801 ** construction process.
   83802 */
   83803 SQLITE_PRIVATE void sqlite3BeginTrigger(
   83804   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
   83805   Token *pName1,      /* The name of the trigger */
   83806   Token *pName2,      /* The name of the trigger */
   83807   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
   83808   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
   83809   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
   83810   SrcList *pTableName,/* The name of the table/view the trigger applies to */
   83811   Expr *pWhen,        /* WHEN clause */
   83812   int isTemp,         /* True if the TEMPORARY keyword is present */
   83813   int noErr           /* Suppress errors if the trigger already exists */
   83814 ){
   83815   Trigger *pTrigger = 0;  /* The new trigger */
   83816   Table *pTab;            /* Table that the trigger fires off of */
   83817   char *zName = 0;        /* Name of the trigger */
   83818   sqlite3 *db = pParse->db;  /* The database connection */
   83819   int iDb;                /* The database to store the trigger in */
   83820   Token *pName;           /* The unqualified db name */
   83821   DbFixer sFix;           /* State vector for the DB fixer */
   83822   int iTabDb;             /* Index of the database holding pTab */
   83823 
   83824   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
   83825   assert( pName2!=0 );
   83826   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
   83827   assert( op>0 && op<0xff );
   83828   if( isTemp ){
   83829     /* If TEMP was specified, then the trigger name may not be qualified. */
   83830     if( pName2->n>0 ){
   83831       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
   83832       goto trigger_cleanup;
   83833     }
   83834     iDb = 1;
   83835     pName = pName1;
   83836   }else{
   83837     /* Figure out the db that the the trigger will be created in */
   83838     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   83839     if( iDb<0 ){
   83840       goto trigger_cleanup;
   83841     }
   83842   }
   83843 
   83844   /* If the trigger name was unqualified, and the table is a temp table,
   83845   ** then set iDb to 1 to create the trigger in the temporary database.
   83846   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
   83847   ** exist, the error is caught by the block below.
   83848   */
   83849   if( !pTableName || db->mallocFailed ){
   83850     goto trigger_cleanup;
   83851   }
   83852   pTab = sqlite3SrcListLookup(pParse, pTableName);
   83853   if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
   83854     iDb = 1;
   83855   }
   83856 
   83857   /* Ensure the table name matches database name and that the table exists */
   83858   if( db->mallocFailed ) goto trigger_cleanup;
   83859   assert( pTableName->nSrc==1 );
   83860   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
   83861       sqlite3FixSrcList(&sFix, pTableName) ){
   83862     goto trigger_cleanup;
   83863   }
   83864   pTab = sqlite3SrcListLookup(pParse, pTableName);
   83865   if( !pTab ){
   83866     /* The table does not exist. */
   83867     if( db->init.iDb==1 ){
   83868       /* Ticket #3810.
   83869       ** Normally, whenever a table is dropped, all associated triggers are
   83870       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
   83871       ** and the table is dropped by a different database connection, the
   83872       ** trigger is not visible to the database connection that does the
   83873       ** drop so the trigger cannot be dropped.  This results in an
   83874       ** "orphaned trigger" - a trigger whose associated table is missing.
   83875       */
   83876       db->init.orphanTrigger = 1;
   83877     }
   83878     goto trigger_cleanup;
   83879   }
   83880   if( IsVirtual(pTab) ){
   83881     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
   83882     goto trigger_cleanup;
   83883   }
   83884 
   83885   /* Check that the trigger name is not reserved and that no trigger of the
   83886   ** specified name exists */
   83887   zName = sqlite3NameFromToken(db, pName);
   83888   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   83889     goto trigger_cleanup;
   83890   }
   83891   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
   83892                       zName, sqlite3Strlen30(zName)) ){
   83893     if( !noErr ){
   83894       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
   83895     }
   83896     goto trigger_cleanup;
   83897   }
   83898 
   83899   /* Do not create a trigger on a system table */
   83900   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
   83901     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
   83902     pParse->nErr++;
   83903     goto trigger_cleanup;
   83904   }
   83905 
   83906   /* INSTEAD of triggers are only for views and views only support INSTEAD
   83907   ** of triggers.
   83908   */
   83909   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
   83910     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
   83911         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
   83912     goto trigger_cleanup;
   83913   }
   83914   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
   83915     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
   83916         " trigger on table: %S", pTableName, 0);
   83917     goto trigger_cleanup;
   83918   }
   83919   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   83920 
   83921 #ifndef SQLITE_OMIT_AUTHORIZATION
   83922   {
   83923     int code = SQLITE_CREATE_TRIGGER;
   83924     const char *zDb = db->aDb[iTabDb].zName;
   83925     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
   83926     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
   83927     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
   83928       goto trigger_cleanup;
   83929     }
   83930     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
   83931       goto trigger_cleanup;
   83932     }
   83933   }
   83934 #endif
   83935 
   83936   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
   83937   ** cannot appear on views.  So we might as well translate every
   83938   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
   83939   ** elsewhere.
   83940   */
   83941   if (tr_tm == TK_INSTEAD){
   83942     tr_tm = TK_BEFORE;
   83943   }
   83944 
   83945   /* Build the Trigger object */
   83946   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
   83947   if( pTrigger==0 ) goto trigger_cleanup;
   83948   pTrigger->zName = zName;
   83949   zName = 0;
   83950   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
   83951   pTrigger->pSchema = db->aDb[iDb].pSchema;
   83952   pTrigger->pTabSchema = pTab->pSchema;
   83953   pTrigger->op = (u8)op;
   83954   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
   83955   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
   83956   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
   83957   assert( pParse->pNewTrigger==0 );
   83958   pParse->pNewTrigger = pTrigger;
   83959 
   83960 trigger_cleanup:
   83961   sqlite3DbFree(db, zName);
   83962   sqlite3SrcListDelete(db, pTableName);
   83963   sqlite3IdListDelete(db, pColumns);
   83964   sqlite3ExprDelete(db, pWhen);
   83965   if( !pParse->pNewTrigger ){
   83966     sqlite3DeleteTrigger(db, pTrigger);
   83967   }else{
   83968     assert( pParse->pNewTrigger==pTrigger );
   83969   }
   83970 }
   83971 
   83972 /*
   83973 ** This routine is called after all of the trigger actions have been parsed
   83974 ** in order to complete the process of building the trigger.
   83975 */
   83976 SQLITE_PRIVATE void sqlite3FinishTrigger(
   83977   Parse *pParse,          /* Parser context */
   83978   TriggerStep *pStepList, /* The triggered program */
   83979   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
   83980 ){
   83981   Trigger *pTrig = pParse->pNewTrigger;    /* Trigger being finished */
   83982   char *zName;                             /* Name of trigger */
   83983   sqlite3 *db = pParse->db;                /* The database */
   83984   DbFixer sFix;
   83985   int iDb;                                 /* Database containing the trigger */
   83986   Token nameToken;           /* Trigger name for error reporting */
   83987 
   83988   pTrig = pParse->pNewTrigger;
   83989   pParse->pNewTrigger = 0;
   83990   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
   83991   zName = pTrig->zName;
   83992   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
   83993   pTrig->step_list = pStepList;
   83994   while( pStepList ){
   83995     pStepList->pTrig = pTrig;
   83996     pStepList = pStepList->pNext;
   83997   }
   83998   nameToken.z = pTrig->zName;
   83999   nameToken.n = sqlite3Strlen30(nameToken.z);
   84000   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
   84001           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
   84002     goto triggerfinish_cleanup;
   84003   }
   84004 
   84005   /* if we are not initializing, and this trigger is not on a TEMP table,
   84006   ** build the sqlite_master entry
   84007   */
   84008   if( !db->init.busy ){
   84009     Vdbe *v;
   84010     char *z;
   84011 
   84012     /* Make an entry in the sqlite_master table */
   84013     v = sqlite3GetVdbe(pParse);
   84014     if( v==0 ) goto triggerfinish_cleanup;
   84015     sqlite3BeginWriteOperation(pParse, 0, iDb);
   84016     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
   84017     sqlite3NestedParse(pParse,
   84018        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
   84019        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
   84020        pTrig->table, z);
   84021     sqlite3DbFree(db, z);
   84022     sqlite3ChangeCookie(pParse, iDb);
   84023     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
   84024         db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
   84025     );
   84026   }
   84027 
   84028   if( db->init.busy ){
   84029     Trigger *pLink = pTrig;
   84030     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
   84031     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
   84032     if( pTrig ){
   84033       db->mallocFailed = 1;
   84034     }else if( pLink->pSchema==pLink->pTabSchema ){
   84035       Table *pTab;
   84036       int n = sqlite3Strlen30(pLink->table);
   84037       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
   84038       assert( pTab!=0 );
   84039       pLink->pNext = pTab->pTrigger;
   84040       pTab->pTrigger = pLink;
   84041     }
   84042   }
   84043 
   84044 triggerfinish_cleanup:
   84045   sqlite3DeleteTrigger(db, pTrig);
   84046   assert( !pParse->pNewTrigger );
   84047   sqlite3DeleteTriggerStep(db, pStepList);
   84048 }
   84049 
   84050 /*
   84051 ** Turn a SELECT statement (that the pSelect parameter points to) into
   84052 ** a trigger step.  Return a pointer to a TriggerStep structure.
   84053 **
   84054 ** The parser calls this routine when it finds a SELECT statement in
   84055 ** body of a TRIGGER.
   84056 */
   84057 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
   84058   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
   84059   if( pTriggerStep==0 ) {
   84060     sqlite3SelectDelete(db, pSelect);
   84061     return 0;
   84062   }
   84063   pTriggerStep->op = TK_SELECT;
   84064   pTriggerStep->pSelect = pSelect;
   84065   pTriggerStep->orconf = OE_Default;
   84066   return pTriggerStep;
   84067 }
   84068 
   84069 /*
   84070 ** Allocate space to hold a new trigger step.  The allocated space
   84071 ** holds both the TriggerStep object and the TriggerStep.target.z string.
   84072 **
   84073 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
   84074 */
   84075 static TriggerStep *triggerStepAllocate(
   84076   sqlite3 *db,                /* Database connection */
   84077   u8 op,                      /* Trigger opcode */
   84078   Token *pName                /* The target name */
   84079 ){
   84080   TriggerStep *pTriggerStep;
   84081 
   84082   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
   84083   if( pTriggerStep ){
   84084     char *z = (char*)&pTriggerStep[1];
   84085     memcpy(z, pName->z, pName->n);
   84086     pTriggerStep->target.z = z;
   84087     pTriggerStep->target.n = pName->n;
   84088     pTriggerStep->op = op;
   84089   }
   84090   return pTriggerStep;
   84091 }
   84092 
   84093 /*
   84094 ** Build a trigger step out of an INSERT statement.  Return a pointer
   84095 ** to the new trigger step.
   84096 **
   84097 ** The parser calls this routine when it sees an INSERT inside the
   84098 ** body of a trigger.
   84099 */
   84100 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
   84101   sqlite3 *db,        /* The database connection */
   84102   Token *pTableName,  /* Name of the table into which we insert */
   84103   IdList *pColumn,    /* List of columns in pTableName to insert into */
   84104   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
   84105   Select *pSelect,    /* A SELECT statement that supplies values */
   84106   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
   84107 ){
   84108   TriggerStep *pTriggerStep;
   84109 
   84110   assert(pEList == 0 || pSelect == 0);
   84111   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
   84112 
   84113   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
   84114   if( pTriggerStep ){
   84115     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   84116     pTriggerStep->pIdList = pColumn;
   84117     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
   84118     pTriggerStep->orconf = orconf;
   84119   }else{
   84120     sqlite3IdListDelete(db, pColumn);
   84121   }
   84122   sqlite3ExprListDelete(db, pEList);
   84123   sqlite3SelectDelete(db, pSelect);
   84124 
   84125   return pTriggerStep;
   84126 }
   84127 
   84128 /*
   84129 ** Construct a trigger step that implements an UPDATE statement and return
   84130 ** a pointer to that trigger step.  The parser calls this routine when it
   84131 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
   84132 */
   84133 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
   84134   sqlite3 *db,         /* The database connection */
   84135   Token *pTableName,   /* Name of the table to be updated */
   84136   ExprList *pEList,    /* The SET clause: list of column and new values */
   84137   Expr *pWhere,        /* The WHERE clause */
   84138   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
   84139 ){
   84140   TriggerStep *pTriggerStep;
   84141 
   84142   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
   84143   if( pTriggerStep ){
   84144     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
   84145     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   84146     pTriggerStep->orconf = orconf;
   84147   }
   84148   sqlite3ExprListDelete(db, pEList);
   84149   sqlite3ExprDelete(db, pWhere);
   84150   return pTriggerStep;
   84151 }
   84152 
   84153 /*
   84154 ** Construct a trigger step that implements a DELETE statement and return
   84155 ** a pointer to that trigger step.  The parser calls this routine when it
   84156 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
   84157 */
   84158 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
   84159   sqlite3 *db,            /* Database connection */
   84160   Token *pTableName,      /* The table from which rows are deleted */
   84161   Expr *pWhere            /* The WHERE clause */
   84162 ){
   84163   TriggerStep *pTriggerStep;
   84164 
   84165   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
   84166   if( pTriggerStep ){
   84167     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   84168     pTriggerStep->orconf = OE_Default;
   84169   }
   84170   sqlite3ExprDelete(db, pWhere);
   84171   return pTriggerStep;
   84172 }
   84173 
   84174 /*
   84175 ** Recursively delete a Trigger structure
   84176 */
   84177 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
   84178   if( pTrigger==0 ) return;
   84179   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
   84180   sqlite3DbFree(db, pTrigger->zName);
   84181   sqlite3DbFree(db, pTrigger->table);
   84182   sqlite3ExprDelete(db, pTrigger->pWhen);
   84183   sqlite3IdListDelete(db, pTrigger->pColumns);
   84184   sqlite3DbFree(db, pTrigger);
   84185 }
   84186 
   84187 /*
   84188 ** This function is called to drop a trigger from the database schema.
   84189 **
   84190 ** This may be called directly from the parser and therefore identifies
   84191 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
   84192 ** same job as this routine except it takes a pointer to the trigger
   84193 ** instead of the trigger name.
   84194 **/
   84195 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
   84196   Trigger *pTrigger = 0;
   84197   int i;
   84198   const char *zDb;
   84199   const char *zName;
   84200   int nName;
   84201   sqlite3 *db = pParse->db;
   84202 
   84203   if( db->mallocFailed ) goto drop_trigger_cleanup;
   84204   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   84205     goto drop_trigger_cleanup;
   84206   }
   84207 
   84208   assert( pName->nSrc==1 );
   84209   zDb = pName->a[0].zDatabase;
   84210   zName = pName->a[0].zName;
   84211   nName = sqlite3Strlen30(zName);
   84212   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   84213     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   84214     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
   84215     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
   84216     if( pTrigger ) break;
   84217   }
   84218   if( !pTrigger ){
   84219     if( !noErr ){
   84220       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
   84221     }
   84222     goto drop_trigger_cleanup;
   84223   }
   84224   sqlite3DropTriggerPtr(pParse, pTrigger);
   84225 
   84226 drop_trigger_cleanup:
   84227   sqlite3SrcListDelete(db, pName);
   84228 }
   84229 
   84230 /*
   84231 ** Return a pointer to the Table structure for the table that a trigger
   84232 ** is set on.
   84233 */
   84234 static Table *tableOfTrigger(Trigger *pTrigger){
   84235   int n = sqlite3Strlen30(pTrigger->table);
   84236   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
   84237 }
   84238 
   84239 
   84240 /*
   84241 ** Drop a trigger given a pointer to that trigger.
   84242 */
   84243 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
   84244   Table   *pTable;
   84245   Vdbe *v;
   84246   sqlite3 *db = pParse->db;
   84247   int iDb;
   84248 
   84249   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
   84250   assert( iDb>=0 && iDb<db->nDb );
   84251   pTable = tableOfTrigger(pTrigger);
   84252   assert( pTable );
   84253   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
   84254 #ifndef SQLITE_OMIT_AUTHORIZATION
   84255   {
   84256     int code = SQLITE_DROP_TRIGGER;
   84257     const char *zDb = db->aDb[iDb].zName;
   84258     const char *zTab = SCHEMA_TABLE(iDb);
   84259     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
   84260     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
   84261       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
   84262       return;
   84263     }
   84264   }
   84265 #endif
   84266 
   84267   /* Generate code to destroy the database record of the trigger.
   84268   */
   84269   assert( pTable!=0 );
   84270   if( (v = sqlite3GetVdbe(pParse))!=0 ){
   84271     int base;
   84272     static const VdbeOpList dropTrigger[] = {
   84273       { OP_Rewind,     0, ADDR(9),  0},
   84274       { OP_String8,    0, 1,        0}, /* 1 */
   84275       { OP_Column,     0, 1,        2},
   84276       { OP_Ne,         2, ADDR(8),  1},
   84277       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
   84278       { OP_Column,     0, 0,        2},
   84279       { OP_Ne,         2, ADDR(8),  1},
   84280       { OP_Delete,     0, 0,        0},
   84281       { OP_Next,       0, ADDR(1),  0}, /* 8 */
   84282     };
   84283 
   84284     sqlite3BeginWriteOperation(pParse, 0, iDb);
   84285     sqlite3OpenMasterTable(pParse, iDb);
   84286     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
   84287     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
   84288     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
   84289     sqlite3ChangeCookie(pParse, iDb);
   84290     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
   84291     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
   84292     if( pParse->nMem<3 ){
   84293       pParse->nMem = 3;
   84294     }
   84295   }
   84296 }
   84297 
   84298 /*
   84299 ** Remove a trigger from the hash tables of the sqlite* pointer.
   84300 */
   84301 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
   84302   Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
   84303   Trigger *pTrigger;
   84304   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
   84305   if( ALWAYS(pTrigger) ){
   84306     if( pTrigger->pSchema==pTrigger->pTabSchema ){
   84307       Table *pTab = tableOfTrigger(pTrigger);
   84308       Trigger **pp;
   84309       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
   84310       *pp = (*pp)->pNext;
   84311     }
   84312     sqlite3DeleteTrigger(db, pTrigger);
   84313     db->flags |= SQLITE_InternChanges;
   84314   }
   84315 }
   84316 
   84317 /*
   84318 ** pEList is the SET clause of an UPDATE statement.  Each entry
   84319 ** in pEList is of the format <id>=<expr>.  If any of the entries
   84320 ** in pEList have an <id> which matches an identifier in pIdList,
   84321 ** then return TRUE.  If pIdList==NULL, then it is considered a
   84322 ** wildcard that matches anything.  Likewise if pEList==NULL then
   84323 ** it matches anything so always return true.  Return false only
   84324 ** if there is no match.
   84325 */
   84326 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
   84327   int e;
   84328   if( pIdList==0 || NEVER(pEList==0) ) return 1;
   84329   for(e=0; e<pEList->nExpr; e++){
   84330     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
   84331   }
   84332   return 0;
   84333 }
   84334 
   84335 /*
   84336 ** Return a list of all triggers on table pTab if there exists at least
   84337 ** one trigger that must be fired when an operation of type 'op' is
   84338 ** performed on the table, and, if that operation is an UPDATE, if at
   84339 ** least one of the columns in pChanges is being modified.
   84340 */
   84341 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
   84342   Parse *pParse,          /* Parse context */
   84343   Table *pTab,            /* The table the contains the triggers */
   84344   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
   84345   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
   84346   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   84347 ){
   84348   int mask = 0;
   84349   Trigger *pList = sqlite3TriggerList(pParse, pTab);
   84350   Trigger *p;
   84351   assert( pList==0 || IsVirtual(pTab)==0 );
   84352   for(p=pList; p; p=p->pNext){
   84353     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
   84354       mask |= p->tr_tm;
   84355     }
   84356   }
   84357   if( pMask ){
   84358     *pMask = mask;
   84359   }
   84360   return (mask ? pList : 0);
   84361 }
   84362 
   84363 /*
   84364 ** Convert the pStep->target token into a SrcList and return a pointer
   84365 ** to that SrcList.
   84366 **
   84367 ** This routine adds a specific database name, if needed, to the target when
   84368 ** forming the SrcList.  This prevents a trigger in one database from
   84369 ** referring to a target in another database.  An exception is when the
   84370 ** trigger is in TEMP in which case it can refer to any other database it
   84371 ** wants.
   84372 */
   84373 static SrcList *targetSrcList(
   84374   Parse *pParse,       /* The parsing context */
   84375   TriggerStep *pStep   /* The trigger containing the target token */
   84376 ){
   84377   int iDb;             /* Index of the database to use */
   84378   SrcList *pSrc;       /* SrcList to be returned */
   84379 
   84380   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
   84381   if( pSrc ){
   84382     assert( pSrc->nSrc>0 );
   84383     assert( pSrc->a!=0 );
   84384     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
   84385     if( iDb==0 || iDb>=2 ){
   84386       sqlite3 *db = pParse->db;
   84387       assert( iDb<pParse->db->nDb );
   84388       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
   84389     }
   84390   }
   84391   return pSrc;
   84392 }
   84393 
   84394 /*
   84395 ** Generate VDBE code for the statements inside the body of a single
   84396 ** trigger.
   84397 */
   84398 static int codeTriggerProgram(
   84399   Parse *pParse,            /* The parser context */
   84400   TriggerStep *pStepList,   /* List of statements inside the trigger body */
   84401   int orconf                /* Conflict algorithm. (OE_Abort, etc) */
   84402 ){
   84403   TriggerStep *pStep;
   84404   Vdbe *v = pParse->pVdbe;
   84405   sqlite3 *db = pParse->db;
   84406 
   84407   assert( pParse->pTriggerTab && pParse->pToplevel );
   84408   assert( pStepList );
   84409   assert( v!=0 );
   84410   for(pStep=pStepList; pStep; pStep=pStep->pNext){
   84411     /* Figure out the ON CONFLICT policy that will be used for this step
   84412     ** of the trigger program. If the statement that caused this trigger
   84413     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
   84414     ** the ON CONFLICT policy that was specified as part of the trigger
   84415     ** step statement. Example:
   84416     **
   84417     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
   84418     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
   84419     **   END;
   84420     **
   84421     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
   84422     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
   84423     */
   84424     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
   84425 
   84426     switch( pStep->op ){
   84427       case TK_UPDATE: {
   84428         sqlite3Update(pParse,
   84429           targetSrcList(pParse, pStep),
   84430           sqlite3ExprListDup(db, pStep->pExprList, 0),
   84431           sqlite3ExprDup(db, pStep->pWhere, 0),
   84432           pParse->eOrconf
   84433         );
   84434         break;
   84435       }
   84436       case TK_INSERT: {
   84437         sqlite3Insert(pParse,
   84438           targetSrcList(pParse, pStep),
   84439           sqlite3ExprListDup(db, pStep->pExprList, 0),
   84440           sqlite3SelectDup(db, pStep->pSelect, 0),
   84441           sqlite3IdListDup(db, pStep->pIdList),
   84442           pParse->eOrconf
   84443         );
   84444         break;
   84445       }
   84446       case TK_DELETE: {
   84447         sqlite3DeleteFrom(pParse,
   84448           targetSrcList(pParse, pStep),
   84449           sqlite3ExprDup(db, pStep->pWhere, 0)
   84450         );
   84451         break;
   84452       }
   84453       default: assert( pStep->op==TK_SELECT ); {
   84454         SelectDest sDest;
   84455         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
   84456         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
   84457         sqlite3Select(pParse, pSelect, &sDest);
   84458         sqlite3SelectDelete(db, pSelect);
   84459         break;
   84460       }
   84461     }
   84462     if( pStep->op!=TK_SELECT ){
   84463       sqlite3VdbeAddOp0(v, OP_ResetCount);
   84464     }
   84465   }
   84466 
   84467   return 0;
   84468 }
   84469 
   84470 #ifdef SQLITE_DEBUG
   84471 /*
   84472 ** This function is used to add VdbeComment() annotations to a VDBE
   84473 ** program. It is not used in production code, only for debugging.
   84474 */
   84475 static const char *onErrorText(int onError){
   84476   switch( onError ){
   84477     case OE_Abort:    return "abort";
   84478     case OE_Rollback: return "rollback";
   84479     case OE_Fail:     return "fail";
   84480     case OE_Replace:  return "replace";
   84481     case OE_Ignore:   return "ignore";
   84482     case OE_Default:  return "default";
   84483   }
   84484   return "n/a";
   84485 }
   84486 #endif
   84487 
   84488 /*
   84489 ** Parse context structure pFrom has just been used to create a sub-vdbe
   84490 ** (trigger program). If an error has occurred, transfer error information
   84491 ** from pFrom to pTo.
   84492 */
   84493 static void transferParseError(Parse *pTo, Parse *pFrom){
   84494   assert( pFrom->zErrMsg==0 || pFrom->nErr );
   84495   assert( pTo->zErrMsg==0 || pTo->nErr );
   84496   if( pTo->nErr==0 ){
   84497     pTo->zErrMsg = pFrom->zErrMsg;
   84498     pTo->nErr = pFrom->nErr;
   84499   }else{
   84500     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
   84501   }
   84502 }
   84503 
   84504 /*
   84505 ** Create and populate a new TriggerPrg object with a sub-program
   84506 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
   84507 */
   84508 static TriggerPrg *codeRowTrigger(
   84509   Parse *pParse,       /* Current parse context */
   84510   Trigger *pTrigger,   /* Trigger to code */
   84511   Table *pTab,         /* The table pTrigger is attached to */
   84512   int orconf           /* ON CONFLICT policy to code trigger program with */
   84513 ){
   84514   Parse *pTop = sqlite3ParseToplevel(pParse);
   84515   sqlite3 *db = pParse->db;   /* Database handle */
   84516   TriggerPrg *pPrg;           /* Value to return */
   84517   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
   84518   Vdbe *v;                    /* Temporary VM */
   84519   NameContext sNC;            /* Name context for sub-vdbe */
   84520   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
   84521   Parse *pSubParse;           /* Parse context for sub-vdbe */
   84522   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
   84523 
   84524   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
   84525 
   84526   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
   84527   ** are freed if an error occurs, link them into the Parse.pTriggerPrg
   84528   ** list of the top-level Parse object sooner rather than later.  */
   84529   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
   84530   if( !pPrg ) return 0;
   84531   pPrg->pNext = pTop->pTriggerPrg;
   84532   pTop->pTriggerPrg = pPrg;
   84533   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
   84534   if( !pProgram ) return 0;
   84535   pProgram->nRef = 1;
   84536   pPrg->pTrigger = pTrigger;
   84537   pPrg->orconf = orconf;
   84538   pPrg->aColmask[0] = 0xffffffff;
   84539   pPrg->aColmask[1] = 0xffffffff;
   84540 
   84541   /* Allocate and populate a new Parse context to use for coding the
   84542   ** trigger sub-program.  */
   84543   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
   84544   if( !pSubParse ) return 0;
   84545   memset(&sNC, 0, sizeof(sNC));
   84546   sNC.pParse = pSubParse;
   84547   pSubParse->db = db;
   84548   pSubParse->pTriggerTab = pTab;
   84549   pSubParse->pToplevel = pTop;
   84550   pSubParse->zAuthContext = pTrigger->zName;
   84551   pSubParse->eTriggerOp = pTrigger->op;
   84552 
   84553   v = sqlite3GetVdbe(pSubParse);
   84554   if( v ){
   84555     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
   84556       pTrigger->zName, onErrorText(orconf),
   84557       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
   84558         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
   84559         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
   84560         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
   84561       pTab->zName
   84562     ));
   84563 #ifndef SQLITE_OMIT_TRACE
   84564     sqlite3VdbeChangeP4(v, -1,
   84565       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
   84566     );
   84567 #endif
   84568 
   84569     /* If one was specified, code the WHEN clause. If it evaluates to false
   84570     ** (or NULL) the sub-vdbe is immediately halted by jumping to the
   84571     ** OP_Halt inserted at the end of the program.  */
   84572     if( pTrigger->pWhen ){
   84573       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
   84574       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
   84575        && db->mallocFailed==0
   84576       ){
   84577         iEndTrigger = sqlite3VdbeMakeLabel(v);
   84578         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
   84579       }
   84580       sqlite3ExprDelete(db, pWhen);
   84581     }
   84582 
   84583     /* Code the trigger program into the sub-vdbe. */
   84584     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
   84585 
   84586     /* Insert an OP_Halt at the end of the sub-program. */
   84587     if( iEndTrigger ){
   84588       sqlite3VdbeResolveLabel(v, iEndTrigger);
   84589     }
   84590     sqlite3VdbeAddOp0(v, OP_Halt);
   84591     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
   84592 
   84593     transferParseError(pParse, pSubParse);
   84594     if( db->mallocFailed==0 ){
   84595       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
   84596     }
   84597     pProgram->nMem = pSubParse->nMem;
   84598     pProgram->nCsr = pSubParse->nTab;
   84599     pProgram->token = (void *)pTrigger;
   84600     pPrg->aColmask[0] = pSubParse->oldmask;
   84601     pPrg->aColmask[1] = pSubParse->newmask;
   84602     sqlite3VdbeDelete(v);
   84603   }
   84604 
   84605   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
   84606   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
   84607   sqlite3StackFree(db, pSubParse);
   84608 
   84609   return pPrg;
   84610 }
   84611 
   84612 /*
   84613 ** Return a pointer to a TriggerPrg object containing the sub-program for
   84614 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
   84615 ** TriggerPrg object exists, a new object is allocated and populated before
   84616 ** being returned.
   84617 */
   84618 static TriggerPrg *getRowTrigger(
   84619   Parse *pParse,       /* Current parse context */
   84620   Trigger *pTrigger,   /* Trigger to code */
   84621   Table *pTab,         /* The table trigger pTrigger is attached to */
   84622   int orconf           /* ON CONFLICT algorithm. */
   84623 ){
   84624   Parse *pRoot = sqlite3ParseToplevel(pParse);
   84625   TriggerPrg *pPrg;
   84626 
   84627   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
   84628 
   84629   /* It may be that this trigger has already been coded (or is in the
   84630   ** process of being coded). If this is the case, then an entry with
   84631   ** a matching TriggerPrg.pTrigger field will be present somewhere
   84632   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
   84633   for(pPrg=pRoot->pTriggerPrg;
   84634       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
   84635       pPrg=pPrg->pNext
   84636   );
   84637 
   84638   /* If an existing TriggerPrg could not be located, create a new one. */
   84639   if( !pPrg ){
   84640     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
   84641   }
   84642 
   84643   return pPrg;
   84644 }
   84645 
   84646 /*
   84647 ** Generate code for the trigger program associated with trigger p on
   84648 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
   84649 ** function are the same as those described in the header function for
   84650 ** sqlite3CodeRowTrigger()
   84651 */
   84652 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
   84653   Parse *pParse,       /* Parse context */
   84654   Trigger *p,          /* Trigger to code */
   84655   Table *pTab,         /* The table to code triggers from */
   84656   int reg,             /* Reg array containing OLD.* and NEW.* values */
   84657   int orconf,          /* ON CONFLICT policy */
   84658   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
   84659 ){
   84660   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
   84661   TriggerPrg *pPrg;
   84662   pPrg = getRowTrigger(pParse, p, pTab, orconf);
   84663   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
   84664 
   84665   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
   84666   ** is a pointer to the sub-vdbe containing the trigger program.  */
   84667   if( pPrg ){
   84668     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
   84669     pPrg->pProgram->nRef++;
   84670     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
   84671     VdbeComment(
   84672         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
   84673 
   84674     /* Set the P5 operand of the OP_Program instruction to non-zero if
   84675     ** recursive invocation of this trigger program is disallowed. Recursive
   84676     ** invocation is disallowed if (a) the sub-program is really a trigger,
   84677     ** not a foreign key action, and (b) the flag to enable recursive triggers
   84678     ** is clear.  */
   84679     sqlite3VdbeChangeP5(v, (u8)(p->zName && !(pParse->db->flags&SQLITE_RecTriggers)));
   84680   }
   84681 }
   84682 
   84683 /*
   84684 ** This is called to code the required FOR EACH ROW triggers for an operation
   84685 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
   84686 ** is given by the op paramater. The tr_tm parameter determines whether the
   84687 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
   84688 ** parameter pChanges is passed the list of columns being modified.
   84689 **
   84690 ** If there are no triggers that fire at the specified time for the specified
   84691 ** operation on pTab, this function is a no-op.
   84692 **
   84693 ** The reg argument is the address of the first in an array of registers
   84694 ** that contain the values substituted for the new.* and old.* references
   84695 ** in the trigger program. If N is the number of columns in table pTab
   84696 ** (a copy of pTab->nCol), then registers are populated as follows:
   84697 **
   84698 **   Register       Contains
   84699 **   ------------------------------------------------------
   84700 **   reg+0          OLD.rowid
   84701 **   reg+1          OLD.* value of left-most column of pTab
   84702 **   ...            ...
   84703 **   reg+N          OLD.* value of right-most column of pTab
   84704 **   reg+N+1        NEW.rowid
   84705 **   reg+N+2        OLD.* value of left-most column of pTab
   84706 **   ...            ...
   84707 **   reg+N+N+1      NEW.* value of right-most column of pTab
   84708 **
   84709 ** For ON DELETE triggers, the registers containing the NEW.* values will
   84710 ** never be accessed by the trigger program, so they are not allocated or
   84711 ** populated by the caller (there is no data to populate them with anyway).
   84712 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
   84713 ** are never accessed, and so are not allocated by the caller. So, for an
   84714 ** ON INSERT trigger, the value passed to this function as parameter reg
   84715 ** is not a readable register, although registers (reg+N) through
   84716 ** (reg+N+N+1) are.
   84717 **
   84718 ** Parameter orconf is the default conflict resolution algorithm for the
   84719 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
   84720 ** is the instruction that control should jump to if a trigger program
   84721 ** raises an IGNORE exception.
   84722 */
   84723 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
   84724   Parse *pParse,       /* Parse context */
   84725   Trigger *pTrigger,   /* List of triggers on table pTab */
   84726   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
   84727   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
   84728   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
   84729   Table *pTab,         /* The table to code triggers from */
   84730   int reg,             /* The first in an array of registers (see above) */
   84731   int orconf,          /* ON CONFLICT policy */
   84732   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
   84733 ){
   84734   Trigger *p;          /* Used to iterate through pTrigger list */
   84735 
   84736   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
   84737   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
   84738   assert( (op==TK_UPDATE)==(pChanges!=0) );
   84739 
   84740   for(p=pTrigger; p; p=p->pNext){
   84741 
   84742     /* Sanity checking:  The schema for the trigger and for the table are
   84743     ** always defined.  The trigger must be in the same schema as the table
   84744     ** or else it must be a TEMP trigger. */
   84745     assert( p->pSchema!=0 );
   84746     assert( p->pTabSchema!=0 );
   84747     assert( p->pSchema==p->pTabSchema
   84748          || p->pSchema==pParse->db->aDb[1].pSchema );
   84749 
   84750     /* Determine whether we should code this trigger */
   84751     if( p->op==op
   84752      && p->tr_tm==tr_tm
   84753      && checkColumnOverlap(p->pColumns, pChanges)
   84754     ){
   84755       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
   84756     }
   84757   }
   84758 }
   84759 
   84760 /*
   84761 ** Triggers may access values stored in the old.* or new.* pseudo-table.
   84762 ** This function returns a 32-bit bitmask indicating which columns of the
   84763 ** old.* or new.* tables actually are used by triggers. This information
   84764 ** may be used by the caller, for example, to avoid having to load the entire
   84765 ** old.* record into memory when executing an UPDATE or DELETE command.
   84766 **
   84767 ** Bit 0 of the returned mask is set if the left-most column of the
   84768 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
   84769 ** the second leftmost column value is required, and so on. If there
   84770 ** are more than 32 columns in the table, and at least one of the columns
   84771 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
   84772 **
   84773 ** It is not possible to determine if the old.rowid or new.rowid column is
   84774 ** accessed by triggers. The caller must always assume that it is.
   84775 **
   84776 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
   84777 ** applies to the old.* table. If 1, the new.* table.
   84778 **
   84779 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
   84780 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
   84781 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
   84782 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
   84783 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
   84784 */
   84785 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
   84786   Parse *pParse,       /* Parse context */
   84787   Trigger *pTrigger,   /* List of triggers on table pTab */
   84788   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
   84789   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
   84790   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   84791   Table *pTab,         /* The table to code triggers from */
   84792   int orconf           /* Default ON CONFLICT policy for trigger steps */
   84793 ){
   84794   const int op = pChanges ? TK_UPDATE : TK_DELETE;
   84795   u32 mask = 0;
   84796   Trigger *p;
   84797 
   84798   assert( isNew==1 || isNew==0 );
   84799   for(p=pTrigger; p; p=p->pNext){
   84800     if( p->op==op && (tr_tm&p->tr_tm)
   84801      && checkColumnOverlap(p->pColumns,pChanges)
   84802     ){
   84803       TriggerPrg *pPrg;
   84804       pPrg = getRowTrigger(pParse, p, pTab, orconf);
   84805       if( pPrg ){
   84806         mask |= pPrg->aColmask[isNew];
   84807       }
   84808     }
   84809   }
   84810 
   84811   return mask;
   84812 }
   84813 
   84814 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   84815 
   84816 /************** End of trigger.c *********************************************/
   84817 /************** Begin file update.c ******************************************/
   84818 /*
   84819 ** 2001 September 15
   84820 **
   84821 ** The author disclaims copyright to this source code.  In place of
   84822 ** a legal notice, here is a blessing:
   84823 **
   84824 **    May you do good and not evil.
   84825 **    May you find forgiveness for yourself and forgive others.
   84826 **    May you share freely, never taking more than you give.
   84827 **
   84828 *************************************************************************
   84829 ** This file contains C code routines that are called by the parser
   84830 ** to handle UPDATE statements.
   84831 */
   84832 
   84833 #ifndef SQLITE_OMIT_VIRTUALTABLE
   84834 /* Forward declaration */
   84835 static void updateVirtualTable(
   84836   Parse *pParse,       /* The parsing context */
   84837   SrcList *pSrc,       /* The virtual table to be modified */
   84838   Table *pTab,         /* The virtual table */
   84839   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
   84840   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
   84841   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
   84842   Expr *pWhere         /* WHERE clause of the UPDATE statement */
   84843 );
   84844 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   84845 
   84846 /*
   84847 ** The most recently coded instruction was an OP_Column to retrieve the
   84848 ** i-th column of table pTab. This routine sets the P4 parameter of the
   84849 ** OP_Column to the default value, if any.
   84850 **
   84851 ** The default value of a column is specified by a DEFAULT clause in the
   84852 ** column definition. This was either supplied by the user when the table
   84853 ** was created, or added later to the table definition by an ALTER TABLE
   84854 ** command. If the latter, then the row-records in the table btree on disk
   84855 ** may not contain a value for the column and the default value, taken
   84856 ** from the P4 parameter of the OP_Column instruction, is returned instead.
   84857 ** If the former, then all row-records are guaranteed to include a value
   84858 ** for the column and the P4 value is not required.
   84859 **
   84860 ** Column definitions created by an ALTER TABLE command may only have
   84861 ** literal default values specified: a number, null or a string. (If a more
   84862 ** complicated default expression value was provided, it is evaluated
   84863 ** when the ALTER TABLE is executed and one of the literal values written
   84864 ** into the sqlite_master table.)
   84865 **
   84866 ** Therefore, the P4 parameter is only required if the default value for
   84867 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
   84868 ** function is capable of transforming these types of expressions into
   84869 ** sqlite3_value objects.
   84870 **
   84871 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
   84872 ** on register iReg. This is used when an equivalent integer value is
   84873 ** stored in place of an 8-byte floating point value in order to save
   84874 ** space.
   84875 */
   84876 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
   84877   assert( pTab!=0 );
   84878   if( !pTab->pSelect ){
   84879     sqlite3_value *pValue;
   84880     u8 enc = ENC(sqlite3VdbeDb(v));
   84881     Column *pCol = &pTab->aCol[i];
   84882     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
   84883     assert( i<pTab->nCol );
   84884     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
   84885                          pCol->affinity, &pValue);
   84886     if( pValue ){
   84887       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
   84888     }
   84889 #ifndef SQLITE_OMIT_FLOATING_POINT
   84890     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
   84891       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
   84892     }
   84893 #endif
   84894   }
   84895 }
   84896 
   84897 /*
   84898 ** Process an UPDATE statement.
   84899 **
   84900 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
   84901 **          \_______/ \________/     \______/       \________________/
   84902 *            onError   pTabList      pChanges             pWhere
   84903 */
   84904 SQLITE_PRIVATE void sqlite3Update(
   84905   Parse *pParse,         /* The parser context */
   84906   SrcList *pTabList,     /* The table in which we should change things */
   84907   ExprList *pChanges,    /* Things to be changed */
   84908   Expr *pWhere,          /* The WHERE clause.  May be null */
   84909   int onError            /* How to handle constraint errors */
   84910 ){
   84911   int i, j;              /* Loop counters */
   84912   Table *pTab;           /* The table to be updated */
   84913   int addr = 0;          /* VDBE instruction address of the start of the loop */
   84914   WhereInfo *pWInfo;     /* Information about the WHERE clause */
   84915   Vdbe *v;               /* The virtual database engine */
   84916   Index *pIdx;           /* For looping over indices */
   84917   int nIdx;              /* Number of indices that need updating */
   84918   int iCur;              /* VDBE Cursor number of pTab */
   84919   sqlite3 *db;           /* The database structure */
   84920   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
   84921   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
   84922                          ** an expression for the i-th column of the table.
   84923                          ** aXRef[i]==-1 if the i-th column is not changed. */
   84924   int chngRowid;         /* True if the record number is being changed */
   84925   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
   84926   int openAll = 0;       /* True if all indices need to be opened */
   84927   AuthContext sContext;  /* The authorization context */
   84928   NameContext sNC;       /* The name-context to resolve expressions in */
   84929   int iDb;               /* Database containing the table being updated */
   84930   int okOnePass;         /* True for one-pass algorithm without the FIFO */
   84931   int hasFK;             /* True if foreign key processing is required */
   84932 
   84933 #ifndef SQLITE_OMIT_TRIGGER
   84934   int isView;            /* True when updating a view (INSTEAD OF trigger) */
   84935   Trigger *pTrigger;     /* List of triggers on pTab, if required */
   84936   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   84937 #endif
   84938   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
   84939 
   84940   /* Register Allocations */
   84941   int regRowCount = 0;   /* A count of rows changed */
   84942   int regOldRowid;       /* The old rowid */
   84943   int regNewRowid;       /* The new rowid */
   84944   int regNew;
   84945   int regOld = 0;
   84946   int regRowSet = 0;     /* Rowset of rows to be updated */
   84947   int regRec;            /* Register used for new table record to insert */
   84948 
   84949   memset(&sContext, 0, sizeof(sContext));
   84950   db = pParse->db;
   84951   if( pParse->nErr || db->mallocFailed ){
   84952     goto update_cleanup;
   84953   }
   84954   assert( pTabList->nSrc==1 );
   84955 
   84956   /* Locate the table which we want to update.
   84957   */
   84958   pTab = sqlite3SrcListLookup(pParse, pTabList);
   84959   if( pTab==0 ) goto update_cleanup;
   84960   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   84961 
   84962   /* Figure out if we have any triggers and if the table being
   84963   ** updated is a view.
   84964   */
   84965 #ifndef SQLITE_OMIT_TRIGGER
   84966   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
   84967   isView = pTab->pSelect!=0;
   84968   assert( pTrigger || tmask==0 );
   84969 #else
   84970 # define pTrigger 0
   84971 # define isView 0
   84972 # define tmask 0
   84973 #endif
   84974 #ifdef SQLITE_OMIT_VIEW
   84975 # undef isView
   84976 # define isView 0
   84977 #endif
   84978 
   84979   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   84980     goto update_cleanup;
   84981   }
   84982   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
   84983     goto update_cleanup;
   84984   }
   84985   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
   84986   if( aXRef==0 ) goto update_cleanup;
   84987   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
   84988 
   84989   /* Allocate a cursors for the main database table and for all indices.
   84990   ** The index cursors might not be used, but if they are used they
   84991   ** need to occur right after the database cursor.  So go ahead and
   84992   ** allocate enough space, just in case.
   84993   */
   84994   pTabList->a[0].iCursor = iCur = pParse->nTab++;
   84995   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   84996     pParse->nTab++;
   84997   }
   84998 
   84999   /* Initialize the name-context */
   85000   memset(&sNC, 0, sizeof(sNC));
   85001   sNC.pParse = pParse;
   85002   sNC.pSrcList = pTabList;
   85003 
   85004   /* Resolve the column names in all the expressions of the
   85005   ** of the UPDATE statement.  Also find the column index
   85006   ** for each column to be updated in the pChanges array.  For each
   85007   ** column to be updated, make sure we have authorization to change
   85008   ** that column.
   85009   */
   85010   chngRowid = 0;
   85011   for(i=0; i<pChanges->nExpr; i++){
   85012     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
   85013       goto update_cleanup;
   85014     }
   85015     for(j=0; j<pTab->nCol; j++){
   85016       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
   85017         if( j==pTab->iPKey ){
   85018           chngRowid = 1;
   85019           pRowidExpr = pChanges->a[i].pExpr;
   85020         }
   85021         aXRef[j] = i;
   85022         break;
   85023       }
   85024     }
   85025     if( j>=pTab->nCol ){
   85026       if( sqlite3IsRowid(pChanges->a[i].zName) ){
   85027         chngRowid = 1;
   85028         pRowidExpr = pChanges->a[i].pExpr;
   85029       }else{
   85030         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
   85031         goto update_cleanup;
   85032       }
   85033     }
   85034 #ifndef SQLITE_OMIT_AUTHORIZATION
   85035     {
   85036       int rc;
   85037       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
   85038                            pTab->aCol[j].zName, db->aDb[iDb].zName);
   85039       if( rc==SQLITE_DENY ){
   85040         goto update_cleanup;
   85041       }else if( rc==SQLITE_IGNORE ){
   85042         aXRef[j] = -1;
   85043       }
   85044     }
   85045 #endif
   85046   }
   85047 
   85048   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
   85049 
   85050   /* Allocate memory for the array aRegIdx[].  There is one entry in the
   85051   ** array for each index associated with table being updated.  Fill in
   85052   ** the value with a register number for indices that are to be used
   85053   ** and with zero for unused indices.
   85054   */
   85055   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
   85056   if( nIdx>0 ){
   85057     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
   85058     if( aRegIdx==0 ) goto update_cleanup;
   85059   }
   85060   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   85061     int reg;
   85062     if( chngRowid ){
   85063       reg = ++pParse->nMem;
   85064     }else{
   85065       reg = 0;
   85066       for(i=0; i<pIdx->nColumn; i++){
   85067         if( aXRef[pIdx->aiColumn[i]]>=0 ){
   85068           reg = ++pParse->nMem;
   85069           break;
   85070         }
   85071       }
   85072     }
   85073     aRegIdx[j] = reg;
   85074   }
   85075 
   85076   /* Begin generating code. */
   85077   v = sqlite3GetVdbe(pParse);
   85078   if( v==0 ) goto update_cleanup;
   85079   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   85080   sqlite3BeginWriteOperation(pParse, 1, iDb);
   85081 
   85082 #ifndef SQLITE_OMIT_VIRTUALTABLE
   85083   /* Virtual tables must be handled separately */
   85084   if( IsVirtual(pTab) ){
   85085     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
   85086                        pWhere);
   85087     pWhere = 0;
   85088     pTabList = 0;
   85089     goto update_cleanup;
   85090   }
   85091 #endif
   85092 
   85093   /* Allocate required registers. */
   85094   regOldRowid = regNewRowid = ++pParse->nMem;
   85095   if( pTrigger || hasFK ){
   85096     regOld = pParse->nMem + 1;
   85097     pParse->nMem += pTab->nCol;
   85098   }
   85099   if( chngRowid || pTrigger || hasFK ){
   85100     regNewRowid = ++pParse->nMem;
   85101   }
   85102   regNew = pParse->nMem + 1;
   85103   pParse->nMem += pTab->nCol;
   85104   regRec = ++pParse->nMem;
   85105 
   85106   /* Start the view context. */
   85107   if( isView ){
   85108     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
   85109   }
   85110 
   85111   /* If we are trying to update a view, realize that view into
   85112   ** a ephemeral table.
   85113   */
   85114 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   85115   if( isView ){
   85116     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
   85117   }
   85118 #endif
   85119 
   85120   /* Resolve the column names in all the expressions in the
   85121   ** WHERE clause.
   85122   */
   85123   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
   85124     goto update_cleanup;
   85125   }
   85126 
   85127   /* Begin the database scan
   85128   */
   85129   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
   85130   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
   85131   if( pWInfo==0 ) goto update_cleanup;
   85132   okOnePass = pWInfo->okOnePass;
   85133 
   85134   /* Remember the rowid of every item to be updated.
   85135   */
   85136   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
   85137   if( !okOnePass ){
   85138     regRowSet = ++pParse->nMem;
   85139     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
   85140   }
   85141 
   85142   /* End the database scan loop.
   85143   */
   85144   sqlite3WhereEnd(pWInfo);
   85145 
   85146   /* Initialize the count of updated rows
   85147   */
   85148   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
   85149     regRowCount = ++pParse->nMem;
   85150     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   85151   }
   85152 
   85153   if( !isView ){
   85154     /*
   85155     ** Open every index that needs updating.  Note that if any
   85156     ** index could potentially invoke a REPLACE conflict resolution
   85157     ** action, then we need to open all indices because we might need
   85158     ** to be deleting some records.
   85159     */
   85160     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
   85161     if( onError==OE_Replace ){
   85162       openAll = 1;
   85163     }else{
   85164       openAll = 0;
   85165       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   85166         if( pIdx->onError==OE_Replace ){
   85167           openAll = 1;
   85168           break;
   85169         }
   85170       }
   85171     }
   85172     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   85173       if( openAll || aRegIdx[i]>0 ){
   85174         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   85175         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
   85176                        (char*)pKey, P4_KEYINFO_HANDOFF);
   85177         assert( pParse->nTab>iCur+i+1 );
   85178       }
   85179     }
   85180   }
   85181 
   85182   /* Top of the update loop */
   85183   if( okOnePass ){
   85184     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
   85185     addr = sqlite3VdbeAddOp0(v, OP_Goto);
   85186     sqlite3VdbeJumpHere(v, a1);
   85187   }else{
   85188     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
   85189   }
   85190 
   85191   /* Make cursor iCur point to the record that is being updated. If
   85192   ** this record does not exist for some reason (deleted by a trigger,
   85193   ** for example, then jump to the next iteration of the RowSet loop.  */
   85194   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
   85195 
   85196   /* If the record number will change, set register regNewRowid to
   85197   ** contain the new value. If the record number is not being modified,
   85198   ** then regNewRowid is the same register as regOldRowid, which is
   85199   ** already populated.  */
   85200   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
   85201   if( chngRowid ){
   85202     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
   85203     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
   85204   }
   85205 
   85206   /* If there are triggers on this table, populate an array of registers
   85207   ** with the required old.* column data.  */
   85208   if( hasFK || pTrigger ){
   85209     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
   85210     oldmask |= sqlite3TriggerColmask(pParse,
   85211         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
   85212     );
   85213     for(i=0; i<pTab->nCol; i++){
   85214       if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
   85215         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regOld+i);
   85216         sqlite3ColumnDefault(v, pTab, i, regOld+i);
   85217       }else{
   85218         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
   85219       }
   85220     }
   85221     if( chngRowid==0 ){
   85222       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
   85223     }
   85224   }
   85225 
   85226   /* Populate the array of registers beginning at regNew with the new
   85227   ** row data. This array is used to check constaints, create the new
   85228   ** table and index records, and as the values for any new.* references
   85229   ** made by triggers.
   85230   **
   85231   ** If there are one or more BEFORE triggers, then do not populate the
   85232   ** registers associated with columns that are (a) not modified by
   85233   ** this UPDATE statement and (b) not accessed by new.* references. The
   85234   ** values for registers not modified by the UPDATE must be reloaded from
   85235   ** the database after the BEFORE triggers are fired anyway (as the trigger
   85236   ** may have modified them). So not loading those that are not going to
   85237   ** be used eliminates some redundant opcodes.
   85238   */
   85239   newmask = sqlite3TriggerColmask(
   85240       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
   85241   );
   85242   for(i=0; i<pTab->nCol; i++){
   85243     if( i==pTab->iPKey ){
   85244       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
   85245     }else{
   85246       j = aXRef[i];
   85247       if( j>=0 ){
   85248         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
   85249       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
   85250         /* This branch loads the value of a column that will not be changed
   85251         ** into a register. This is done if there are no BEFORE triggers, or
   85252         ** if there are one or more BEFORE triggers that use this value via
   85253         ** a new.* reference in a trigger program.
   85254         */
   85255         testcase( i==31 );
   85256         testcase( i==32 );
   85257         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
   85258         sqlite3ColumnDefault(v, pTab, i, regNew+i);
   85259       }
   85260     }
   85261   }
   85262 
   85263   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
   85264   ** verified. One could argue that this is wrong.
   85265   */
   85266   if( tmask&TRIGGER_BEFORE ){
   85267     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
   85268     sqlite3TableAffinityStr(v, pTab);
   85269     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
   85270         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
   85271 
   85272     /* The row-trigger may have deleted the row being updated. In this
   85273     ** case, jump to the next row. No updates or AFTER triggers are
   85274     ** required. This behaviour - what happens when the row being updated
   85275     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
   85276     ** documentation.
   85277     */
   85278     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
   85279 
   85280     /* If it did not delete it, the row-trigger may still have modified
   85281     ** some of the columns of the row being updated. Load the values for
   85282     ** all columns not modified by the update statement into their
   85283     ** registers in case this has happened.
   85284     */
   85285     for(i=0; i<pTab->nCol; i++){
   85286       if( aXRef[i]<0 && i!=pTab->iPKey ){
   85287         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
   85288         sqlite3ColumnDefault(v, pTab, i, regNew+i);
   85289       }
   85290     }
   85291   }
   85292 
   85293   if( !isView ){
   85294     int j1;                       /* Address of jump instruction */
   85295 
   85296     /* Do constraint checks. */
   85297     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
   85298         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
   85299 
   85300     /* Do FK constraint checks. */
   85301     if( hasFK ){
   85302       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
   85303     }
   85304 
   85305     /* Delete the index entries associated with the current record.  */
   85306     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
   85307     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
   85308 
   85309     /* If changing the record number, delete the old record.  */
   85310     if( hasFK || chngRowid ){
   85311       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
   85312     }
   85313     sqlite3VdbeJumpHere(v, j1);
   85314 
   85315     if( hasFK ){
   85316       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
   85317     }
   85318 
   85319     /* Insert the new index entries and the new record. */
   85320     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
   85321 
   85322     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
   85323     ** handle rows (possibly in other tables) that refer via a foreign key
   85324     ** to the row just updated. */
   85325     if( hasFK ){
   85326       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
   85327     }
   85328   }
   85329 
   85330   /* Increment the row counter
   85331   */
   85332   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
   85333     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
   85334   }
   85335 
   85336   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
   85337       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
   85338 
   85339   /* Repeat the above with the next record to be updated, until
   85340   ** all record selected by the WHERE clause have been updated.
   85341   */
   85342   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
   85343   sqlite3VdbeJumpHere(v, addr);
   85344 
   85345   /* Close all tables */
   85346   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   85347     if( openAll || aRegIdx[i]>0 ){
   85348       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
   85349     }
   85350   }
   85351   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
   85352 
   85353   /* Update the sqlite_sequence table by storing the content of the
   85354   ** maximum rowid counter values recorded while inserting into
   85355   ** autoincrement tables.
   85356   */
   85357   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   85358     sqlite3AutoincrementEnd(pParse);
   85359   }
   85360 
   85361   /*
   85362   ** Return the number of rows that were changed. If this routine is
   85363   ** generating code because of a call to sqlite3NestedParse(), do not
   85364   ** invoke the callback function.
   85365   */
   85366   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
   85367     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
   85368     sqlite3VdbeSetNumCols(v, 1);
   85369     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
   85370   }
   85371 
   85372 update_cleanup:
   85373   sqlite3AuthContextPop(&sContext);
   85374   sqlite3DbFree(db, aRegIdx);
   85375   sqlite3DbFree(db, aXRef);
   85376   sqlite3SrcListDelete(db, pTabList);
   85377   sqlite3ExprListDelete(db, pChanges);
   85378   sqlite3ExprDelete(db, pWhere);
   85379   return;
   85380 }
   85381 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   85382 ** thely may interfere with compilation of other functions in this file
   85383 ** (or in another file, if this file becomes part of the amalgamation).  */
   85384 #ifdef isView
   85385  #undef isView
   85386 #endif
   85387 #ifdef pTrigger
   85388  #undef pTrigger
   85389 #endif
   85390 
   85391 #ifndef SQLITE_OMIT_VIRTUALTABLE
   85392 /*
   85393 ** Generate code for an UPDATE of a virtual table.
   85394 **
   85395 ** The strategy is that we create an ephemerial table that contains
   85396 ** for each row to be changed:
   85397 **
   85398 **   (A)  The original rowid of that row.
   85399 **   (B)  The revised rowid for the row. (note1)
   85400 **   (C)  The content of every column in the row.
   85401 **
   85402 ** Then we loop over this ephemeral table and for each row in
   85403 ** the ephermeral table call VUpdate.
   85404 **
   85405 ** When finished, drop the ephemeral table.
   85406 **
   85407 ** (note1) Actually, if we know in advance that (A) is always the same
   85408 ** as (B) we only store (A), then duplicate (A) when pulling
   85409 ** it out of the ephemeral table before calling VUpdate.
   85410 */
   85411 static void updateVirtualTable(
   85412   Parse *pParse,       /* The parsing context */
   85413   SrcList *pSrc,       /* The virtual table to be modified */
   85414   Table *pTab,         /* The virtual table */
   85415   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
   85416   Expr *pRowid,        /* Expression used to recompute the rowid */
   85417   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
   85418   Expr *pWhere         /* WHERE clause of the UPDATE statement */
   85419 ){
   85420   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
   85421   ExprList *pEList = 0;     /* The result set of the SELECT statement */
   85422   Select *pSelect = 0;      /* The SELECT statement */
   85423   Expr *pExpr;              /* Temporary expression */
   85424   int ephemTab;             /* Table holding the result of the SELECT */
   85425   int i;                    /* Loop counter */
   85426   int addr;                 /* Address of top of loop */
   85427   int iReg;                 /* First register in set passed to OP_VUpdate */
   85428   sqlite3 *db = pParse->db; /* Database connection */
   85429   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
   85430   SelectDest dest;
   85431 
   85432   /* Construct the SELECT statement that will find the new values for
   85433   ** all updated rows.
   85434   */
   85435   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
   85436   if( pRowid ){
   85437     pEList = sqlite3ExprListAppend(pParse, pEList,
   85438                                    sqlite3ExprDup(db, pRowid, 0));
   85439   }
   85440   assert( pTab->iPKey<0 );
   85441   for(i=0; i<pTab->nCol; i++){
   85442     if( aXRef[i]>=0 ){
   85443       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
   85444     }else{
   85445       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
   85446     }
   85447     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
   85448   }
   85449   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
   85450 
   85451   /* Create the ephemeral table into which the update results will
   85452   ** be stored.
   85453   */
   85454   assert( v );
   85455   ephemTab = pParse->nTab++;
   85456   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
   85457 
   85458   /* fill the ephemeral table
   85459   */
   85460   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
   85461   sqlite3Select(pParse, pSelect, &dest);
   85462 
   85463   /* Generate code to scan the ephemeral table and call VUpdate. */
   85464   iReg = ++pParse->nMem;
   85465   pParse->nMem += pTab->nCol+1;
   85466   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
   85467   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
   85468   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
   85469   for(i=0; i<pTab->nCol; i++){
   85470     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
   85471   }
   85472   sqlite3VtabMakeWritable(pParse, pTab);
   85473   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
   85474   sqlite3MayAbort(pParse);
   85475   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
   85476   sqlite3VdbeJumpHere(v, addr);
   85477   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
   85478 
   85479   /* Cleanup */
   85480   sqlite3SelectDelete(db, pSelect);
   85481 }
   85482 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   85483 
   85484 /************** End of update.c **********************************************/
   85485 /************** Begin file vacuum.c ******************************************/
   85486 /*
   85487 ** 2003 April 6
   85488 **
   85489 ** The author disclaims copyright to this source code.  In place of
   85490 ** a legal notice, here is a blessing:
   85491 **
   85492 **    May you do good and not evil.
   85493 **    May you find forgiveness for yourself and forgive others.
   85494 **    May you share freely, never taking more than you give.
   85495 **
   85496 *************************************************************************
   85497 ** This file contains code used to implement the VACUUM command.
   85498 **
   85499 ** Most of the code in this file may be omitted by defining the
   85500 ** SQLITE_OMIT_VACUUM macro.
   85501 */
   85502 
   85503 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
   85504 /*
   85505 ** Finalize a prepared statement.  If there was an error, store the
   85506 ** text of the error message in *pzErrMsg.  Return the result code.
   85507 */
   85508 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
   85509   int rc;
   85510   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
   85511   if( rc ){
   85512     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
   85513   }
   85514   return rc;
   85515 }
   85516 
   85517 /*
   85518 ** Execute zSql on database db. Return an error code.
   85519 */
   85520 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
   85521   sqlite3_stmt *pStmt;
   85522   VVA_ONLY( int rc; )
   85523   if( !zSql ){
   85524     return SQLITE_NOMEM;
   85525   }
   85526   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
   85527     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
   85528     return sqlite3_errcode(db);
   85529   }
   85530   VVA_ONLY( rc = ) sqlite3_step(pStmt);
   85531   assert( rc!=SQLITE_ROW );
   85532   return vacuumFinalize(db, pStmt, pzErrMsg);
   85533 }
   85534 
   85535 /*
   85536 ** Execute zSql on database db. The statement returns exactly
   85537 ** one column. Execute this as SQL on the same database.
   85538 */
   85539 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
   85540   sqlite3_stmt *pStmt;
   85541   int rc;
   85542 
   85543   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   85544   if( rc!=SQLITE_OK ) return rc;
   85545 
   85546   while( SQLITE_ROW==sqlite3_step(pStmt) ){
   85547     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
   85548     if( rc!=SQLITE_OK ){
   85549       vacuumFinalize(db, pStmt, pzErrMsg);
   85550       return rc;
   85551     }
   85552   }
   85553 
   85554   return vacuumFinalize(db, pStmt, pzErrMsg);
   85555 }
   85556 
   85557 /*
   85558 ** The non-standard VACUUM command is used to clean up the database,
   85559 ** collapse free space, etc.  It is modelled after the VACUUM command
   85560 ** in PostgreSQL.
   85561 **
   85562 ** In version 1.0.x of SQLite, the VACUUM command would call
   85563 ** gdbm_reorganize() on all the database tables.  But beginning
   85564 ** with 2.0.0, SQLite no longer uses GDBM so this command has
   85565 ** become a no-op.
   85566 */
   85567 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
   85568   Vdbe *v = sqlite3GetVdbe(pParse);
   85569   if( v ){
   85570     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
   85571   }
   85572   return;
   85573 }
   85574 
   85575 /*
   85576 ** This routine implements the OP_Vacuum opcode of the VDBE.
   85577 */
   85578 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
   85579   int rc = SQLITE_OK;     /* Return code from service routines */
   85580   Btree *pMain;           /* The database being vacuumed */
   85581   Btree *pTemp;           /* The temporary database we vacuum into */
   85582   char *zSql = 0;         /* SQL statements */
   85583   int saved_flags;        /* Saved value of the db->flags */
   85584   int saved_nChange;      /* Saved value of db->nChange */
   85585   int saved_nTotalChange; /* Saved value of db->nTotalChange */
   85586   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
   85587   Db *pDb = 0;            /* Database to detach at end of vacuum */
   85588   int isMemDb;            /* True if vacuuming a :memory: database */
   85589   int nRes;
   85590 
   85591   if( !db->autoCommit ){
   85592     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
   85593     return SQLITE_ERROR;
   85594   }
   85595 
   85596   /* Save the current value of the database flags so that it can be
   85597   ** restored before returning. Then set the writable-schema flag, and
   85598   ** disable CHECK and foreign key constraints.  */
   85599   saved_flags = db->flags;
   85600   saved_nChange = db->nChange;
   85601   saved_nTotalChange = db->nTotalChange;
   85602   saved_xTrace = db->xTrace;
   85603   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
   85604   db->flags &= ~SQLITE_ForeignKeys;
   85605   db->xTrace = 0;
   85606 
   85607   pMain = db->aDb[0].pBt;
   85608   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
   85609 
   85610   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
   85611   ** can be set to 'off' for this file, as it is not recovered if a crash
   85612   ** occurs anyway. The integrity of the database is maintained by a
   85613   ** (possibly synchronous) transaction opened on the main database before
   85614   ** sqlite3BtreeCopyFile() is called.
   85615   **
   85616   ** An optimisation would be to use a non-journaled pager.
   85617   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
   85618   ** that actually made the VACUUM run slower.  Very little journalling
   85619   ** actually occurs when doing a vacuum since the vacuum_db is initially
   85620   ** empty.  Only the journal header is written.  Apparently it takes more
   85621   ** time to parse and run the PRAGMA to turn journalling off than it does
   85622   ** to write the journal header file.
   85623   */
   85624   if( sqlite3TempInMemory(db) ){
   85625     zSql = "ATTACH ':memory:' AS vacuum_db;";
   85626   }else{
   85627     zSql = "ATTACH '' AS vacuum_db;";
   85628   }
   85629   rc = execSql(db, pzErrMsg, zSql);
   85630   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   85631   pDb = &db->aDb[db->nDb-1];
   85632   assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
   85633   pTemp = db->aDb[db->nDb-1].pBt;
   85634 
   85635   /* The call to execSql() to attach the temp database has left the file
   85636   ** locked (as there was more than one active statement when the transaction
   85637   ** to read the schema was concluded. Unlock it here so that this doesn't
   85638   ** cause problems for the call to BtreeSetPageSize() below.  */
   85639   sqlite3BtreeCommit(pTemp);
   85640 
   85641   nRes = sqlite3BtreeGetReserve(pMain);
   85642 
   85643   /* A VACUUM cannot change the pagesize of an encrypted database. */
   85644 #ifdef SQLITE_HAS_CODEC
   85645   if( db->nextPagesize ){
   85646     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
   85647     int nKey;
   85648     char *zKey;
   85649     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
   85650     if( nKey ) db->nextPagesize = 0;
   85651   }
   85652 #endif
   85653 
   85654   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
   85655    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
   85656    || NEVER(db->mallocFailed)
   85657   ){
   85658     rc = SQLITE_NOMEM;
   85659     goto end_of_vacuum;
   85660   }
   85661   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
   85662   if( rc!=SQLITE_OK ){
   85663     goto end_of_vacuum;
   85664   }
   85665 
   85666 #ifndef SQLITE_OMIT_AUTOVACUUM
   85667   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
   85668                                            sqlite3BtreeGetAutoVacuum(pMain));
   85669 #endif
   85670 
   85671   /* Begin a transaction */
   85672   rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
   85673   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   85674 
   85675   /* Query the schema of the main database. Create a mirror schema
   85676   ** in the temporary database.
   85677   */
   85678   rc = execExecSql(db, pzErrMsg,
   85679       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
   85680       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
   85681       "   AND rootpage>0"
   85682   );
   85683   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   85684   rc = execExecSql(db, pzErrMsg,
   85685       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
   85686       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
   85687   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   85688   rc = execExecSql(db, pzErrMsg,
   85689       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
   85690       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
   85691   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   85692 
   85693   /* Loop through the tables in the main database. For each, do
   85694   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
   85695   ** the contents to the temporary database.
   85696   */
   85697   rc = execExecSql(db, pzErrMsg,
   85698       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
   85699       "|| ' SELECT * FROM main.' || quote(name) || ';'"
   85700       "FROM main.sqlite_master "
   85701       "WHERE type = 'table' AND name!='sqlite_sequence' "
   85702       "  AND rootpage>0"
   85703   );
   85704   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   85705 
   85706   /* Copy over the sequence table
   85707   */
   85708   rc = execExecSql(db, pzErrMsg,
   85709       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
   85710       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
   85711   );
   85712   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   85713   rc = execExecSql(db, pzErrMsg,
   85714       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
   85715       "|| ' SELECT * FROM main.' || quote(name) || ';' "
   85716       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
   85717   );
   85718   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   85719 
   85720 
   85721   /* Copy the triggers, views, and virtual tables from the main database
   85722   ** over to the temporary database.  None of these objects has any
   85723   ** associated storage, so all we have to do is copy their entries
   85724   ** from the SQLITE_MASTER table.
   85725   */
   85726   rc = execSql(db, pzErrMsg,
   85727       "INSERT INTO vacuum_db.sqlite_master "
   85728       "  SELECT type, name, tbl_name, rootpage, sql"
   85729       "    FROM main.sqlite_master"
   85730       "   WHERE type='view' OR type='trigger'"
   85731       "      OR (type='table' AND rootpage=0)"
   85732   );
   85733   if( rc ) goto end_of_vacuum;
   85734 
   85735   /* At this point, unless the main db was completely empty, there is now a
   85736   ** transaction open on the vacuum database, but not on the main database.
   85737   ** Open a btree level transaction on the main database. This allows a
   85738   ** call to sqlite3BtreeCopyFile(). The main database btree level
   85739   ** transaction is then committed, so the SQL level never knows it was
   85740   ** opened for writing. This way, the SQL transaction used to create the
   85741   ** temporary database never needs to be committed.
   85742   */
   85743   {
   85744     u32 meta;
   85745     int i;
   85746 
   85747     /* This array determines which meta meta values are preserved in the
   85748     ** vacuum.  Even entries are the meta value number and odd entries
   85749     ** are an increment to apply to the meta value after the vacuum.
   85750     ** The increment is used to increase the schema cookie so that other
   85751     ** connections to the same database will know to reread the schema.
   85752     */
   85753     static const unsigned char aCopy[] = {
   85754        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
   85755        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
   85756        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
   85757        BTREE_USER_VERSION,       0,  /* Preserve the user version */
   85758     };
   85759 
   85760     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
   85761     assert( 1==sqlite3BtreeIsInTrans(pMain) );
   85762 
   85763     /* Copy Btree meta values */
   85764     for(i=0; i<ArraySize(aCopy); i+=2){
   85765       /* GetMeta() and UpdateMeta() cannot fail in this context because
   85766       ** we already have page 1 loaded into cache and marked dirty. */
   85767       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
   85768       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
   85769       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
   85770     }
   85771 
   85772     rc = sqlite3BtreeCopyFile(pMain, pTemp);
   85773     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   85774     rc = sqlite3BtreeCommit(pTemp);
   85775     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   85776 #ifndef SQLITE_OMIT_AUTOVACUUM
   85777     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
   85778 #endif
   85779   }
   85780 
   85781   assert( rc==SQLITE_OK );
   85782   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
   85783 
   85784 end_of_vacuum:
   85785   /* Restore the original value of db->flags */
   85786   db->flags = saved_flags;
   85787   db->nChange = saved_nChange;
   85788   db->nTotalChange = saved_nTotalChange;
   85789   db->xTrace = saved_xTrace;
   85790 
   85791   /* Currently there is an SQL level transaction open on the vacuum
   85792   ** database. No locks are held on any other files (since the main file
   85793   ** was committed at the btree level). So it safe to end the transaction
   85794   ** by manually setting the autoCommit flag to true and detaching the
   85795   ** vacuum database. The vacuum_db journal file is deleted when the pager
   85796   ** is closed by the DETACH.
   85797   */
   85798   db->autoCommit = 1;
   85799 
   85800   if( pDb ){
   85801     sqlite3BtreeClose(pDb->pBt);
   85802     pDb->pBt = 0;
   85803     pDb->pSchema = 0;
   85804   }
   85805 
   85806   sqlite3ResetInternalSchema(db, 0);
   85807 
   85808   return rc;
   85809 }
   85810 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
   85811 
   85812 /************** End of vacuum.c **********************************************/
   85813 /************** Begin file vtab.c ********************************************/
   85814 /*
   85815 ** 2006 June 10
   85816 **
   85817 ** The author disclaims copyright to this source code.  In place of
   85818 ** a legal notice, here is a blessing:
   85819 **
   85820 **    May you do good and not evil.
   85821 **    May you find forgiveness for yourself and forgive others.
   85822 **    May you share freely, never taking more than you give.
   85823 **
   85824 *************************************************************************
   85825 ** This file contains code used to help implement virtual tables.
   85826 */
   85827 #ifndef SQLITE_OMIT_VIRTUALTABLE
   85828 
   85829 /*
   85830 ** The actual function that does the work of creating a new module.
   85831 ** This function implements the sqlite3_create_module() and
   85832 ** sqlite3_create_module_v2() interfaces.
   85833 */
   85834 static int createModule(
   85835   sqlite3 *db,                    /* Database in which module is registered */
   85836   const char *zName,              /* Name assigned to this module */
   85837   const sqlite3_module *pModule,  /* The definition of the module */
   85838   void *pAux,                     /* Context pointer for xCreate/xConnect */
   85839   void (*xDestroy)(void *)        /* Module destructor function */
   85840 ){
   85841   int rc, nName;
   85842   Module *pMod;
   85843 
   85844   sqlite3_mutex_enter(db->mutex);
   85845   nName = sqlite3Strlen30(zName);
   85846   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
   85847   if( pMod ){
   85848     Module *pDel;
   85849     char *zCopy = (char *)(&pMod[1]);
   85850     memcpy(zCopy, zName, nName+1);
   85851     pMod->zName = zCopy;
   85852     pMod->pModule = pModule;
   85853     pMod->pAux = pAux;
   85854     pMod->xDestroy = xDestroy;
   85855     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
   85856     if( pDel && pDel->xDestroy ){
   85857       pDel->xDestroy(pDel->pAux);
   85858     }
   85859     sqlite3DbFree(db, pDel);
   85860     if( pDel==pMod ){
   85861       db->mallocFailed = 1;
   85862     }
   85863     sqlite3ResetInternalSchema(db, 0);
   85864   }else if( xDestroy ){
   85865     xDestroy(pAux);
   85866   }
   85867   rc = sqlite3ApiExit(db, SQLITE_OK);
   85868   sqlite3_mutex_leave(db->mutex);
   85869   return rc;
   85870 }
   85871 
   85872 
   85873 /*
   85874 ** External API function used to create a new virtual-table module.
   85875 */
   85876 SQLITE_API int sqlite3_create_module(
   85877   sqlite3 *db,                    /* Database in which module is registered */
   85878   const char *zName,              /* Name assigned to this module */
   85879   const sqlite3_module *pModule,  /* The definition of the module */
   85880   void *pAux                      /* Context pointer for xCreate/xConnect */
   85881 ){
   85882   return createModule(db, zName, pModule, pAux, 0);
   85883 }
   85884 
   85885 /*
   85886 ** External API function used to create a new virtual-table module.
   85887 */
   85888 SQLITE_API int sqlite3_create_module_v2(
   85889   sqlite3 *db,                    /* Database in which module is registered */
   85890   const char *zName,              /* Name assigned to this module */
   85891   const sqlite3_module *pModule,  /* The definition of the module */
   85892   void *pAux,                     /* Context pointer for xCreate/xConnect */
   85893   void (*xDestroy)(void *)        /* Module destructor function */
   85894 ){
   85895   return createModule(db, zName, pModule, pAux, xDestroy);
   85896 }
   85897 
   85898 /*
   85899 ** Lock the virtual table so that it cannot be disconnected.
   85900 ** Locks nest.  Every lock should have a corresponding unlock.
   85901 ** If an unlock is omitted, resources leaks will occur.
   85902 **
   85903 ** If a disconnect is attempted while a virtual table is locked,
   85904 ** the disconnect is deferred until all locks have been removed.
   85905 */
   85906 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
   85907   pVTab->nRef++;
   85908 }
   85909 
   85910 
   85911 /*
   85912 ** pTab is a pointer to a Table structure representing a virtual-table.
   85913 ** Return a pointer to the VTable object used by connection db to access
   85914 ** this virtual-table, if one has been created, or NULL otherwise.
   85915 */
   85916 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
   85917   VTable *pVtab;
   85918   assert( IsVirtual(pTab) );
   85919   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
   85920   return pVtab;
   85921 }
   85922 
   85923 /*
   85924 ** Decrement the ref-count on a virtual table object. When the ref-count
   85925 ** reaches zero, call the xDisconnect() method to delete the object.
   85926 */
   85927 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
   85928   sqlite3 *db = pVTab->db;
   85929 
   85930   assert( db );
   85931   assert( pVTab->nRef>0 );
   85932   assert( sqlite3SafetyCheckOk(db) );
   85933 
   85934   pVTab->nRef--;
   85935   if( pVTab->nRef==0 ){
   85936     sqlite3_vtab *p = pVTab->pVtab;
   85937     if( p ){
   85938       p->pModule->xDisconnect(p);
   85939     }
   85940     sqlite3DbFree(db, pVTab);
   85941   }
   85942 }
   85943 
   85944 /*
   85945 ** Table p is a virtual table. This function moves all elements in the
   85946 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
   85947 ** database connections to be disconnected at the next opportunity.
   85948 ** Except, if argument db is not NULL, then the entry associated with
   85949 ** connection db is left in the p->pVTable list.
   85950 */
   85951 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
   85952   VTable *pRet = 0;
   85953   VTable *pVTable = p->pVTable;
   85954   p->pVTable = 0;
   85955 
   85956   /* Assert that the mutex (if any) associated with the BtShared database
   85957   ** that contains table p is held by the caller. See header comments
   85958   ** above function sqlite3VtabUnlockList() for an explanation of why
   85959   ** this makes it safe to access the sqlite3.pDisconnect list of any
   85960   ** database connection that may have an entry in the p->pVTable list.  */
   85961   assert( db==0 ||
   85962     sqlite3BtreeHoldsMutex(db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].pBt)
   85963   );
   85964 
   85965   while( pVTable ){
   85966     sqlite3 *db2 = pVTable->db;
   85967     VTable *pNext = pVTable->pNext;
   85968     assert( db2 );
   85969     if( db2==db ){
   85970       pRet = pVTable;
   85971       p->pVTable = pRet;
   85972       pRet->pNext = 0;
   85973     }else{
   85974       pVTable->pNext = db2->pDisconnect;
   85975       db2->pDisconnect = pVTable;
   85976     }
   85977     pVTable = pNext;
   85978   }
   85979 
   85980   assert( !db || pRet );
   85981   return pRet;
   85982 }
   85983 
   85984 
   85985 /*
   85986 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
   85987 **
   85988 ** This function may only be called when the mutexes associated with all
   85989 ** shared b-tree databases opened using connection db are held by the
   85990 ** caller. This is done to protect the sqlite3.pDisconnect list. The
   85991 ** sqlite3.pDisconnect list is accessed only as follows:
   85992 **
   85993 **   1) By this function. In this case, all BtShared mutexes and the mutex
   85994 **      associated with the database handle itself must be held.
   85995 **
   85996 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
   85997 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
   85998 **      associated with the database the virtual table is stored in is held
   85999 **      or, if the virtual table is stored in a non-sharable database, then
   86000 **      the database handle mutex is held.
   86001 **
   86002 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
   86003 ** by multiple threads. It is thread-safe.
   86004 */
   86005 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
   86006   VTable *p = db->pDisconnect;
   86007   db->pDisconnect = 0;
   86008 
   86009   assert( sqlite3BtreeHoldsAllMutexes(db) );
   86010   assert( sqlite3_mutex_held(db->mutex) );
   86011 
   86012   if( p ){
   86013     sqlite3ExpirePreparedStatements(db);
   86014     do {
   86015       VTable *pNext = p->pNext;
   86016       sqlite3VtabUnlock(p);
   86017       p = pNext;
   86018     }while( p );
   86019   }
   86020 }
   86021 
   86022 /*
   86023 ** Clear any and all virtual-table information from the Table record.
   86024 ** This routine is called, for example, just before deleting the Table
   86025 ** record.
   86026 **
   86027 ** Since it is a virtual-table, the Table structure contains a pointer
   86028 ** to the head of a linked list of VTable structures. Each VTable
   86029 ** structure is associated with a single sqlite3* user of the schema.
   86030 ** The reference count of the VTable structure associated with database
   86031 ** connection db is decremented immediately (which may lead to the
   86032 ** structure being xDisconnected and free). Any other VTable structures
   86033 ** in the list are moved to the sqlite3.pDisconnect list of the associated
   86034 ** database connection.
   86035 */
   86036 SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
   86037   vtabDisconnectAll(0, p);
   86038   if( p->azModuleArg ){
   86039     int i;
   86040     for(i=0; i<p->nModuleArg; i++){
   86041       sqlite3DbFree(p->dbMem, p->azModuleArg[i]);
   86042     }
   86043     sqlite3DbFree(p->dbMem, p->azModuleArg);
   86044   }
   86045 }
   86046 
   86047 /*
   86048 ** Add a new module argument to pTable->azModuleArg[].
   86049 ** The string is not copied - the pointer is stored.  The
   86050 ** string will be freed automatically when the table is
   86051 ** deleted.
   86052 */
   86053 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
   86054   int i = pTable->nModuleArg++;
   86055   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
   86056   char **azModuleArg;
   86057   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
   86058   if( azModuleArg==0 ){
   86059     int j;
   86060     for(j=0; j<i; j++){
   86061       sqlite3DbFree(db, pTable->azModuleArg[j]);
   86062     }
   86063     sqlite3DbFree(db, zArg);
   86064     sqlite3DbFree(db, pTable->azModuleArg);
   86065     pTable->nModuleArg = 0;
   86066   }else{
   86067     azModuleArg[i] = zArg;
   86068     azModuleArg[i+1] = 0;
   86069   }
   86070   pTable->azModuleArg = azModuleArg;
   86071 }
   86072 
   86073 /*
   86074 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
   86075 ** statement.  The module name has been parsed, but the optional list
   86076 ** of parameters that follow the module name are still pending.
   86077 */
   86078 SQLITE_PRIVATE void sqlite3VtabBeginParse(
   86079   Parse *pParse,        /* Parsing context */
   86080   Token *pName1,        /* Name of new table, or database name */
   86081   Token *pName2,        /* Name of new table or NULL */
   86082   Token *pModuleName    /* Name of the module for the virtual table */
   86083 ){
   86084   int iDb;              /* The database the table is being created in */
   86085   Table *pTable;        /* The new virtual table */
   86086   sqlite3 *db;          /* Database connection */
   86087 
   86088   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
   86089   pTable = pParse->pNewTable;
   86090   if( pTable==0 ) return;
   86091   assert( 0==pTable->pIndex );
   86092 
   86093   db = pParse->db;
   86094   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
   86095   assert( iDb>=0 );
   86096 
   86097   pTable->tabFlags |= TF_Virtual;
   86098   pTable->nModuleArg = 0;
   86099   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
   86100   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
   86101   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
   86102   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
   86103 
   86104 #ifndef SQLITE_OMIT_AUTHORIZATION
   86105   /* Creating a virtual table invokes the authorization callback twice.
   86106   ** The first invocation, to obtain permission to INSERT a row into the
   86107   ** sqlite_master table, has already been made by sqlite3StartTable().
   86108   ** The second call, to obtain permission to create the table, is made now.
   86109   */
   86110   if( pTable->azModuleArg ){
   86111     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
   86112             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
   86113   }
   86114 #endif
   86115 }
   86116 
   86117 /*
   86118 ** This routine takes the module argument that has been accumulating
   86119 ** in pParse->zArg[] and appends it to the list of arguments on the
   86120 ** virtual table currently under construction in pParse->pTable.
   86121 */
   86122 static void addArgumentToVtab(Parse *pParse){
   86123   if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
   86124     const char *z = (const char*)pParse->sArg.z;
   86125     int n = pParse->sArg.n;
   86126     sqlite3 *db = pParse->db;
   86127     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
   86128   }
   86129 }
   86130 
   86131 /*
   86132 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
   86133 ** has been completely parsed.
   86134 */
   86135 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
   86136   Table *pTab = pParse->pNewTable;  /* The table being constructed */
   86137   sqlite3 *db = pParse->db;         /* The database connection */
   86138 
   86139   if( pTab==0 ) return;
   86140   addArgumentToVtab(pParse);
   86141   pParse->sArg.z = 0;
   86142   if( pTab->nModuleArg<1 ) return;
   86143 
   86144   /* If the CREATE VIRTUAL TABLE statement is being entered for the
   86145   ** first time (in other words if the virtual table is actually being
   86146   ** created now instead of just being read out of sqlite_master) then
   86147   ** do additional initialization work and store the statement text
   86148   ** in the sqlite_master table.
   86149   */
   86150   if( !db->init.busy ){
   86151     char *zStmt;
   86152     char *zWhere;
   86153     int iDb;
   86154     Vdbe *v;
   86155 
   86156     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
   86157     if( pEnd ){
   86158       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
   86159     }
   86160     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
   86161 
   86162     /* A slot for the record has already been allocated in the
   86163     ** SQLITE_MASTER table.  We just need to update that slot with all
   86164     ** the information we've collected.
   86165     **
   86166     ** The VM register number pParse->regRowid holds the rowid of an
   86167     ** entry in the sqlite_master table tht was created for this vtab
   86168     ** by sqlite3StartTable().
   86169     */
   86170     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   86171     sqlite3NestedParse(pParse,
   86172       "UPDATE %Q.%s "
   86173          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
   86174        "WHERE rowid=#%d",
   86175       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   86176       pTab->zName,
   86177       pTab->zName,
   86178       zStmt,
   86179       pParse->regRowid
   86180     );
   86181     sqlite3DbFree(db, zStmt);
   86182     v = sqlite3GetVdbe(pParse);
   86183     sqlite3ChangeCookie(pParse, iDb);
   86184 
   86185     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
   86186     zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
   86187     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
   86188     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
   86189                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
   86190   }
   86191 
   86192   /* If we are rereading the sqlite_master table create the in-memory
   86193   ** record of the table. The xConnect() method is not called until
   86194   ** the first time the virtual table is used in an SQL statement. This
   86195   ** allows a schema that contains virtual tables to be loaded before
   86196   ** the required virtual table implementations are registered.  */
   86197   else {
   86198     Table *pOld;
   86199     Schema *pSchema = pTab->pSchema;
   86200     const char *zName = pTab->zName;
   86201     int nName = sqlite3Strlen30(zName);
   86202     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
   86203     if( pOld ){
   86204       db->mallocFailed = 1;
   86205       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
   86206       return;
   86207     }
   86208     pSchema->db = pParse->db;
   86209     pParse->pNewTable = 0;
   86210   }
   86211 }
   86212 
   86213 /*
   86214 ** The parser calls this routine when it sees the first token
   86215 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
   86216 */
   86217 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
   86218   addArgumentToVtab(pParse);
   86219   pParse->sArg.z = 0;
   86220   pParse->sArg.n = 0;
   86221 }
   86222 
   86223 /*
   86224 ** The parser calls this routine for each token after the first token
   86225 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
   86226 */
   86227 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
   86228   Token *pArg = &pParse->sArg;
   86229   if( pArg->z==0 ){
   86230     pArg->z = p->z;
   86231     pArg->n = p->n;
   86232   }else{
   86233     assert(pArg->z < p->z);
   86234     pArg->n = (int)(&p->z[p->n] - pArg->z);
   86235   }
   86236 }
   86237 
   86238 /*
   86239 ** Invoke a virtual table constructor (either xCreate or xConnect). The
   86240 ** pointer to the function to invoke is passed as the fourth parameter
   86241 ** to this procedure.
   86242 */
   86243 static int vtabCallConstructor(
   86244   sqlite3 *db,
   86245   Table *pTab,
   86246   Module *pMod,
   86247   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
   86248   char **pzErr
   86249 ){
   86250   VTable *pVTable;
   86251   int rc;
   86252   const char *const*azArg = (const char *const*)pTab->azModuleArg;
   86253   int nArg = pTab->nModuleArg;
   86254   char *zErr = 0;
   86255   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
   86256 
   86257   if( !zModuleName ){
   86258     return SQLITE_NOMEM;
   86259   }
   86260 
   86261   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
   86262   if( !pVTable ){
   86263     sqlite3DbFree(db, zModuleName);
   86264     return SQLITE_NOMEM;
   86265   }
   86266   pVTable->db = db;
   86267   pVTable->pMod = pMod;
   86268 
   86269   assert( !db->pVTab );
   86270   assert( xConstruct );
   86271   db->pVTab = pTab;
   86272 
   86273   /* Invoke the virtual table constructor */
   86274   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
   86275   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
   86276 
   86277   if( SQLITE_OK!=rc ){
   86278     if( zErr==0 ){
   86279       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
   86280     }else {
   86281       *pzErr = sqlite3MPrintf(db, "%s", zErr);
   86282       sqlite3DbFree(db, zErr);
   86283     }
   86284     sqlite3DbFree(db, pVTable);
   86285   }else if( ALWAYS(pVTable->pVtab) ){
   86286     /* Justification of ALWAYS():  A correct vtab constructor must allocate
   86287     ** the sqlite3_vtab object if successful.  */
   86288     pVTable->pVtab->pModule = pMod->pModule;
   86289     pVTable->nRef = 1;
   86290     if( db->pVTab ){
   86291       const char *zFormat = "vtable constructor did not declare schema: %s";
   86292       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
   86293       sqlite3VtabUnlock(pVTable);
   86294       rc = SQLITE_ERROR;
   86295     }else{
   86296       int iCol;
   86297       /* If everything went according to plan, link the new VTable structure
   86298       ** into the linked list headed by pTab->pVTable. Then loop through the
   86299       ** columns of the table to see if any of them contain the token "hidden".
   86300       ** If so, set the Column.isHidden flag and remove the token from
   86301       ** the type string.  */
   86302       pVTable->pNext = pTab->pVTable;
   86303       pTab->pVTable = pVTable;
   86304 
   86305       for(iCol=0; iCol<pTab->nCol; iCol++){
   86306         char *zType = pTab->aCol[iCol].zType;
   86307         int nType;
   86308         int i = 0;
   86309         if( !zType ) continue;
   86310         nType = sqlite3Strlen30(zType);
   86311         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
   86312           for(i=0; i<nType; i++){
   86313             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
   86314              && (zType[i+7]=='\0' || zType[i+7]==' ')
   86315             ){
   86316               i++;
   86317               break;
   86318             }
   86319           }
   86320         }
   86321         if( i<nType ){
   86322           int j;
   86323           int nDel = 6 + (zType[i+6] ? 1 : 0);
   86324           for(j=i; (j+nDel)<=nType; j++){
   86325             zType[j] = zType[j+nDel];
   86326           }
   86327           if( zType[i]=='\0' && i>0 ){
   86328             assert(zType[i-1]==' ');
   86329             zType[i-1] = '\0';
   86330           }
   86331           pTab->aCol[iCol].isHidden = 1;
   86332         }
   86333       }
   86334     }
   86335   }
   86336 
   86337   sqlite3DbFree(db, zModuleName);
   86338   db->pVTab = 0;
   86339   return rc;
   86340 }
   86341 
   86342 /*
   86343 ** This function is invoked by the parser to call the xConnect() method
   86344 ** of the virtual table pTab. If an error occurs, an error code is returned
   86345 ** and an error left in pParse.
   86346 **
   86347 ** This call is a no-op if table pTab is not a virtual table.
   86348 */
   86349 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
   86350   sqlite3 *db = pParse->db;
   86351   const char *zMod;
   86352   Module *pMod;
   86353   int rc;
   86354 
   86355   assert( pTab );
   86356   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
   86357     return SQLITE_OK;
   86358   }
   86359 
   86360   /* Locate the required virtual table module */
   86361   zMod = pTab->azModuleArg[0];
   86362   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
   86363 
   86364   if( !pMod ){
   86365     const char *zModule = pTab->azModuleArg[0];
   86366     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
   86367     rc = SQLITE_ERROR;
   86368   }else{
   86369     char *zErr = 0;
   86370     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
   86371     if( rc!=SQLITE_OK ){
   86372       sqlite3ErrorMsg(pParse, "%s", zErr);
   86373     }
   86374     sqlite3DbFree(db, zErr);
   86375   }
   86376 
   86377   return rc;
   86378 }
   86379 
   86380 /*
   86381 ** Add the virtual table pVTab to the array sqlite3.aVTrans[].
   86382 */
   86383 static int addToVTrans(sqlite3 *db, VTable *pVTab){
   86384   const int ARRAY_INCR = 5;
   86385 
   86386   /* Grow the sqlite3.aVTrans array if required */
   86387   if( (db->nVTrans%ARRAY_INCR)==0 ){
   86388     VTable **aVTrans;
   86389     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
   86390     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
   86391     if( !aVTrans ){
   86392       return SQLITE_NOMEM;
   86393     }
   86394     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
   86395     db->aVTrans = aVTrans;
   86396   }
   86397 
   86398   /* Add pVtab to the end of sqlite3.aVTrans */
   86399   db->aVTrans[db->nVTrans++] = pVTab;
   86400   sqlite3VtabLock(pVTab);
   86401   return SQLITE_OK;
   86402 }
   86403 
   86404 /*
   86405 ** This function is invoked by the vdbe to call the xCreate method
   86406 ** of the virtual table named zTab in database iDb.
   86407 **
   86408 ** If an error occurs, *pzErr is set to point an an English language
   86409 ** description of the error and an SQLITE_XXX error code is returned.
   86410 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
   86411 */
   86412 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
   86413   int rc = SQLITE_OK;
   86414   Table *pTab;
   86415   Module *pMod;
   86416   const char *zMod;
   86417 
   86418   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
   86419   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
   86420 
   86421   /* Locate the required virtual table module */
   86422   zMod = pTab->azModuleArg[0];
   86423   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
   86424 
   86425   /* If the module has been registered and includes a Create method,
   86426   ** invoke it now. If the module has not been registered, return an
   86427   ** error. Otherwise, do nothing.
   86428   */
   86429   if( !pMod ){
   86430     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
   86431     rc = SQLITE_ERROR;
   86432   }else{
   86433     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
   86434   }
   86435 
   86436   /* Justification of ALWAYS():  The xConstructor method is required to
   86437   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
   86438   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
   86439       rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
   86440   }
   86441 
   86442   return rc;
   86443 }
   86444 
   86445 /*
   86446 ** This function is used to set the schema of a virtual table.  It is only
   86447 ** valid to call this function from within the xCreate() or xConnect() of a
   86448 ** virtual table module.
   86449 */
   86450 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
   86451   Parse *pParse;
   86452 
   86453   int rc = SQLITE_OK;
   86454   Table *pTab;
   86455   char *zErr = 0;
   86456 
   86457   sqlite3_mutex_enter(db->mutex);
   86458   pTab = db->pVTab;
   86459   if( !pTab ){
   86460     sqlite3Error(db, SQLITE_MISUSE, 0);
   86461     sqlite3_mutex_leave(db->mutex);
   86462     return SQLITE_MISUSE_BKPT;
   86463   }
   86464   assert( (pTab->tabFlags & TF_Virtual)!=0 );
   86465 
   86466   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
   86467   if( pParse==0 ){
   86468     rc = SQLITE_NOMEM;
   86469   }else{
   86470     pParse->declareVtab = 1;
   86471     pParse->db = db;
   86472 
   86473     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
   86474      && pParse->pNewTable
   86475      && !db->mallocFailed
   86476      && !pParse->pNewTable->pSelect
   86477      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
   86478     ){
   86479       if( !pTab->aCol ){
   86480         pTab->aCol = pParse->pNewTable->aCol;
   86481         pTab->nCol = pParse->pNewTable->nCol;
   86482         pParse->pNewTable->nCol = 0;
   86483         pParse->pNewTable->aCol = 0;
   86484       }
   86485       db->pVTab = 0;
   86486     }else{
   86487       sqlite3Error(db, SQLITE_ERROR, zErr);
   86488       sqlite3DbFree(db, zErr);
   86489       rc = SQLITE_ERROR;
   86490     }
   86491     pParse->declareVtab = 0;
   86492 
   86493     if( pParse->pVdbe ){
   86494       sqlite3VdbeFinalize(pParse->pVdbe);
   86495     }
   86496     sqlite3DeleteTable(pParse->pNewTable);
   86497     sqlite3StackFree(db, pParse);
   86498   }
   86499 
   86500   assert( (rc&0xff)==rc );
   86501   rc = sqlite3ApiExit(db, rc);
   86502   sqlite3_mutex_leave(db->mutex);
   86503   return rc;
   86504 }
   86505 
   86506 /*
   86507 ** This function is invoked by the vdbe to call the xDestroy method
   86508 ** of the virtual table named zTab in database iDb. This occurs
   86509 ** when a DROP TABLE is mentioned.
   86510 **
   86511 ** This call is a no-op if zTab is not a virtual table.
   86512 */
   86513 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
   86514   int rc = SQLITE_OK;
   86515   Table *pTab;
   86516 
   86517   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
   86518   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
   86519     VTable *p = vtabDisconnectAll(db, pTab);
   86520 
   86521     assert( rc==SQLITE_OK );
   86522     rc = p->pMod->pModule->xDestroy(p->pVtab);
   86523 
   86524     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
   86525     if( rc==SQLITE_OK ){
   86526       assert( pTab->pVTable==p && p->pNext==0 );
   86527       p->pVtab = 0;
   86528       pTab->pVTable = 0;
   86529       sqlite3VtabUnlock(p);
   86530     }
   86531   }
   86532 
   86533   return rc;
   86534 }
   86535 
   86536 /*
   86537 ** This function invokes either the xRollback or xCommit method
   86538 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
   86539 ** called is identified by the second argument, "offset", which is
   86540 ** the offset of the method to call in the sqlite3_module structure.
   86541 **
   86542 ** The array is cleared after invoking the callbacks.
   86543 */
   86544 static void callFinaliser(sqlite3 *db, int offset){
   86545   int i;
   86546   if( db->aVTrans ){
   86547     for(i=0; i<db->nVTrans; i++){
   86548       VTable *pVTab = db->aVTrans[i];
   86549       sqlite3_vtab *p = pVTab->pVtab;
   86550       if( p ){
   86551         int (*x)(sqlite3_vtab *);
   86552         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
   86553         if( x ) x(p);
   86554       }
   86555       sqlite3VtabUnlock(pVTab);
   86556     }
   86557     sqlite3DbFree(db, db->aVTrans);
   86558     db->nVTrans = 0;
   86559     db->aVTrans = 0;
   86560   }
   86561 }
   86562 
   86563 /*
   86564 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
   86565 ** array. Return the error code for the first error that occurs, or
   86566 ** SQLITE_OK if all xSync operations are successful.
   86567 **
   86568 ** Set *pzErrmsg to point to a buffer that should be released using
   86569 ** sqlite3DbFree() containing an error message, if one is available.
   86570 */
   86571 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
   86572   int i;
   86573   int rc = SQLITE_OK;
   86574   VTable **aVTrans = db->aVTrans;
   86575 
   86576   db->aVTrans = 0;
   86577   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
   86578     int (*x)(sqlite3_vtab *);
   86579     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
   86580     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
   86581       rc = x(pVtab);
   86582       sqlite3DbFree(db, *pzErrmsg);
   86583       *pzErrmsg = pVtab->zErrMsg;
   86584       pVtab->zErrMsg = 0;
   86585     }
   86586   }
   86587   db->aVTrans = aVTrans;
   86588   return rc;
   86589 }
   86590 
   86591 /*
   86592 ** Invoke the xRollback method of all virtual tables in the
   86593 ** sqlite3.aVTrans array. Then clear the array itself.
   86594 */
   86595 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
   86596   callFinaliser(db, offsetof(sqlite3_module,xRollback));
   86597   return SQLITE_OK;
   86598 }
   86599 
   86600 /*
   86601 ** Invoke the xCommit method of all virtual tables in the
   86602 ** sqlite3.aVTrans array. Then clear the array itself.
   86603 */
   86604 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
   86605   callFinaliser(db, offsetof(sqlite3_module,xCommit));
   86606   return SQLITE_OK;
   86607 }
   86608 
   86609 /*
   86610 ** If the virtual table pVtab supports the transaction interface
   86611 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
   86612 ** not currently open, invoke the xBegin method now.
   86613 **
   86614 ** If the xBegin call is successful, place the sqlite3_vtab pointer
   86615 ** in the sqlite3.aVTrans array.
   86616 */
   86617 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
   86618   int rc = SQLITE_OK;
   86619   const sqlite3_module *pModule;
   86620 
   86621   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
   86622   ** than zero, then this function is being called from within a
   86623   ** virtual module xSync() callback. It is illegal to write to
   86624   ** virtual module tables in this case, so return SQLITE_LOCKED.
   86625   */
   86626   if( sqlite3VtabInSync(db) ){
   86627     return SQLITE_LOCKED;
   86628   }
   86629   if( !pVTab ){
   86630     return SQLITE_OK;
   86631   }
   86632   pModule = pVTab->pVtab->pModule;
   86633 
   86634   if( pModule->xBegin ){
   86635     int i;
   86636 
   86637 
   86638     /* If pVtab is already in the aVTrans array, return early */
   86639     for(i=0; i<db->nVTrans; i++){
   86640       if( db->aVTrans[i]==pVTab ){
   86641         return SQLITE_OK;
   86642       }
   86643     }
   86644 
   86645     /* Invoke the xBegin method */
   86646     rc = pModule->xBegin(pVTab->pVtab);
   86647     if( rc==SQLITE_OK ){
   86648       rc = addToVTrans(db, pVTab);
   86649     }
   86650   }
   86651   return rc;
   86652 }
   86653 
   86654 /*
   86655 ** The first parameter (pDef) is a function implementation.  The
   86656 ** second parameter (pExpr) is the first argument to this function.
   86657 ** If pExpr is a column in a virtual table, then let the virtual
   86658 ** table implementation have an opportunity to overload the function.
   86659 **
   86660 ** This routine is used to allow virtual table implementations to
   86661 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
   86662 **
   86663 ** Return either the pDef argument (indicating no change) or a
   86664 ** new FuncDef structure that is marked as ephemeral using the
   86665 ** SQLITE_FUNC_EPHEM flag.
   86666 */
   86667 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
   86668   sqlite3 *db,    /* Database connection for reporting malloc problems */
   86669   FuncDef *pDef,  /* Function to possibly overload */
   86670   int nArg,       /* Number of arguments to the function */
   86671   Expr *pExpr     /* First argument to the function */
   86672 ){
   86673   Table *pTab;
   86674   sqlite3_vtab *pVtab;
   86675   sqlite3_module *pMod;
   86676   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
   86677   void *pArg = 0;
   86678   FuncDef *pNew;
   86679   int rc = 0;
   86680   char *zLowerName;
   86681   unsigned char *z;
   86682 
   86683 
   86684   /* Check to see the left operand is a column in a virtual table */
   86685   if( NEVER(pExpr==0) ) return pDef;
   86686   if( pExpr->op!=TK_COLUMN ) return pDef;
   86687   pTab = pExpr->pTab;
   86688   if( NEVER(pTab==0) ) return pDef;
   86689   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
   86690   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
   86691   assert( pVtab!=0 );
   86692   assert( pVtab->pModule!=0 );
   86693   pMod = (sqlite3_module *)pVtab->pModule;
   86694   if( pMod->xFindFunction==0 ) return pDef;
   86695 
   86696   /* Call the xFindFunction method on the virtual table implementation
   86697   ** to see if the implementation wants to overload this function
   86698   */
   86699   zLowerName = sqlite3DbStrDup(db, pDef->zName);
   86700   if( zLowerName ){
   86701     for(z=(unsigned char*)zLowerName; *z; z++){
   86702       *z = sqlite3UpperToLower[*z];
   86703     }
   86704     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
   86705     sqlite3DbFree(db, zLowerName);
   86706   }
   86707   if( rc==0 ){
   86708     return pDef;
   86709   }
   86710 
   86711   /* Create a new ephemeral function definition for the overloaded
   86712   ** function */
   86713   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
   86714                              + sqlite3Strlen30(pDef->zName) + 1);
   86715   if( pNew==0 ){
   86716     return pDef;
   86717   }
   86718   *pNew = *pDef;
   86719   pNew->zName = (char *)&pNew[1];
   86720   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
   86721   pNew->xFunc = xFunc;
   86722   pNew->pUserData = pArg;
   86723   pNew->flags |= SQLITE_FUNC_EPHEM;
   86724   return pNew;
   86725 }
   86726 
   86727 /*
   86728 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
   86729 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
   86730 ** array if it is missing.  If pTab is already in the array, this routine
   86731 ** is a no-op.
   86732 */
   86733 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
   86734   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   86735   int i, n;
   86736   Table **apVtabLock;
   86737 
   86738   assert( IsVirtual(pTab) );
   86739   for(i=0; i<pToplevel->nVtabLock; i++){
   86740     if( pTab==pToplevel->apVtabLock[i] ) return;
   86741   }
   86742   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
   86743   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
   86744   if( apVtabLock ){
   86745     pToplevel->apVtabLock = apVtabLock;
   86746     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
   86747   }else{
   86748     pToplevel->db->mallocFailed = 1;
   86749   }
   86750 }
   86751 
   86752 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   86753 
   86754 /************** End of vtab.c ************************************************/
   86755 /************** Begin file where.c *******************************************/
   86756 /*
   86757 ** 2001 September 15
   86758 **
   86759 ** The author disclaims copyright to this source code.  In place of
   86760 ** a legal notice, here is a blessing:
   86761 **
   86762 **    May you do good and not evil.
   86763 **    May you find forgiveness for yourself and forgive others.
   86764 **    May you share freely, never taking more than you give.
   86765 **
   86766 *************************************************************************
   86767 ** This module contains C code that generates VDBE code used to process
   86768 ** the WHERE clause of SQL statements.  This module is responsible for
   86769 ** generating the code that loops through a table looking for applicable
   86770 ** rows.  Indices are selected and used to speed the search when doing
   86771 ** so is applicable.  Because this module is responsible for selecting
   86772 ** indices, you might also think of this module as the "query optimizer".
   86773 */
   86774 
   86775 /*
   86776 ** Trace output macros
   86777 */
   86778 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
   86779 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
   86780 #endif
   86781 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   86782 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
   86783 #else
   86784 # define WHERETRACE(X)
   86785 #endif
   86786 
   86787 /* Forward reference
   86788 */
   86789 typedef struct WhereClause WhereClause;
   86790 typedef struct WhereMaskSet WhereMaskSet;
   86791 typedef struct WhereOrInfo WhereOrInfo;
   86792 typedef struct WhereAndInfo WhereAndInfo;
   86793 typedef struct WhereCost WhereCost;
   86794 
   86795 /*
   86796 ** The query generator uses an array of instances of this structure to
   86797 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
   86798 ** clause subexpression is separated from the others by AND operators,
   86799 ** usually, or sometimes subexpressions separated by OR.
   86800 **
   86801 ** All WhereTerms are collected into a single WhereClause structure.
   86802 ** The following identity holds:
   86803 **
   86804 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
   86805 **
   86806 ** When a term is of the form:
   86807 **
   86808 **              X <op> <expr>
   86809 **
   86810 ** where X is a column name and <op> is one of certain operators,
   86811 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
   86812 ** cursor number and column number for X.  WhereTerm.eOperator records
   86813 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
   86814 ** use of a bitmask encoding for the operator allows us to search
   86815 ** quickly for terms that match any of several different operators.
   86816 **
   86817 ** A WhereTerm might also be two or more subterms connected by OR:
   86818 **
   86819 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
   86820 **
   86821 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
   86822 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
   86823 ** is collected about the
   86824 **
   86825 ** If a term in the WHERE clause does not match either of the two previous
   86826 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
   86827 ** to the original subexpression content and wtFlags is set up appropriately
   86828 ** but no other fields in the WhereTerm object are meaningful.
   86829 **
   86830 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
   86831 ** but they do so indirectly.  A single WhereMaskSet structure translates
   86832 ** cursor number into bits and the translated bit is stored in the prereq
   86833 ** fields.  The translation is used in order to maximize the number of
   86834 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
   86835 ** spread out over the non-negative integers.  For example, the cursor
   86836 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
   86837 ** translates these sparse cursor numbers into consecutive integers
   86838 ** beginning with 0 in order to make the best possible use of the available
   86839 ** bits in the Bitmask.  So, in the example above, the cursor numbers
   86840 ** would be mapped into integers 0 through 7.
   86841 **
   86842 ** The number of terms in a join is limited by the number of bits
   86843 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
   86844 ** is only able to process joins with 64 or fewer tables.
   86845 */
   86846 typedef struct WhereTerm WhereTerm;
   86847 struct WhereTerm {
   86848   Expr *pExpr;            /* Pointer to the subexpression that is this term */
   86849   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
   86850   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
   86851   union {
   86852     int leftColumn;         /* Column number of X in "X <op> <expr>" */
   86853     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
   86854     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
   86855   } u;
   86856   u16 eOperator;          /* A WO_xx value describing <op> */
   86857   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
   86858   u8 nChild;              /* Number of children that must disable us */
   86859   WhereClause *pWC;       /* The clause this term is part of */
   86860   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
   86861   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
   86862 };
   86863 
   86864 /*
   86865 ** Allowed values of WhereTerm.wtFlags
   86866 */
   86867 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
   86868 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
   86869 #define TERM_CODED      0x04   /* This term is already coded */
   86870 #define TERM_COPIED     0x08   /* Has a child */
   86871 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
   86872 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
   86873 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
   86874 
   86875 /*
   86876 ** An instance of the following structure holds all information about a
   86877 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
   86878 */
   86879 struct WhereClause {
   86880   Parse *pParse;           /* The parser context */
   86881   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
   86882   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
   86883   u8 op;                   /* Split operator.  TK_AND or TK_OR */
   86884   int nTerm;               /* Number of terms */
   86885   int nSlot;               /* Number of entries in a[] */
   86886   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
   86887 #if defined(SQLITE_SMALL_STACK)
   86888   WhereTerm aStatic[1];    /* Initial static space for a[] */
   86889 #else
   86890   WhereTerm aStatic[8];    /* Initial static space for a[] */
   86891 #endif
   86892 };
   86893 
   86894 /*
   86895 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
   86896 ** a dynamically allocated instance of the following structure.
   86897 */
   86898 struct WhereOrInfo {
   86899   WhereClause wc;          /* Decomposition into subterms */
   86900   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
   86901 };
   86902 
   86903 /*
   86904 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
   86905 ** a dynamically allocated instance of the following structure.
   86906 */
   86907 struct WhereAndInfo {
   86908   WhereClause wc;          /* The subexpression broken out */
   86909 };
   86910 
   86911 /*
   86912 ** An instance of the following structure keeps track of a mapping
   86913 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
   86914 **
   86915 ** The VDBE cursor numbers are small integers contained in
   86916 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
   86917 ** clause, the cursor numbers might not begin with 0 and they might
   86918 ** contain gaps in the numbering sequence.  But we want to make maximum
   86919 ** use of the bits in our bitmasks.  This structure provides a mapping
   86920 ** from the sparse cursor numbers into consecutive integers beginning
   86921 ** with 0.
   86922 **
   86923 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
   86924 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
   86925 **
   86926 ** For example, if the WHERE clause expression used these VDBE
   86927 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
   86928 ** would map those cursor numbers into bits 0 through 5.
   86929 **
   86930 ** Note that the mapping is not necessarily ordered.  In the example
   86931 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
   86932 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
   86933 ** does not really matter.  What is important is that sparse cursor
   86934 ** numbers all get mapped into bit numbers that begin with 0 and contain
   86935 ** no gaps.
   86936 */
   86937 struct WhereMaskSet {
   86938   int n;                        /* Number of assigned cursor values */
   86939   int ix[BMS];                  /* Cursor assigned to each bit */
   86940 };
   86941 
   86942 /*
   86943 ** A WhereCost object records a lookup strategy and the estimated
   86944 ** cost of pursuing that strategy.
   86945 */
   86946 struct WhereCost {
   86947   WherePlan plan;    /* The lookup strategy */
   86948   double rCost;      /* Overall cost of pursuing this search strategy */
   86949   double nRow;       /* Estimated number of output rows */
   86950   Bitmask used;      /* Bitmask of cursors used by this plan */
   86951 };
   86952 
   86953 /*
   86954 ** Bitmasks for the operators that indices are able to exploit.  An
   86955 ** OR-ed combination of these values can be used when searching for
   86956 ** terms in the where clause.
   86957 */
   86958 #define WO_IN     0x001
   86959 #define WO_EQ     0x002
   86960 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
   86961 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
   86962 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
   86963 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
   86964 #define WO_MATCH  0x040
   86965 #define WO_ISNULL 0x080
   86966 #define WO_OR     0x100       /* Two or more OR-connected terms */
   86967 #define WO_AND    0x200       /* Two or more AND-connected terms */
   86968 
   86969 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
   86970 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
   86971 
   86972 /*
   86973 ** Value for wsFlags returned by bestIndex() and stored in
   86974 ** WhereLevel.wsFlags.  These flags determine which search
   86975 ** strategies are appropriate.
   86976 **
   86977 ** The least significant 12 bits is reserved as a mask for WO_ values above.
   86978 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
   86979 ** But if the table is the right table of a left join, WhereLevel.wsFlags
   86980 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
   86981 ** the "op" parameter to findTerm when we are resolving equality constraints.
   86982 ** ISNULL constraints will then not be used on the right table of a left
   86983 ** join.  Tickets #2177 and #2189.
   86984 */
   86985 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
   86986 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
   86987 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
   86988 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
   86989 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
   86990 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
   86991 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
   86992 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
   86993 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
   86994 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
   86995 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
   86996 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
   86997 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
   86998 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
   86999 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
   87000 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
   87001 
   87002 /*
   87003 ** Initialize a preallocated WhereClause structure.
   87004 */
   87005 static void whereClauseInit(
   87006   WhereClause *pWC,        /* The WhereClause to be initialized */
   87007   Parse *pParse,           /* The parsing context */
   87008   WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
   87009 ){
   87010   pWC->pParse = pParse;
   87011   pWC->pMaskSet = pMaskSet;
   87012   pWC->nTerm = 0;
   87013   pWC->nSlot = ArraySize(pWC->aStatic);
   87014   pWC->a = pWC->aStatic;
   87015   pWC->vmask = 0;
   87016 }
   87017 
   87018 /* Forward reference */
   87019 static void whereClauseClear(WhereClause*);
   87020 
   87021 /*
   87022 ** Deallocate all memory associated with a WhereOrInfo object.
   87023 */
   87024 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
   87025   whereClauseClear(&p->wc);
   87026   sqlite3DbFree(db, p);
   87027 }
   87028 
   87029 /*
   87030 ** Deallocate all memory associated with a WhereAndInfo object.
   87031 */
   87032 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
   87033   whereClauseClear(&p->wc);
   87034   sqlite3DbFree(db, p);
   87035 }
   87036 
   87037 /*
   87038 ** Deallocate a WhereClause structure.  The WhereClause structure
   87039 ** itself is not freed.  This routine is the inverse of whereClauseInit().
   87040 */
   87041 static void whereClauseClear(WhereClause *pWC){
   87042   int i;
   87043   WhereTerm *a;
   87044   sqlite3 *db = pWC->pParse->db;
   87045   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
   87046     if( a->wtFlags & TERM_DYNAMIC ){
   87047       sqlite3ExprDelete(db, a->pExpr);
   87048     }
   87049     if( a->wtFlags & TERM_ORINFO ){
   87050       whereOrInfoDelete(db, a->u.pOrInfo);
   87051     }else if( a->wtFlags & TERM_ANDINFO ){
   87052       whereAndInfoDelete(db, a->u.pAndInfo);
   87053     }
   87054   }
   87055   if( pWC->a!=pWC->aStatic ){
   87056     sqlite3DbFree(db, pWC->a);
   87057   }
   87058 }
   87059 
   87060 /*
   87061 ** Add a single new WhereTerm entry to the WhereClause object pWC.
   87062 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
   87063 ** The index in pWC->a[] of the new WhereTerm is returned on success.
   87064 ** 0 is returned if the new WhereTerm could not be added due to a memory
   87065 ** allocation error.  The memory allocation failure will be recorded in
   87066 ** the db->mallocFailed flag so that higher-level functions can detect it.
   87067 **
   87068 ** This routine will increase the size of the pWC->a[] array as necessary.
   87069 **
   87070 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
   87071 ** for freeing the expression p is assumed by the WhereClause object pWC.
   87072 ** This is true even if this routine fails to allocate a new WhereTerm.
   87073 **
   87074 ** WARNING:  This routine might reallocate the space used to store
   87075 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
   87076 ** calling this routine.  Such pointers may be reinitialized by referencing
   87077 ** the pWC->a[] array.
   87078 */
   87079 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
   87080   WhereTerm *pTerm;
   87081   int idx;
   87082   if( pWC->nTerm>=pWC->nSlot ){
   87083     WhereTerm *pOld = pWC->a;
   87084     sqlite3 *db = pWC->pParse->db;
   87085     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
   87086     if( pWC->a==0 ){
   87087       if( wtFlags & TERM_DYNAMIC ){
   87088         sqlite3ExprDelete(db, p);
   87089       }
   87090       pWC->a = pOld;
   87091       return 0;
   87092     }
   87093     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
   87094     if( pOld!=pWC->aStatic ){
   87095       sqlite3DbFree(db, pOld);
   87096     }
   87097     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
   87098   }
   87099   pTerm = &pWC->a[idx = pWC->nTerm++];
   87100   pTerm->pExpr = p;
   87101   pTerm->wtFlags = wtFlags;
   87102   pTerm->pWC = pWC;
   87103   pTerm->iParent = -1;
   87104   return idx;
   87105 }
   87106 
   87107 /*
   87108 ** This routine identifies subexpressions in the WHERE clause where
   87109 ** each subexpression is separated by the AND operator or some other
   87110 ** operator specified in the op parameter.  The WhereClause structure
   87111 ** is filled with pointers to subexpressions.  For example:
   87112 **
   87113 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
   87114 **           \________/     \_______________/     \________________/
   87115 **            slot[0]            slot[1]               slot[2]
   87116 **
   87117 ** The original WHERE clause in pExpr is unaltered.  All this routine
   87118 ** does is make slot[] entries point to substructure within pExpr.
   87119 **
   87120 ** In the previous sentence and in the diagram, "slot[]" refers to
   87121 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
   87122 ** all terms of the WHERE clause.
   87123 */
   87124 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
   87125   pWC->op = (u8)op;
   87126   if( pExpr==0 ) return;
   87127   if( pExpr->op!=op ){
   87128     whereClauseInsert(pWC, pExpr, 0);
   87129   }else{
   87130     whereSplit(pWC, pExpr->pLeft, op);
   87131     whereSplit(pWC, pExpr->pRight, op);
   87132   }
   87133 }
   87134 
   87135 /*
   87136 ** Initialize an expression mask set (a WhereMaskSet object)
   87137 */
   87138 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
   87139 
   87140 /*
   87141 ** Return the bitmask for the given cursor number.  Return 0 if
   87142 ** iCursor is not in the set.
   87143 */
   87144 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
   87145   int i;
   87146   assert( pMaskSet->n<=sizeof(Bitmask)*8 );
   87147   for(i=0; i<pMaskSet->n; i++){
   87148     if( pMaskSet->ix[i]==iCursor ){
   87149       return ((Bitmask)1)<<i;
   87150     }
   87151   }
   87152   return 0;
   87153 }
   87154 
   87155 /*
   87156 ** Create a new mask for cursor iCursor.
   87157 **
   87158 ** There is one cursor per table in the FROM clause.  The number of
   87159 ** tables in the FROM clause is limited by a test early in the
   87160 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
   87161 ** array will never overflow.
   87162 */
   87163 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
   87164   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
   87165   pMaskSet->ix[pMaskSet->n++] = iCursor;
   87166 }
   87167 
   87168 /*
   87169 ** This routine walks (recursively) an expression tree and generates
   87170 ** a bitmask indicating which tables are used in that expression
   87171 ** tree.
   87172 **
   87173 ** In order for this routine to work, the calling function must have
   87174 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
   87175 ** the header comment on that routine for additional information.
   87176 ** The sqlite3ResolveExprNames() routines looks for column names and
   87177 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
   87178 ** the VDBE cursor number of the table.  This routine just has to
   87179 ** translate the cursor numbers into bitmask values and OR all
   87180 ** the bitmasks together.
   87181 */
   87182 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
   87183 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
   87184 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
   87185   Bitmask mask = 0;
   87186   if( p==0 ) return 0;
   87187   if( p->op==TK_COLUMN ){
   87188     mask = getMask(pMaskSet, p->iTable);
   87189     return mask;
   87190   }
   87191   mask = exprTableUsage(pMaskSet, p->pRight);
   87192   mask |= exprTableUsage(pMaskSet, p->pLeft);
   87193   if( ExprHasProperty(p, EP_xIsSelect) ){
   87194     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
   87195   }else{
   87196     mask |= exprListTableUsage(pMaskSet, p->x.pList);
   87197   }
   87198   return mask;
   87199 }
   87200 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
   87201   int i;
   87202   Bitmask mask = 0;
   87203   if( pList ){
   87204     for(i=0; i<pList->nExpr; i++){
   87205       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
   87206     }
   87207   }
   87208   return mask;
   87209 }
   87210 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
   87211   Bitmask mask = 0;
   87212   while( pS ){
   87213     mask |= exprListTableUsage(pMaskSet, pS->pEList);
   87214     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
   87215     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
   87216     mask |= exprTableUsage(pMaskSet, pS->pWhere);
   87217     mask |= exprTableUsage(pMaskSet, pS->pHaving);
   87218     pS = pS->pPrior;
   87219   }
   87220   return mask;
   87221 }
   87222 
   87223 /*
   87224 ** Return TRUE if the given operator is one of the operators that is
   87225 ** allowed for an indexable WHERE clause term.  The allowed operators are
   87226 ** "=", "<", ">", "<=", ">=", and "IN".
   87227 */
   87228 static int allowedOp(int op){
   87229   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
   87230   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
   87231   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
   87232   assert( TK_GE==TK_EQ+4 );
   87233   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
   87234 }
   87235 
   87236 /*
   87237 ** Swap two objects of type TYPE.
   87238 */
   87239 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
   87240 
   87241 /*
   87242 ** Commute a comparison operator.  Expressions of the form "X op Y"
   87243 ** are converted into "Y op X".
   87244 **
   87245 ** If a collation sequence is associated with either the left or right
   87246 ** side of the comparison, it remains associated with the same side after
   87247 ** the commutation. So "Y collate NOCASE op X" becomes
   87248 ** "X collate NOCASE op Y". This is because any collation sequence on
   87249 ** the left hand side of a comparison overrides any collation sequence
   87250 ** attached to the right. For the same reason the EP_ExpCollate flag
   87251 ** is not commuted.
   87252 */
   87253 static void exprCommute(Parse *pParse, Expr *pExpr){
   87254   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
   87255   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
   87256   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
   87257   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
   87258   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
   87259   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
   87260   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
   87261   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
   87262   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
   87263   if( pExpr->op>=TK_GT ){
   87264     assert( TK_LT==TK_GT+2 );
   87265     assert( TK_GE==TK_LE+2 );
   87266     assert( TK_GT>TK_EQ );
   87267     assert( TK_GT<TK_LE );
   87268     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
   87269     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
   87270   }
   87271 }
   87272 
   87273 /*
   87274 ** Translate from TK_xx operator to WO_xx bitmask.
   87275 */
   87276 static u16 operatorMask(int op){
   87277   u16 c;
   87278   assert( allowedOp(op) );
   87279   if( op==TK_IN ){
   87280     c = WO_IN;
   87281   }else if( op==TK_ISNULL ){
   87282     c = WO_ISNULL;
   87283   }else{
   87284     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
   87285     c = (u16)(WO_EQ<<(op-TK_EQ));
   87286   }
   87287   assert( op!=TK_ISNULL || c==WO_ISNULL );
   87288   assert( op!=TK_IN || c==WO_IN );
   87289   assert( op!=TK_EQ || c==WO_EQ );
   87290   assert( op!=TK_LT || c==WO_LT );
   87291   assert( op!=TK_LE || c==WO_LE );
   87292   assert( op!=TK_GT || c==WO_GT );
   87293   assert( op!=TK_GE || c==WO_GE );
   87294   return c;
   87295 }
   87296 
   87297 /*
   87298 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
   87299 ** where X is a reference to the iColumn of table iCur and <op> is one of
   87300 ** the WO_xx operator codes specified by the op parameter.
   87301 ** Return a pointer to the term.  Return 0 if not found.
   87302 */
   87303 static WhereTerm *findTerm(
   87304   WhereClause *pWC,     /* The WHERE clause to be searched */
   87305   int iCur,             /* Cursor number of LHS */
   87306   int iColumn,          /* Column number of LHS */
   87307   Bitmask notReady,     /* RHS must not overlap with this mask */
   87308   u32 op,               /* Mask of WO_xx values describing operator */
   87309   Index *pIdx           /* Must be compatible with this index, if not NULL */
   87310 ){
   87311   WhereTerm *pTerm;
   87312   int k;
   87313   assert( iCur>=0 );
   87314   op &= WO_ALL;
   87315   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
   87316     if( pTerm->leftCursor==iCur
   87317        && (pTerm->prereqRight & notReady)==0
   87318        && pTerm->u.leftColumn==iColumn
   87319        && (pTerm->eOperator & op)!=0
   87320     ){
   87321       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
   87322         Expr *pX = pTerm->pExpr;
   87323         CollSeq *pColl;
   87324         char idxaff;
   87325         int j;
   87326         Parse *pParse = pWC->pParse;
   87327 
   87328         idxaff = pIdx->pTable->aCol[iColumn].affinity;
   87329         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
   87330 
   87331         /* Figure out the collation sequence required from an index for
   87332         ** it to be useful for optimising expression pX. Store this
   87333         ** value in variable pColl.
   87334         */
   87335         assert(pX->pLeft);
   87336         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
   87337         assert(pColl || pParse->nErr);
   87338 
   87339         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
   87340           if( NEVER(j>=pIdx->nColumn) ) return 0;
   87341         }
   87342         if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
   87343       }
   87344       return pTerm;
   87345     }
   87346   }
   87347   return 0;
   87348 }
   87349 
   87350 /* Forward reference */
   87351 static void exprAnalyze(SrcList*, WhereClause*, int);
   87352 
   87353 /*
   87354 ** Call exprAnalyze on all terms in a WHERE clause.
   87355 **
   87356 **
   87357 */
   87358 static void exprAnalyzeAll(
   87359   SrcList *pTabList,       /* the FROM clause */
   87360   WhereClause *pWC         /* the WHERE clause to be analyzed */
   87361 ){
   87362   int i;
   87363   for(i=pWC->nTerm-1; i>=0; i--){
   87364     exprAnalyze(pTabList, pWC, i);
   87365   }
   87366 }
   87367 
   87368 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
   87369 /*
   87370 ** Check to see if the given expression is a LIKE or GLOB operator that
   87371 ** can be optimized using inequality constraints.  Return TRUE if it is
   87372 ** so and false if not.
   87373 **
   87374 ** In order for the operator to be optimizible, the RHS must be a string
   87375 ** literal that does not begin with a wildcard.
   87376 */
   87377 static int isLikeOrGlob(
   87378   Parse *pParse,    /* Parsing and code generating context */
   87379   Expr *pExpr,      /* Test this expression */
   87380   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
   87381   int *pisComplete, /* True if the only wildcard is % in the last character */
   87382   int *pnoCase      /* True if uppercase is equivalent to lowercase */
   87383 ){
   87384   const char *z = 0;         /* String on RHS of LIKE operator */
   87385   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
   87386   ExprList *pList;           /* List of operands to the LIKE operator */
   87387   int c;                     /* One character in z[] */
   87388   int cnt;                   /* Number of non-wildcard prefix characters */
   87389   char wc[3];                /* Wildcard characters */
   87390   CollSeq *pColl;            /* Collating sequence for LHS */
   87391   sqlite3 *db = pParse->db;  /* Database connection */
   87392   sqlite3_value *pVal = 0;
   87393   int op;                    /* Opcode of pRight */
   87394 
   87395   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
   87396     return 0;
   87397   }
   87398 #ifdef SQLITE_EBCDIC
   87399   if( *pnoCase ) return 0;
   87400 #endif
   87401   pList = pExpr->x.pList;
   87402   pLeft = pList->a[1].pExpr;
   87403   if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
   87404     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
   87405     ** be the name of an indexed column with TEXT affinity. */
   87406     return 0;
   87407   }
   87408   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
   87409   pColl = sqlite3ExprCollSeq(pParse, pLeft);
   87410   assert( pColl!=0 );  /* Every non-IPK column has a collating sequence */
   87411   if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
   87412       (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
   87413     /* IMP: R-09003-32046 For the GLOB operator, the column must use the
   87414     ** default BINARY collating sequence.
   87415     ** IMP: R-41408-28306 For the LIKE operator, if case_sensitive_like mode
   87416     ** is enabled then the column must use the default BINARY collating
   87417     ** sequence, or if case_sensitive_like mode is disabled then the column
   87418     ** must use the built-in NOCASE collating sequence.
   87419     */
   87420     return 0;
   87421   }
   87422 
   87423   pRight = pList->a[0].pExpr;
   87424   op = pRight->op;
   87425   if( op==TK_REGISTER ){
   87426     op = pRight->op2;
   87427   }
   87428   if( op==TK_VARIABLE ){
   87429     Vdbe *pReprepare = pParse->pReprepare;
   87430     pVal = sqlite3VdbeGetValue(pReprepare, pRight->iColumn, SQLITE_AFF_NONE);
   87431     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
   87432       z = (char *)sqlite3_value_text(pVal);
   87433     }
   87434     sqlite3VdbeSetVarmask(pParse->pVdbe, pRight->iColumn);
   87435     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
   87436   }else if( op==TK_STRING ){
   87437     z = pRight->u.zToken;
   87438   }
   87439   if( z ){
   87440     cnt = 0;
   87441     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
   87442       cnt++;
   87443     }
   87444     if( cnt!=0 && c!=0 && 255!=(u8)z[cnt-1] ){
   87445       Expr *pPrefix;
   87446       *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
   87447       pPrefix = sqlite3Expr(db, TK_STRING, z);
   87448       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
   87449       *ppPrefix = pPrefix;
   87450       if( op==TK_VARIABLE ){
   87451         Vdbe *v = pParse->pVdbe;
   87452         sqlite3VdbeSetVarmask(v, pRight->iColumn);
   87453         if( *pisComplete && pRight->u.zToken[1] ){
   87454           /* If the rhs of the LIKE expression is a variable, and the current
   87455           ** value of the variable means there is no need to invoke the LIKE
   87456           ** function, then no OP_Variable will be added to the program.
   87457           ** This causes problems for the sqlite3_bind_parameter_name()
   87458           ** API. To workaround them, add a dummy OP_Variable here.
   87459           */
   87460           int r1 = sqlite3GetTempReg(pParse);
   87461           sqlite3ExprCodeTarget(pParse, pRight, r1);
   87462           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
   87463           sqlite3ReleaseTempReg(pParse, r1);
   87464         }
   87465       }
   87466     }else{
   87467       z = 0;
   87468     }
   87469   }
   87470 
   87471   sqlite3ValueFree(pVal);
   87472   return (z!=0);
   87473 }
   87474 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
   87475 
   87476 
   87477 #ifndef SQLITE_OMIT_VIRTUALTABLE
   87478 /*
   87479 ** Check to see if the given expression is of the form
   87480 **
   87481 **         column MATCH expr
   87482 **
   87483 ** If it is then return TRUE.  If not, return FALSE.
   87484 */
   87485 static int isMatchOfColumn(
   87486   Expr *pExpr      /* Test this expression */
   87487 ){
   87488   ExprList *pList;
   87489 
   87490   if( pExpr->op!=TK_FUNCTION ){
   87491     return 0;
   87492   }
   87493   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
   87494     return 0;
   87495   }
   87496   pList = pExpr->x.pList;
   87497   if( pList->nExpr!=2 ){
   87498     return 0;
   87499   }
   87500   if( pList->a[1].pExpr->op != TK_COLUMN ){
   87501     return 0;
   87502   }
   87503   return 1;
   87504 }
   87505 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   87506 
   87507 /*
   87508 ** If the pBase expression originated in the ON or USING clause of
   87509 ** a join, then transfer the appropriate markings over to derived.
   87510 */
   87511 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
   87512   pDerived->flags |= pBase->flags & EP_FromJoin;
   87513   pDerived->iRightJoinTable = pBase->iRightJoinTable;
   87514 }
   87515 
   87516 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
   87517 /*
   87518 ** Analyze a term that consists of two or more OR-connected
   87519 ** subterms.  So in:
   87520 **
   87521 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
   87522 **                          ^^^^^^^^^^^^^^^^^^^^
   87523 **
   87524 ** This routine analyzes terms such as the middle term in the above example.
   87525 ** A WhereOrTerm object is computed and attached to the term under
   87526 ** analysis, regardless of the outcome of the analysis.  Hence:
   87527 **
   87528 **     WhereTerm.wtFlags   |=  TERM_ORINFO
   87529 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
   87530 **
   87531 ** The term being analyzed must have two or more of OR-connected subterms.
   87532 ** A single subterm might be a set of AND-connected sub-subterms.
   87533 ** Examples of terms under analysis:
   87534 **
   87535 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
   87536 **     (B)     x=expr1 OR expr2=x OR x=expr3
   87537 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
   87538 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
   87539 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
   87540 **
   87541 ** CASE 1:
   87542 **
   87543 ** If all subterms are of the form T.C=expr for some single column of C
   87544 ** a single table T (as shown in example B above) then create a new virtual
   87545 ** term that is an equivalent IN expression.  In other words, if the term
   87546 ** being analyzed is:
   87547 **
   87548 **      x = expr1  OR  expr2 = x  OR  x = expr3
   87549 **
   87550 ** then create a new virtual term like this:
   87551 **
   87552 **      x IN (expr1,expr2,expr3)
   87553 **
   87554 ** CASE 2:
   87555 **
   87556 ** If all subterms are indexable by a single table T, then set
   87557 **
   87558 **     WhereTerm.eOperator              =  WO_OR
   87559 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
   87560 **
   87561 ** A subterm is "indexable" if it is of the form
   87562 ** "T.C <op> <expr>" where C is any column of table T and
   87563 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
   87564 ** A subterm is also indexable if it is an AND of two or more
   87565 ** subsubterms at least one of which is indexable.  Indexable AND
   87566 ** subterms have their eOperator set to WO_AND and they have
   87567 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
   87568 **
   87569 ** From another point of view, "indexable" means that the subterm could
   87570 ** potentially be used with an index if an appropriate index exists.
   87571 ** This analysis does not consider whether or not the index exists; that
   87572 ** is something the bestIndex() routine will determine.  This analysis
   87573 ** only looks at whether subterms appropriate for indexing exist.
   87574 **
   87575 ** All examples A through E above all satisfy case 2.  But if a term
   87576 ** also statisfies case 1 (such as B) we know that the optimizer will
   87577 ** always prefer case 1, so in that case we pretend that case 2 is not
   87578 ** satisfied.
   87579 **
   87580 ** It might be the case that multiple tables are indexable.  For example,
   87581 ** (E) above is indexable on tables P, Q, and R.
   87582 **
   87583 ** Terms that satisfy case 2 are candidates for lookup by using
   87584 ** separate indices to find rowids for each subterm and composing
   87585 ** the union of all rowids using a RowSet object.  This is similar
   87586 ** to "bitmap indices" in other database engines.
   87587 **
   87588 ** OTHERWISE:
   87589 **
   87590 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
   87591 ** zero.  This term is not useful for search.
   87592 */
   87593 static void exprAnalyzeOrTerm(
   87594   SrcList *pSrc,            /* the FROM clause */
   87595   WhereClause *pWC,         /* the complete WHERE clause */
   87596   int idxTerm               /* Index of the OR-term to be analyzed */
   87597 ){
   87598   Parse *pParse = pWC->pParse;            /* Parser context */
   87599   sqlite3 *db = pParse->db;               /* Database connection */
   87600   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
   87601   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
   87602   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
   87603   int i;                                  /* Loop counters */
   87604   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
   87605   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
   87606   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
   87607   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
   87608   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
   87609 
   87610   /*
   87611   ** Break the OR clause into its separate subterms.  The subterms are
   87612   ** stored in a WhereClause structure containing within the WhereOrInfo
   87613   ** object that is attached to the original OR clause term.
   87614   */
   87615   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
   87616   assert( pExpr->op==TK_OR );
   87617   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
   87618   if( pOrInfo==0 ) return;
   87619   pTerm->wtFlags |= TERM_ORINFO;
   87620   pOrWc = &pOrInfo->wc;
   87621   whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
   87622   whereSplit(pOrWc, pExpr, TK_OR);
   87623   exprAnalyzeAll(pSrc, pOrWc);
   87624   if( db->mallocFailed ) return;
   87625   assert( pOrWc->nTerm>=2 );
   87626 
   87627   /*
   87628   ** Compute the set of tables that might satisfy cases 1 or 2.
   87629   */
   87630   indexable = ~(Bitmask)0;
   87631   chngToIN = ~(pWC->vmask);
   87632   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
   87633     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
   87634       WhereAndInfo *pAndInfo;
   87635       assert( pOrTerm->eOperator==0 );
   87636       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
   87637       chngToIN = 0;
   87638       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
   87639       if( pAndInfo ){
   87640         WhereClause *pAndWC;
   87641         WhereTerm *pAndTerm;
   87642         int j;
   87643         Bitmask b = 0;
   87644         pOrTerm->u.pAndInfo = pAndInfo;
   87645         pOrTerm->wtFlags |= TERM_ANDINFO;
   87646         pOrTerm->eOperator = WO_AND;
   87647         pAndWC = &pAndInfo->wc;
   87648         whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
   87649         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
   87650         exprAnalyzeAll(pSrc, pAndWC);
   87651         testcase( db->mallocFailed );
   87652         if( !db->mallocFailed ){
   87653           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
   87654             assert( pAndTerm->pExpr );
   87655             if( allowedOp(pAndTerm->pExpr->op) ){
   87656               b |= getMask(pMaskSet, pAndTerm->leftCursor);
   87657             }
   87658           }
   87659         }
   87660         indexable &= b;
   87661       }
   87662     }else if( pOrTerm->wtFlags & TERM_COPIED ){
   87663       /* Skip this term for now.  We revisit it when we process the
   87664       ** corresponding TERM_VIRTUAL term */
   87665     }else{
   87666       Bitmask b;
   87667       b = getMask(pMaskSet, pOrTerm->leftCursor);
   87668       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
   87669         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
   87670         b |= getMask(pMaskSet, pOther->leftCursor);
   87671       }
   87672       indexable &= b;
   87673       if( pOrTerm->eOperator!=WO_EQ ){
   87674         chngToIN = 0;
   87675       }else{
   87676         chngToIN &= b;
   87677       }
   87678     }
   87679   }
   87680 
   87681   /*
   87682   ** Record the set of tables that satisfy case 2.  The set might be
   87683   ** empty.
   87684   */
   87685   pOrInfo->indexable = indexable;
   87686   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
   87687 
   87688   /*
   87689   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
   87690   ** we have to do some additional checking to see if case 1 really
   87691   ** is satisfied.
   87692   **
   87693   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
   87694   ** that there is no possibility of transforming the OR clause into an
   87695   ** IN operator because one or more terms in the OR clause contain
   87696   ** something other than == on a column in the single table.  The 1-bit
   87697   ** case means that every term of the OR clause is of the form
   87698   ** "table.column=expr" for some single table.  The one bit that is set
   87699   ** will correspond to the common table.  We still need to check to make
   87700   ** sure the same column is used on all terms.  The 2-bit case is when
   87701   ** the all terms are of the form "table1.column=table2.column".  It
   87702   ** might be possible to form an IN operator with either table1.column
   87703   ** or table2.column as the LHS if either is common to every term of
   87704   ** the OR clause.
   87705   **
   87706   ** Note that terms of the form "table.column1=table.column2" (the
   87707   ** same table on both sizes of the ==) cannot be optimized.
   87708   */
   87709   if( chngToIN ){
   87710     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
   87711     int iColumn = -1;         /* Column index on lhs of IN operator */
   87712     int iCursor = -1;         /* Table cursor common to all terms */
   87713     int j = 0;                /* Loop counter */
   87714 
   87715     /* Search for a table and column that appears on one side or the
   87716     ** other of the == operator in every subterm.  That table and column
   87717     ** will be recorded in iCursor and iColumn.  There might not be any
   87718     ** such table and column.  Set okToChngToIN if an appropriate table
   87719     ** and column is found but leave okToChngToIN false if not found.
   87720     */
   87721     for(j=0; j<2 && !okToChngToIN; j++){
   87722       pOrTerm = pOrWc->a;
   87723       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
   87724         assert( pOrTerm->eOperator==WO_EQ );
   87725         pOrTerm->wtFlags &= ~TERM_OR_OK;
   87726         if( pOrTerm->leftCursor==iCursor ){
   87727           /* This is the 2-bit case and we are on the second iteration and
   87728           ** current term is from the first iteration.  So skip this term. */
   87729           assert( j==1 );
   87730           continue;
   87731         }
   87732         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
   87733           /* This term must be of the form t1.a==t2.b where t2 is in the
   87734           ** chngToIN set but t1 is not.  This term will be either preceeded
   87735           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
   87736           ** and use its inversion. */
   87737           testcase( pOrTerm->wtFlags & TERM_COPIED );
   87738           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
   87739           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
   87740           continue;
   87741         }
   87742         iColumn = pOrTerm->u.leftColumn;
   87743         iCursor = pOrTerm->leftCursor;
   87744         break;
   87745       }
   87746       if( i<0 ){
   87747         /* No candidate table+column was found.  This can only occur
   87748         ** on the second iteration */
   87749         assert( j==1 );
   87750         assert( (chngToIN&(chngToIN-1))==0 );
   87751         assert( chngToIN==getMask(pMaskSet, iCursor) );
   87752         break;
   87753       }
   87754       testcase( j==1 );
   87755 
   87756       /* We have found a candidate table and column.  Check to see if that
   87757       ** table and column is common to every term in the OR clause */
   87758       okToChngToIN = 1;
   87759       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
   87760         assert( pOrTerm->eOperator==WO_EQ );
   87761         if( pOrTerm->leftCursor!=iCursor ){
   87762           pOrTerm->wtFlags &= ~TERM_OR_OK;
   87763         }else if( pOrTerm->u.leftColumn!=iColumn ){
   87764           okToChngToIN = 0;
   87765         }else{
   87766           int affLeft, affRight;
   87767           /* If the right-hand side is also a column, then the affinities
   87768           ** of both right and left sides must be such that no type
   87769           ** conversions are required on the right.  (Ticket #2249)
   87770           */
   87771           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
   87772           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
   87773           if( affRight!=0 && affRight!=affLeft ){
   87774             okToChngToIN = 0;
   87775           }else{
   87776             pOrTerm->wtFlags |= TERM_OR_OK;
   87777           }
   87778         }
   87779       }
   87780     }
   87781 
   87782     /* At this point, okToChngToIN is true if original pTerm satisfies
   87783     ** case 1.  In that case, construct a new virtual term that is
   87784     ** pTerm converted into an IN operator.
   87785     */
   87786     if( okToChngToIN ){
   87787       Expr *pDup;            /* A transient duplicate expression */
   87788       ExprList *pList = 0;   /* The RHS of the IN operator */
   87789       Expr *pLeft = 0;       /* The LHS of the IN operator */
   87790       Expr *pNew;            /* The complete IN operator */
   87791 
   87792       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
   87793         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
   87794         assert( pOrTerm->eOperator==WO_EQ );
   87795         assert( pOrTerm->leftCursor==iCursor );
   87796         assert( pOrTerm->u.leftColumn==iColumn );
   87797         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
   87798         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
   87799         pLeft = pOrTerm->pExpr->pLeft;
   87800       }
   87801       assert( pLeft!=0 );
   87802       pDup = sqlite3ExprDup(db, pLeft, 0);
   87803       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
   87804       if( pNew ){
   87805         int idxNew;
   87806         transferJoinMarkings(pNew, pExpr);
   87807         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
   87808         pNew->x.pList = pList;
   87809         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
   87810         testcase( idxNew==0 );
   87811         exprAnalyze(pSrc, pWC, idxNew);
   87812         pTerm = &pWC->a[idxTerm];
   87813         pWC->a[idxNew].iParent = idxTerm;
   87814         pTerm->nChild = 1;
   87815       }else{
   87816         sqlite3ExprListDelete(db, pList);
   87817       }
   87818       pTerm->eOperator = 0;  /* case 1 trumps case 2 */
   87819     }
   87820   }
   87821 }
   87822 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
   87823 
   87824 
   87825 /*
   87826 ** The input to this routine is an WhereTerm structure with only the
   87827 ** "pExpr" field filled in.  The job of this routine is to analyze the
   87828 ** subexpression and populate all the other fields of the WhereTerm
   87829 ** structure.
   87830 **
   87831 ** If the expression is of the form "<expr> <op> X" it gets commuted
   87832 ** to the standard form of "X <op> <expr>".
   87833 **
   87834 ** If the expression is of the form "X <op> Y" where both X and Y are
   87835 ** columns, then the original expression is unchanged and a new virtual
   87836 ** term of the form "Y <op> X" is added to the WHERE clause and
   87837 ** analyzed separately.  The original term is marked with TERM_COPIED
   87838 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
   87839 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
   87840 ** is a commuted copy of a prior term.)  The original term has nChild=1
   87841 ** and the copy has idxParent set to the index of the original term.
   87842 */
   87843 static void exprAnalyze(
   87844   SrcList *pSrc,            /* the FROM clause */
   87845   WhereClause *pWC,         /* the WHERE clause */
   87846   int idxTerm               /* Index of the term to be analyzed */
   87847 ){
   87848   WhereTerm *pTerm;                /* The term to be analyzed */
   87849   WhereMaskSet *pMaskSet;          /* Set of table index masks */
   87850   Expr *pExpr;                     /* The expression to be analyzed */
   87851   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
   87852   Bitmask prereqAll;               /* Prerequesites of pExpr */
   87853   Bitmask extraRight = 0;          /* */
   87854   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
   87855   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
   87856   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
   87857   int op;                          /* Top-level operator.  pExpr->op */
   87858   Parse *pParse = pWC->pParse;     /* Parsing context */
   87859   sqlite3 *db = pParse->db;        /* Database connection */
   87860 
   87861   if( db->mallocFailed ){
   87862     return;
   87863   }
   87864   pTerm = &pWC->a[idxTerm];
   87865   pMaskSet = pWC->pMaskSet;
   87866   pExpr = pTerm->pExpr;
   87867   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
   87868   op = pExpr->op;
   87869   if( op==TK_IN ){
   87870     assert( pExpr->pRight==0 );
   87871     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   87872       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
   87873     }else{
   87874       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
   87875     }
   87876   }else if( op==TK_ISNULL ){
   87877     pTerm->prereqRight = 0;
   87878   }else{
   87879     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
   87880   }
   87881   prereqAll = exprTableUsage(pMaskSet, pExpr);
   87882   if( ExprHasProperty(pExpr, EP_FromJoin) ){
   87883     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
   87884     prereqAll |= x;
   87885     extraRight = x-1;  /* ON clause terms may not be used with an index
   87886                        ** on left table of a LEFT JOIN.  Ticket #3015 */
   87887   }
   87888   pTerm->prereqAll = prereqAll;
   87889   pTerm->leftCursor = -1;
   87890   pTerm->iParent = -1;
   87891   pTerm->eOperator = 0;
   87892   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
   87893     Expr *pLeft = pExpr->pLeft;
   87894     Expr *pRight = pExpr->pRight;
   87895     if( pLeft->op==TK_COLUMN ){
   87896       pTerm->leftCursor = pLeft->iTable;
   87897       pTerm->u.leftColumn = pLeft->iColumn;
   87898       pTerm->eOperator = operatorMask(op);
   87899     }
   87900     if( pRight && pRight->op==TK_COLUMN ){
   87901       WhereTerm *pNew;
   87902       Expr *pDup;
   87903       if( pTerm->leftCursor>=0 ){
   87904         int idxNew;
   87905         pDup = sqlite3ExprDup(db, pExpr, 0);
   87906         if( db->mallocFailed ){
   87907           sqlite3ExprDelete(db, pDup);
   87908           return;
   87909         }
   87910         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
   87911         if( idxNew==0 ) return;
   87912         pNew = &pWC->a[idxNew];
   87913         pNew->iParent = idxTerm;
   87914         pTerm = &pWC->a[idxTerm];
   87915         pTerm->nChild = 1;
   87916         pTerm->wtFlags |= TERM_COPIED;
   87917       }else{
   87918         pDup = pExpr;
   87919         pNew = pTerm;
   87920       }
   87921       exprCommute(pParse, pDup);
   87922       pLeft = pDup->pLeft;
   87923       pNew->leftCursor = pLeft->iTable;
   87924       pNew->u.leftColumn = pLeft->iColumn;
   87925       pNew->prereqRight = prereqLeft;
   87926       pNew->prereqAll = prereqAll;
   87927       pNew->eOperator = operatorMask(pDup->op);
   87928     }
   87929   }
   87930 
   87931 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
   87932   /* If a term is the BETWEEN operator, create two new virtual terms
   87933   ** that define the range that the BETWEEN implements.  For example:
   87934   **
   87935   **      a BETWEEN b AND c
   87936   **
   87937   ** is converted into:
   87938   **
   87939   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
   87940   **
   87941   ** The two new terms are added onto the end of the WhereClause object.
   87942   ** The new terms are "dynamic" and are children of the original BETWEEN
   87943   ** term.  That means that if the BETWEEN term is coded, the children are
   87944   ** skipped.  Or, if the children are satisfied by an index, the original
   87945   ** BETWEEN term is skipped.
   87946   */
   87947   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
   87948     ExprList *pList = pExpr->x.pList;
   87949     int i;
   87950     static const u8 ops[] = {TK_GE, TK_LE};
   87951     assert( pList!=0 );
   87952     assert( pList->nExpr==2 );
   87953     for(i=0; i<2; i++){
   87954       Expr *pNewExpr;
   87955       int idxNew;
   87956       pNewExpr = sqlite3PExpr(pParse, ops[i],
   87957                              sqlite3ExprDup(db, pExpr->pLeft, 0),
   87958                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
   87959       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
   87960       testcase( idxNew==0 );
   87961       exprAnalyze(pSrc, pWC, idxNew);
   87962       pTerm = &pWC->a[idxTerm];
   87963       pWC->a[idxNew].iParent = idxTerm;
   87964     }
   87965     pTerm->nChild = 2;
   87966   }
   87967 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
   87968 
   87969 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
   87970   /* Analyze a term that is composed of two or more subterms connected by
   87971   ** an OR operator.
   87972   */
   87973   else if( pExpr->op==TK_OR ){
   87974     assert( pWC->op==TK_AND );
   87975     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
   87976     pTerm = &pWC->a[idxTerm];
   87977   }
   87978 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   87979 
   87980 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
   87981   /* Add constraints to reduce the search space on a LIKE or GLOB
   87982   ** operator.
   87983   **
   87984   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
   87985   **
   87986   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
   87987   **
   87988   ** The last character of the prefix "abc" is incremented to form the
   87989   ** termination condition "abd".
   87990   */
   87991   if( pWC->op==TK_AND
   87992    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
   87993   ){
   87994     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
   87995     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
   87996     Expr *pNewExpr1;
   87997     Expr *pNewExpr2;
   87998     int idxNew1;
   87999     int idxNew2;
   88000 
   88001     pLeft = pExpr->x.pList->a[1].pExpr;
   88002     pStr2 = sqlite3ExprDup(db, pStr1, 0);
   88003     if( !db->mallocFailed ){
   88004       u8 c, *pC;       /* Last character before the first wildcard */
   88005       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
   88006       c = *pC;
   88007       if( noCase ){
   88008         /* The point is to increment the last character before the first
   88009         ** wildcard.  But if we increment '@', that will push it into the
   88010         ** alphabetic range where case conversions will mess up the
   88011         ** inequality.  To avoid this, make sure to also run the full
   88012         ** LIKE on all candidate expressions by clearing the isComplete flag
   88013         */
   88014         if( c=='A'-1 ) isComplete = 0;
   88015 
   88016         c = sqlite3UpperToLower[c];
   88017       }
   88018       *pC = c + 1;
   88019     }
   88020     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft,0),pStr1,0);
   88021     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
   88022     testcase( idxNew1==0 );
   88023     exprAnalyze(pSrc, pWC, idxNew1);
   88024     pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft,0),pStr2,0);
   88025     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
   88026     testcase( idxNew2==0 );
   88027     exprAnalyze(pSrc, pWC, idxNew2);
   88028     pTerm = &pWC->a[idxTerm];
   88029     if( isComplete ){
   88030       pWC->a[idxNew1].iParent = idxTerm;
   88031       pWC->a[idxNew2].iParent = idxTerm;
   88032       pTerm->nChild = 2;
   88033     }
   88034   }
   88035 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
   88036 
   88037 #ifndef SQLITE_OMIT_VIRTUALTABLE
   88038   /* Add a WO_MATCH auxiliary term to the constraint set if the
   88039   ** current expression is of the form:  column MATCH expr.
   88040   ** This information is used by the xBestIndex methods of
   88041   ** virtual tables.  The native query optimizer does not attempt
   88042   ** to do anything with MATCH functions.
   88043   */
   88044   if( isMatchOfColumn(pExpr) ){
   88045     int idxNew;
   88046     Expr *pRight, *pLeft;
   88047     WhereTerm *pNewTerm;
   88048     Bitmask prereqColumn, prereqExpr;
   88049 
   88050     pRight = pExpr->x.pList->a[0].pExpr;
   88051     pLeft = pExpr->x.pList->a[1].pExpr;
   88052     prereqExpr = exprTableUsage(pMaskSet, pRight);
   88053     prereqColumn = exprTableUsage(pMaskSet, pLeft);
   88054     if( (prereqExpr & prereqColumn)==0 ){
   88055       Expr *pNewExpr;
   88056       pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
   88057                               0, sqlite3ExprDup(db, pRight, 0), 0);
   88058       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
   88059       testcase( idxNew==0 );
   88060       pNewTerm = &pWC->a[idxNew];
   88061       pNewTerm->prereqRight = prereqExpr;
   88062       pNewTerm->leftCursor = pLeft->iTable;
   88063       pNewTerm->u.leftColumn = pLeft->iColumn;
   88064       pNewTerm->eOperator = WO_MATCH;
   88065       pNewTerm->iParent = idxTerm;
   88066       pTerm = &pWC->a[idxTerm];
   88067       pTerm->nChild = 1;
   88068       pTerm->wtFlags |= TERM_COPIED;
   88069       pNewTerm->prereqAll = pTerm->prereqAll;
   88070     }
   88071   }
   88072 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   88073 
   88074   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
   88075   ** an index for tables to the left of the join.
   88076   */
   88077   pTerm->prereqRight |= extraRight;
   88078 }
   88079 
   88080 /*
   88081 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
   88082 ** a reference to any table other than the iBase table.
   88083 */
   88084 static int referencesOtherTables(
   88085   ExprList *pList,          /* Search expressions in ths list */
   88086   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
   88087   int iFirst,               /* Be searching with the iFirst-th expression */
   88088   int iBase                 /* Ignore references to this table */
   88089 ){
   88090   Bitmask allowed = ~getMask(pMaskSet, iBase);
   88091   while( iFirst<pList->nExpr ){
   88092     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
   88093       return 1;
   88094     }
   88095   }
   88096   return 0;
   88097 }
   88098 
   88099 
   88100 /*
   88101 ** This routine decides if pIdx can be used to satisfy the ORDER BY
   88102 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
   88103 ** ORDER BY clause, this routine returns 0.
   88104 **
   88105 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
   88106 ** left-most table in the FROM clause of that same SELECT statement and
   88107 ** the table has a cursor number of "base".  pIdx is an index on pTab.
   88108 **
   88109 ** nEqCol is the number of columns of pIdx that are used as equality
   88110 ** constraints.  Any of these columns may be missing from the ORDER BY
   88111 ** clause and the match can still be a success.
   88112 **
   88113 ** All terms of the ORDER BY that match against the index must be either
   88114 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
   88115 ** index do not need to satisfy this constraint.)  The *pbRev value is
   88116 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
   88117 ** the ORDER BY clause is all ASC.
   88118 */
   88119 static int isSortingIndex(
   88120   Parse *pParse,          /* Parsing context */
   88121   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
   88122   Index *pIdx,            /* The index we are testing */
   88123   int base,               /* Cursor number for the table to be sorted */
   88124   ExprList *pOrderBy,     /* The ORDER BY clause */
   88125   int nEqCol,             /* Number of index columns with == constraints */
   88126   int *pbRev              /* Set to 1 if ORDER BY is DESC */
   88127 ){
   88128   int i, j;                       /* Loop counters */
   88129   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
   88130   int nTerm;                      /* Number of ORDER BY terms */
   88131   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
   88132   sqlite3 *db = pParse->db;
   88133 
   88134   assert( pOrderBy!=0 );
   88135   nTerm = pOrderBy->nExpr;
   88136   assert( nTerm>0 );
   88137 
   88138   /* Argument pIdx must either point to a 'real' named index structure,
   88139   ** or an index structure allocated on the stack by bestBtreeIndex() to
   88140   ** represent the rowid index that is part of every table.  */
   88141   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
   88142 
   88143   /* Match terms of the ORDER BY clause against columns of
   88144   ** the index.
   88145   **
   88146   ** Note that indices have pIdx->nColumn regular columns plus
   88147   ** one additional column containing the rowid.  The rowid column
   88148   ** of the index is also allowed to match against the ORDER BY
   88149   ** clause.
   88150   */
   88151   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
   88152     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
   88153     CollSeq *pColl;    /* The collating sequence of pExpr */
   88154     int termSortOrder; /* Sort order for this term */
   88155     int iColumn;       /* The i-th column of the index.  -1 for rowid */
   88156     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
   88157     const char *zColl; /* Name of the collating sequence for i-th index term */
   88158 
   88159     pExpr = pTerm->pExpr;
   88160     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
   88161       /* Can not use an index sort on anything that is not a column in the
   88162       ** left-most table of the FROM clause */
   88163       break;
   88164     }
   88165     pColl = sqlite3ExprCollSeq(pParse, pExpr);
   88166     if( !pColl ){
   88167       pColl = db->pDfltColl;
   88168     }
   88169     if( pIdx->zName && i<pIdx->nColumn ){
   88170       iColumn = pIdx->aiColumn[i];
   88171       if( iColumn==pIdx->pTable->iPKey ){
   88172         iColumn = -1;
   88173       }
   88174       iSortOrder = pIdx->aSortOrder[i];
   88175       zColl = pIdx->azColl[i];
   88176     }else{
   88177       iColumn = -1;
   88178       iSortOrder = 0;
   88179       zColl = pColl->zName;
   88180     }
   88181     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
   88182       /* Term j of the ORDER BY clause does not match column i of the index */
   88183       if( i<nEqCol ){
   88184         /* If an index column that is constrained by == fails to match an
   88185         ** ORDER BY term, that is OK.  Just ignore that column of the index
   88186         */
   88187         continue;
   88188       }else if( i==pIdx->nColumn ){
   88189         /* Index column i is the rowid.  All other terms match. */
   88190         break;
   88191       }else{
   88192         /* If an index column fails to match and is not constrained by ==
   88193         ** then the index cannot satisfy the ORDER BY constraint.
   88194         */
   88195         return 0;
   88196       }
   88197     }
   88198     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
   88199     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
   88200     assert( iSortOrder==0 || iSortOrder==1 );
   88201     termSortOrder = iSortOrder ^ pTerm->sortOrder;
   88202     if( i>nEqCol ){
   88203       if( termSortOrder!=sortOrder ){
   88204         /* Indices can only be used if all ORDER BY terms past the
   88205         ** equality constraints are all either DESC or ASC. */
   88206         return 0;
   88207       }
   88208     }else{
   88209       sortOrder = termSortOrder;
   88210     }
   88211     j++;
   88212     pTerm++;
   88213     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
   88214       /* If the indexed column is the primary key and everything matches
   88215       ** so far and none of the ORDER BY terms to the right reference other
   88216       ** tables in the join, then we are assured that the index can be used
   88217       ** to sort because the primary key is unique and so none of the other
   88218       ** columns will make any difference
   88219       */
   88220       j = nTerm;
   88221     }
   88222   }
   88223 
   88224   *pbRev = sortOrder!=0;
   88225   if( j>=nTerm ){
   88226     /* All terms of the ORDER BY clause are covered by this index so
   88227     ** this index can be used for sorting. */
   88228     return 1;
   88229   }
   88230   if( pIdx->onError!=OE_None && i==pIdx->nColumn
   88231       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
   88232     /* All terms of this index match some prefix of the ORDER BY clause
   88233     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
   88234     ** clause reference other tables in a join.  If this is all true then
   88235     ** the order by clause is superfluous. */
   88236     return 1;
   88237   }
   88238   return 0;
   88239 }
   88240 
   88241 /*
   88242 ** Prepare a crude estimate of the logarithm of the input value.
   88243 ** The results need not be exact.  This is only used for estimating
   88244 ** the total cost of performing operations with O(logN) or O(NlogN)
   88245 ** complexity.  Because N is just a guess, it is no great tragedy if
   88246 ** logN is a little off.
   88247 */
   88248 static double estLog(double N){
   88249   double logN = 1;
   88250   double x = 10;
   88251   while( N>x ){
   88252     logN += 1;
   88253     x *= 10;
   88254   }
   88255   return logN;
   88256 }
   88257 
   88258 /*
   88259 ** Two routines for printing the content of an sqlite3_index_info
   88260 ** structure.  Used for testing and debugging only.  If neither
   88261 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
   88262 ** are no-ops.
   88263 */
   88264 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
   88265 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
   88266   int i;
   88267   if( !sqlite3WhereTrace ) return;
   88268   for(i=0; i<p->nConstraint; i++){
   88269     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
   88270        i,
   88271        p->aConstraint[i].iColumn,
   88272        p->aConstraint[i].iTermOffset,
   88273        p->aConstraint[i].op,
   88274        p->aConstraint[i].usable);
   88275   }
   88276   for(i=0; i<p->nOrderBy; i++){
   88277     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
   88278        i,
   88279        p->aOrderBy[i].iColumn,
   88280        p->aOrderBy[i].desc);
   88281   }
   88282 }
   88283 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
   88284   int i;
   88285   if( !sqlite3WhereTrace ) return;
   88286   for(i=0; i<p->nConstraint; i++){
   88287     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
   88288        i,
   88289        p->aConstraintUsage[i].argvIndex,
   88290        p->aConstraintUsage[i].omit);
   88291   }
   88292   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
   88293   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
   88294   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
   88295   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
   88296 }
   88297 #else
   88298 #define TRACE_IDX_INPUTS(A)
   88299 #define TRACE_IDX_OUTPUTS(A)
   88300 #endif
   88301 
   88302 /*
   88303 ** Required because bestIndex() is called by bestOrClauseIndex()
   88304 */
   88305 static void bestIndex(
   88306     Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*);
   88307 
   88308 /*
   88309 ** This routine attempts to find an scanning strategy that can be used
   88310 ** to optimize an 'OR' expression that is part of a WHERE clause.
   88311 **
   88312 ** The table associated with FROM clause term pSrc may be either a
   88313 ** regular B-Tree table or a virtual table.
   88314 */
   88315 static void bestOrClauseIndex(
   88316   Parse *pParse,              /* The parsing context */
   88317   WhereClause *pWC,           /* The WHERE clause */
   88318   struct SrcList_item *pSrc,  /* The FROM clause term to search */
   88319   Bitmask notReady,           /* Mask of cursors that are not available */
   88320   ExprList *pOrderBy,         /* The ORDER BY clause */
   88321   WhereCost *pCost            /* Lowest cost query plan */
   88322 ){
   88323 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
   88324   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
   88325   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
   88326   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
   88327   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
   88328 
   88329   /* Search the WHERE clause terms for a usable WO_OR term. */
   88330   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   88331     if( pTerm->eOperator==WO_OR
   88332      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
   88333      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
   88334     ){
   88335       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
   88336       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
   88337       WhereTerm *pOrTerm;
   88338       int flags = WHERE_MULTI_OR;
   88339       double rTotal = 0;
   88340       double nRow = 0;
   88341       Bitmask used = 0;
   88342 
   88343       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
   88344         WhereCost sTermCost;
   88345         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
   88346           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
   88347         ));
   88348         if( pOrTerm->eOperator==WO_AND ){
   88349           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
   88350           bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
   88351         }else if( pOrTerm->leftCursor==iCur ){
   88352           WhereClause tempWC;
   88353           tempWC.pParse = pWC->pParse;
   88354           tempWC.pMaskSet = pWC->pMaskSet;
   88355           tempWC.op = TK_AND;
   88356           tempWC.a = pOrTerm;
   88357           tempWC.nTerm = 1;
   88358           bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
   88359         }else{
   88360           continue;
   88361         }
   88362         rTotal += sTermCost.rCost;
   88363         nRow += sTermCost.nRow;
   88364         used |= sTermCost.used;
   88365         if( rTotal>=pCost->rCost ) break;
   88366       }
   88367 
   88368       /* If there is an ORDER BY clause, increase the scan cost to account
   88369       ** for the cost of the sort. */
   88370       if( pOrderBy!=0 ){
   88371         rTotal += nRow*estLog(nRow);
   88372         WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
   88373       }
   88374 
   88375       /* If the cost of scanning using this OR term for optimization is
   88376       ** less than the current cost stored in pCost, replace the contents
   88377       ** of pCost. */
   88378       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
   88379       if( rTotal<pCost->rCost ){
   88380         pCost->rCost = rTotal;
   88381         pCost->nRow = nRow;
   88382         pCost->used = used;
   88383         pCost->plan.wsFlags = flags;
   88384         pCost->plan.u.pTerm = pTerm;
   88385       }
   88386     }
   88387   }
   88388 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   88389 }
   88390 
   88391 #ifndef SQLITE_OMIT_VIRTUALTABLE
   88392 /*
   88393 ** Allocate and populate an sqlite3_index_info structure. It is the
   88394 ** responsibility of the caller to eventually release the structure
   88395 ** by passing the pointer returned by this function to sqlite3_free().
   88396 */
   88397 static sqlite3_index_info *allocateIndexInfo(
   88398   Parse *pParse,
   88399   WhereClause *pWC,
   88400   struct SrcList_item *pSrc,
   88401   ExprList *pOrderBy
   88402 ){
   88403   int i, j;
   88404   int nTerm;
   88405   struct sqlite3_index_constraint *pIdxCons;
   88406   struct sqlite3_index_orderby *pIdxOrderBy;
   88407   struct sqlite3_index_constraint_usage *pUsage;
   88408   WhereTerm *pTerm;
   88409   int nOrderBy;
   88410   sqlite3_index_info *pIdxInfo;
   88411 
   88412   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
   88413 
   88414   /* Count the number of possible WHERE clause constraints referring
   88415   ** to this virtual table */
   88416   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   88417     if( pTerm->leftCursor != pSrc->iCursor ) continue;
   88418     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
   88419     testcase( pTerm->eOperator==WO_IN );
   88420     testcase( pTerm->eOperator==WO_ISNULL );
   88421     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
   88422     nTerm++;
   88423   }
   88424 
   88425   /* If the ORDER BY clause contains only columns in the current
   88426   ** virtual table then allocate space for the aOrderBy part of
   88427   ** the sqlite3_index_info structure.
   88428   */
   88429   nOrderBy = 0;
   88430   if( pOrderBy ){
   88431     for(i=0; i<pOrderBy->nExpr; i++){
   88432       Expr *pExpr = pOrderBy->a[i].pExpr;
   88433       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
   88434     }
   88435     if( i==pOrderBy->nExpr ){
   88436       nOrderBy = pOrderBy->nExpr;
   88437     }
   88438   }
   88439 
   88440   /* Allocate the sqlite3_index_info structure
   88441   */
   88442   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
   88443                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
   88444                            + sizeof(*pIdxOrderBy)*nOrderBy );
   88445   if( pIdxInfo==0 ){
   88446     sqlite3ErrorMsg(pParse, "out of memory");
   88447     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   88448     return 0;
   88449   }
   88450 
   88451   /* Initialize the structure.  The sqlite3_index_info structure contains
   88452   ** many fields that are declared "const" to prevent xBestIndex from
   88453   ** changing them.  We have to do some funky casting in order to
   88454   ** initialize those fields.
   88455   */
   88456   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
   88457   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
   88458   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
   88459   *(int*)&pIdxInfo->nConstraint = nTerm;
   88460   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
   88461   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
   88462   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
   88463   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
   88464                                                                    pUsage;
   88465 
   88466   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   88467     if( pTerm->leftCursor != pSrc->iCursor ) continue;
   88468     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
   88469     testcase( pTerm->eOperator==WO_IN );
   88470     testcase( pTerm->eOperator==WO_ISNULL );
   88471     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
   88472     pIdxCons[j].iColumn = pTerm->u.leftColumn;
   88473     pIdxCons[j].iTermOffset = i;
   88474     pIdxCons[j].op = (u8)pTerm->eOperator;
   88475     /* The direct assignment in the previous line is possible only because
   88476     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
   88477     ** following asserts verify this fact. */
   88478     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
   88479     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
   88480     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
   88481     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
   88482     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
   88483     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
   88484     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
   88485     j++;
   88486   }
   88487   for(i=0; i<nOrderBy; i++){
   88488     Expr *pExpr = pOrderBy->a[i].pExpr;
   88489     pIdxOrderBy[i].iColumn = pExpr->iColumn;
   88490     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
   88491   }
   88492 
   88493   return pIdxInfo;
   88494 }
   88495 
   88496 /*
   88497 ** The table object reference passed as the second argument to this function
   88498 ** must represent a virtual table. This function invokes the xBestIndex()
   88499 ** method of the virtual table with the sqlite3_index_info pointer passed
   88500 ** as the argument.
   88501 **
   88502 ** If an error occurs, pParse is populated with an error message and a
   88503 ** non-zero value is returned. Otherwise, 0 is returned and the output
   88504 ** part of the sqlite3_index_info structure is left populated.
   88505 **
   88506 ** Whether or not an error is returned, it is the responsibility of the
   88507 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
   88508 ** that this is required.
   88509 */
   88510 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
   88511   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
   88512   int i;
   88513   int rc;
   88514 
   88515   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
   88516   TRACE_IDX_INPUTS(p);
   88517   rc = pVtab->pModule->xBestIndex(pVtab, p);
   88518   TRACE_IDX_OUTPUTS(p);
   88519 
   88520   if( rc!=SQLITE_OK ){
   88521     if( rc==SQLITE_NOMEM ){
   88522       pParse->db->mallocFailed = 1;
   88523     }else if( !pVtab->zErrMsg ){
   88524       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
   88525     }else{
   88526       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
   88527     }
   88528   }
   88529   sqlite3DbFree(pParse->db, pVtab->zErrMsg);
   88530   pVtab->zErrMsg = 0;
   88531 
   88532   for(i=0; i<p->nConstraint; i++){
   88533     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
   88534       sqlite3ErrorMsg(pParse,
   88535           "table %s: xBestIndex returned an invalid plan", pTab->zName);
   88536     }
   88537   }
   88538 
   88539   return pParse->nErr;
   88540 }
   88541 
   88542 
   88543 /*
   88544 ** Compute the best index for a virtual table.
   88545 **
   88546 ** The best index is computed by the xBestIndex method of the virtual
   88547 ** table module.  This routine is really just a wrapper that sets up
   88548 ** the sqlite3_index_info structure that is used to communicate with
   88549 ** xBestIndex.
   88550 **
   88551 ** In a join, this routine might be called multiple times for the
   88552 ** same virtual table.  The sqlite3_index_info structure is created
   88553 ** and initialized on the first invocation and reused on all subsequent
   88554 ** invocations.  The sqlite3_index_info structure is also used when
   88555 ** code is generated to access the virtual table.  The whereInfoDelete()
   88556 ** routine takes care of freeing the sqlite3_index_info structure after
   88557 ** everybody has finished with it.
   88558 */
   88559 static void bestVirtualIndex(
   88560   Parse *pParse,                  /* The parsing context */
   88561   WhereClause *pWC,               /* The WHERE clause */
   88562   struct SrcList_item *pSrc,      /* The FROM clause term to search */
   88563   Bitmask notReady,               /* Mask of cursors that are not available */
   88564   ExprList *pOrderBy,             /* The order by clause */
   88565   WhereCost *pCost,               /* Lowest cost query plan */
   88566   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
   88567 ){
   88568   Table *pTab = pSrc->pTab;
   88569   sqlite3_index_info *pIdxInfo;
   88570   struct sqlite3_index_constraint *pIdxCons;
   88571   struct sqlite3_index_constraint_usage *pUsage;
   88572   WhereTerm *pTerm;
   88573   int i, j;
   88574   int nOrderBy;
   88575 
   88576   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
   88577   ** malloc in allocateIndexInfo() fails and this function returns leaving
   88578   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
   88579   */
   88580   memset(pCost, 0, sizeof(*pCost));
   88581   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
   88582 
   88583   /* If the sqlite3_index_info structure has not been previously
   88584   ** allocated and initialized, then allocate and initialize it now.
   88585   */
   88586   pIdxInfo = *ppIdxInfo;
   88587   if( pIdxInfo==0 ){
   88588     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
   88589   }
   88590   if( pIdxInfo==0 ){
   88591     return;
   88592   }
   88593 
   88594   /* At this point, the sqlite3_index_info structure that pIdxInfo points
   88595   ** to will have been initialized, either during the current invocation or
   88596   ** during some prior invocation.  Now we just have to customize the
   88597   ** details of pIdxInfo for the current invocation and pass it to
   88598   ** xBestIndex.
   88599   */
   88600 
   88601   /* The module name must be defined. Also, by this point there must
   88602   ** be a pointer to an sqlite3_vtab structure. Otherwise
   88603   ** sqlite3ViewGetColumnNames() would have picked up the error.
   88604   */
   88605   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
   88606   assert( sqlite3GetVTable(pParse->db, pTab) );
   88607 
   88608   /* Set the aConstraint[].usable fields and initialize all
   88609   ** output variables to zero.
   88610   **
   88611   ** aConstraint[].usable is true for constraints where the right-hand
   88612   ** side contains only references to tables to the left of the current
   88613   ** table.  In other words, if the constraint is of the form:
   88614   **
   88615   **           column = expr
   88616   **
   88617   ** and we are evaluating a join, then the constraint on column is
   88618   ** only valid if all tables referenced in expr occur to the left
   88619   ** of the table containing column.
   88620   **
   88621   ** The aConstraints[] array contains entries for all constraints
   88622   ** on the current table.  That way we only have to compute it once
   88623   ** even though we might try to pick the best index multiple times.
   88624   ** For each attempt at picking an index, the order of tables in the
   88625   ** join might be different so we have to recompute the usable flag
   88626   ** each time.
   88627   */
   88628   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
   88629   pUsage = pIdxInfo->aConstraintUsage;
   88630   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
   88631     j = pIdxCons->iTermOffset;
   88632     pTerm = &pWC->a[j];
   88633     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
   88634   }
   88635   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
   88636   if( pIdxInfo->needToFreeIdxStr ){
   88637     sqlite3_free(pIdxInfo->idxStr);
   88638   }
   88639   pIdxInfo->idxStr = 0;
   88640   pIdxInfo->idxNum = 0;
   88641   pIdxInfo->needToFreeIdxStr = 0;
   88642   pIdxInfo->orderByConsumed = 0;
   88643   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
   88644   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
   88645   nOrderBy = pIdxInfo->nOrderBy;
   88646   if( !pOrderBy ){
   88647     pIdxInfo->nOrderBy = 0;
   88648   }
   88649 
   88650   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
   88651     return;
   88652   }
   88653 
   88654   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
   88655   for(i=0; i<pIdxInfo->nConstraint; i++){
   88656     if( pUsage[i].argvIndex>0 ){
   88657       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
   88658     }
   88659   }
   88660 
   88661   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
   88662   ** inital value of lowestCost in this loop. If it is, then the
   88663   ** (cost<lowestCost) test below will never be true.
   88664   **
   88665   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
   88666   ** is defined.
   88667   */
   88668   if( (SQLITE_BIG_DBL/((double)2))<pIdxInfo->estimatedCost ){
   88669     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
   88670   }else{
   88671     pCost->rCost = pIdxInfo->estimatedCost;
   88672   }
   88673   pCost->plan.u.pVtabIdx = pIdxInfo;
   88674   if( pIdxInfo->orderByConsumed ){
   88675     pCost->plan.wsFlags |= WHERE_ORDERBY;
   88676   }
   88677   pCost->plan.nEq = 0;
   88678   pIdxInfo->nOrderBy = nOrderBy;
   88679 
   88680   /* Try to find a more efficient access pattern by using multiple indexes
   88681   ** to optimize an OR expression within the WHERE clause.
   88682   */
   88683   bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
   88684 }
   88685 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   88686 
   88687 /*
   88688 ** Argument pIdx is a pointer to an index structure that has an array of
   88689 ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
   88690 ** stored in Index.aSample. The domain of values stored in said column
   88691 ** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
   88692 ** Region 0 contains all values smaller than the first sample value. Region
   88693 ** 1 contains values larger than or equal to the value of the first sample,
   88694 ** but smaller than the value of the second. And so on.
   88695 **
   88696 ** If successful, this function determines which of the regions value
   88697 ** pVal lies in, sets *piRegion to the region index (a value between 0
   88698 ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
   88699 ** Or, if an OOM occurs while converting text values between encodings,
   88700 ** SQLITE_NOMEM is returned and *piRegion is undefined.
   88701 */
   88702 #ifdef SQLITE_ENABLE_STAT2
   88703 static int whereRangeRegion(
   88704   Parse *pParse,              /* Database connection */
   88705   Index *pIdx,                /* Index to consider domain of */
   88706   sqlite3_value *pVal,        /* Value to consider */
   88707   int *piRegion               /* OUT: Region of domain in which value lies */
   88708 ){
   88709   if( ALWAYS(pVal) ){
   88710     IndexSample *aSample = pIdx->aSample;
   88711     int i = 0;
   88712     int eType = sqlite3_value_type(pVal);
   88713 
   88714     if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
   88715       double r = sqlite3_value_double(pVal);
   88716       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
   88717         if( aSample[i].eType==SQLITE_NULL ) continue;
   88718         if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
   88719       }
   88720     }else{
   88721       sqlite3 *db = pParse->db;
   88722       CollSeq *pColl;
   88723       const u8 *z;
   88724       int n;
   88725 
   88726       /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
   88727       assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
   88728 
   88729       if( eType==SQLITE_BLOB ){
   88730         z = (const u8 *)sqlite3_value_blob(pVal);
   88731         pColl = db->pDfltColl;
   88732         assert( pColl->enc==SQLITE_UTF8 );
   88733       }else{
   88734         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
   88735         if( pColl==0 ){
   88736           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
   88737                           *pIdx->azColl);
   88738           return SQLITE_ERROR;
   88739         }
   88740         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
   88741         if( !z ){
   88742           return SQLITE_NOMEM;
   88743         }
   88744         assert( z && pColl && pColl->xCmp );
   88745       }
   88746       n = sqlite3ValueBytes(pVal, pColl->enc);
   88747 
   88748       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
   88749         int r;
   88750         int eSampletype = aSample[i].eType;
   88751         if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
   88752         if( (eSampletype!=eType) ) break;
   88753 #ifndef SQLITE_OMIT_UTF16
   88754         if( pColl->enc!=SQLITE_UTF8 ){
   88755           int nSample;
   88756           char *zSample = sqlite3Utf8to16(
   88757               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
   88758           );
   88759           if( !zSample ){
   88760             assert( db->mallocFailed );
   88761             return SQLITE_NOMEM;
   88762           }
   88763           r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
   88764           sqlite3DbFree(db, zSample);
   88765         }else
   88766 #endif
   88767         {
   88768           r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
   88769         }
   88770         if( r>0 ) break;
   88771       }
   88772     }
   88773 
   88774     assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
   88775     *piRegion = i;
   88776   }
   88777   return SQLITE_OK;
   88778 }
   88779 #endif   /* #ifdef SQLITE_ENABLE_STAT2 */
   88780 
   88781 /*
   88782 ** If expression pExpr represents a literal value, set *pp to point to
   88783 ** an sqlite3_value structure containing the same value, with affinity
   88784 ** aff applied to it, before returning. It is the responsibility of the
   88785 ** caller to eventually release this structure by passing it to
   88786 ** sqlite3ValueFree().
   88787 **
   88788 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
   88789 ** is an SQL variable that currently has a non-NULL value bound to it,
   88790 ** create an sqlite3_value structure containing this value, again with
   88791 ** affinity aff applied to it, instead.
   88792 **
   88793 ** If neither of the above apply, set *pp to NULL.
   88794 **
   88795 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
   88796 */
   88797 #ifdef SQLITE_ENABLE_STAT2
   88798 static int valueFromExpr(
   88799   Parse *pParse,
   88800   Expr *pExpr,
   88801   u8 aff,
   88802   sqlite3_value **pp
   88803 ){
   88804   /* The evalConstExpr() function will have already converted any TK_VARIABLE
   88805   ** expression involved in an comparison into a TK_REGISTER. */
   88806   assert( pExpr->op!=TK_VARIABLE );
   88807   if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
   88808     int iVar = pExpr->iColumn;
   88809     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
   88810     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
   88811     return SQLITE_OK;
   88812   }
   88813   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
   88814 }
   88815 #endif
   88816 
   88817 /*
   88818 ** This function is used to estimate the number of rows that will be visited
   88819 ** by scanning an index for a range of values. The range may have an upper
   88820 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
   88821 ** and lower bounds are represented by pLower and pUpper respectively. For
   88822 ** example, assuming that index p is on t1(a):
   88823 **
   88824 **   ... FROM t1 WHERE a > ? AND a < ? ...
   88825 **                    |_____|   |_____|
   88826 **                       |         |
   88827 **                     pLower    pUpper
   88828 **
   88829 ** If either of the upper or lower bound is not present, then NULL is passed in
   88830 ** place of the corresponding WhereTerm.
   88831 **
   88832 ** The nEq parameter is passed the index of the index column subject to the
   88833 ** range constraint. Or, equivalently, the number of equality constraints
   88834 ** optimized by the proposed index scan. For example, assuming index p is
   88835 ** on t1(a, b), and the SQL query is:
   88836 **
   88837 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
   88838 **
   88839 ** then nEq should be passed the value 1 (as the range restricted column,
   88840 ** b, is the second left-most column of the index). Or, if the query is:
   88841 **
   88842 **   ... FROM t1 WHERE a > ? AND a < ? ...
   88843 **
   88844 ** then nEq should be passed 0.
   88845 **
   88846 ** The returned value is an integer between 1 and 100, inclusive. A return
   88847 ** value of 1 indicates that the proposed range scan is expected to visit
   88848 ** approximately 1/100th (1%) of the rows selected by the nEq equality
   88849 ** constraints (if any). A return value of 100 indicates that it is expected
   88850 ** that the range scan will visit every row (100%) selected by the equality
   88851 ** constraints.
   88852 **
   88853 ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
   88854 ** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
   88855 ** results in a return of 33 and a range constraint (x>? AND x<?) results
   88856 ** in a return of 11.
   88857 */
   88858 static int whereRangeScanEst(
   88859   Parse *pParse,       /* Parsing & code generating context */
   88860   Index *p,            /* The index containing the range-compared column; "x" */
   88861   int nEq,             /* index into p->aCol[] of the range-compared column */
   88862   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
   88863   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
   88864   int *piEst           /* OUT: Return value */
   88865 ){
   88866   int rc = SQLITE_OK;
   88867 
   88868 #ifdef SQLITE_ENABLE_STAT2
   88869 
   88870   if( nEq==0 && p->aSample ){
   88871     sqlite3_value *pLowerVal = 0;
   88872     sqlite3_value *pUpperVal = 0;
   88873     int iEst;
   88874     int iLower = 0;
   88875     int iUpper = SQLITE_INDEX_SAMPLES;
   88876     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
   88877 
   88878     if( pLower ){
   88879       Expr *pExpr = pLower->pExpr->pRight;
   88880       rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
   88881     }
   88882     if( rc==SQLITE_OK && pUpper ){
   88883       Expr *pExpr = pUpper->pExpr->pRight;
   88884       rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
   88885     }
   88886 
   88887     if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
   88888       sqlite3ValueFree(pLowerVal);
   88889       sqlite3ValueFree(pUpperVal);
   88890       goto range_est_fallback;
   88891     }else if( pLowerVal==0 ){
   88892       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
   88893       if( pLower ) iLower = iUpper/2;
   88894     }else if( pUpperVal==0 ){
   88895       rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
   88896       if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
   88897     }else{
   88898       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
   88899       if( rc==SQLITE_OK ){
   88900         rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
   88901       }
   88902     }
   88903 
   88904     iEst = iUpper - iLower;
   88905     testcase( iEst==SQLITE_INDEX_SAMPLES );
   88906     assert( iEst<=SQLITE_INDEX_SAMPLES );
   88907     if( iEst<1 ){
   88908       iEst = 1;
   88909     }
   88910 
   88911     sqlite3ValueFree(pLowerVal);
   88912     sqlite3ValueFree(pUpperVal);
   88913     *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
   88914     return rc;
   88915   }
   88916 range_est_fallback:
   88917 #else
   88918   UNUSED_PARAMETER(pParse);
   88919   UNUSED_PARAMETER(p);
   88920   UNUSED_PARAMETER(nEq);
   88921 #endif
   88922   assert( pLower || pUpper );
   88923   if( pLower && pUpper ){
   88924     *piEst = 11;
   88925   }else{
   88926     *piEst = 33;
   88927   }
   88928   return rc;
   88929 }
   88930 
   88931 
   88932 /*
   88933 ** Find the query plan for accessing a particular table.  Write the
   88934 ** best query plan and its cost into the WhereCost object supplied as the
   88935 ** last parameter.
   88936 **
   88937 ** The lowest cost plan wins.  The cost is an estimate of the amount of
   88938 ** CPU and disk I/O need to process the request using the selected plan.
   88939 ** Factors that influence cost include:
   88940 **
   88941 **    *  The estimated number of rows that will be retrieved.  (The
   88942 **       fewer the better.)
   88943 **
   88944 **    *  Whether or not sorting must occur.
   88945 **
   88946 **    *  Whether or not there must be separate lookups in the
   88947 **       index and in the main table.
   88948 **
   88949 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
   88950 ** the SQL statement, then this function only considers plans using the
   88951 ** named index. If no such plan is found, then the returned cost is
   88952 ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
   88953 ** then the cost is calculated in the usual way.
   88954 **
   88955 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
   88956 ** in the SELECT statement, then no indexes are considered. However, the
   88957 ** selected plan may still take advantage of the tables built-in rowid
   88958 ** index.
   88959 */
   88960 static void bestBtreeIndex(
   88961   Parse *pParse,              /* The parsing context */
   88962   WhereClause *pWC,           /* The WHERE clause */
   88963   struct SrcList_item *pSrc,  /* The FROM clause term to search */
   88964   Bitmask notReady,           /* Mask of cursors that are not available */
   88965   ExprList *pOrderBy,         /* The ORDER BY clause */
   88966   WhereCost *pCost            /* Lowest cost query plan */
   88967 ){
   88968   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
   88969   Index *pProbe;              /* An index we are evaluating */
   88970   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
   88971   int eqTermMask;             /* Current mask of valid equality operators */
   88972   int idxEqTermMask;          /* Index mask of valid equality operators */
   88973   Index sPk;                  /* A fake index object for the primary key */
   88974   unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
   88975   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
   88976   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
   88977 
   88978   /* Initialize the cost to a worst-case value */
   88979   memset(pCost, 0, sizeof(*pCost));
   88980   pCost->rCost = SQLITE_BIG_DBL;
   88981 
   88982   /* If the pSrc table is the right table of a LEFT JOIN then we may not
   88983   ** use an index to satisfy IS NULL constraints on that table.  This is
   88984   ** because columns might end up being NULL if the table does not match -
   88985   ** a circumstance which the index cannot help us discover.  Ticket #2177.
   88986   */
   88987   if( pSrc->jointype & JT_LEFT ){
   88988     idxEqTermMask = WO_EQ|WO_IN;
   88989   }else{
   88990     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
   88991   }
   88992 
   88993   if( pSrc->pIndex ){
   88994     /* An INDEXED BY clause specifies a particular index to use */
   88995     pIdx = pProbe = pSrc->pIndex;
   88996     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
   88997     eqTermMask = idxEqTermMask;
   88998   }else{
   88999     /* There is no INDEXED BY clause.  Create a fake Index object to
   89000     ** represent the primary key */
   89001     Index *pFirst;                /* Any other index on the table */
   89002     memset(&sPk, 0, sizeof(Index));
   89003     sPk.nColumn = 1;
   89004     sPk.aiColumn = &aiColumnPk;
   89005     sPk.aiRowEst = aiRowEstPk;
   89006     aiRowEstPk[1] = 1;
   89007     sPk.onError = OE_Replace;
   89008     sPk.pTable = pSrc->pTab;
   89009     pFirst = pSrc->pTab->pIndex;
   89010     if( pSrc->notIndexed==0 ){
   89011       sPk.pNext = pFirst;
   89012     }
   89013     /* The aiRowEstPk[0] is an estimate of the total number of rows in the
   89014     ** table.  Get this information from the ANALYZE information if it is
   89015     ** available.  If not available, assume the table 1 million rows in size.
   89016     */
   89017     if( pFirst ){
   89018       assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */
   89019       aiRowEstPk[0] = pFirst->aiRowEst[0];
   89020     }else{
   89021       aiRowEstPk[0] = 1000000;
   89022     }
   89023     pProbe = &sPk;
   89024     wsFlagMask = ~(
   89025         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
   89026     );
   89027     eqTermMask = WO_EQ|WO_IN;
   89028     pIdx = 0;
   89029   }
   89030 
   89031   /* Loop over all indices looking for the best one to use
   89032   */
   89033   for(; pProbe; pIdx=pProbe=pProbe->pNext){
   89034     const unsigned int * const aiRowEst = pProbe->aiRowEst;
   89035     double cost;                /* Cost of using pProbe */
   89036     double nRow;                /* Estimated number of rows in result set */
   89037     int rev;                    /* True to scan in reverse order */
   89038     int wsFlags = 0;
   89039     Bitmask used = 0;
   89040 
   89041     /* The following variables are populated based on the properties of
   89042     ** scan being evaluated. They are then used to determine the expected
   89043     ** cost and number of rows returned.
   89044     **
   89045     **  nEq:
   89046     **    Number of equality terms that can be implemented using the index.
   89047     **
   89048     **  nInMul:
   89049     **    The "in-multiplier". This is an estimate of how many seek operations
   89050     **    SQLite must perform on the index in question. For example, if the
   89051     **    WHERE clause is:
   89052     **
   89053     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
   89054     **
   89055     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
   89056     **    set to 9. Given the same schema and either of the following WHERE
   89057     **    clauses:
   89058     **
   89059     **      WHERE a =  1
   89060     **      WHERE a >= 2
   89061     **
   89062     **    nInMul is set to 1.
   89063     **
   89064     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
   89065     **    the sub-select is assumed to return 25 rows for the purposes of
   89066     **    determining nInMul.
   89067     **
   89068     **  bInEst:
   89069     **    Set to true if there was at least one "x IN (SELECT ...)" term used
   89070     **    in determining the value of nInMul.
   89071     **
   89072     **  nBound:
   89073     **    An estimate on the amount of the table that must be searched.  A
   89074     **    value of 100 means the entire table is searched.  Range constraints
   89075     **    might reduce this to a value less than 100 to indicate that only
   89076     **    a fraction of the table needs searching.  In the absence of
   89077     **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
   89078     **    space to 1/3rd its original size.  So an x>? constraint reduces
   89079     **    nBound to 33.  Two constraints (x>? AND x<?) reduce nBound to 11.
   89080     **
   89081     **  bSort:
   89082     **    Boolean. True if there is an ORDER BY clause that will require an
   89083     **    external sort (i.e. scanning the index being evaluated will not
   89084     **    correctly order records).
   89085     **
   89086     **  bLookup:
   89087     **    Boolean. True if for each index entry visited a lookup on the
   89088     **    corresponding table b-tree is required. This is always false
   89089     **    for the rowid index. For other indexes, it is true unless all the
   89090     **    columns of the table used by the SELECT statement are present in
   89091     **    the index (such an index is sometimes described as a covering index).
   89092     **    For example, given the index on (a, b), the second of the following
   89093     **    two queries requires table b-tree lookups, but the first does not.
   89094     **
   89095     **             SELECT a, b    FROM tbl WHERE a = 1;
   89096     **             SELECT a, b, c FROM tbl WHERE a = 1;
   89097     */
   89098     int nEq;
   89099     int bInEst = 0;
   89100     int nInMul = 1;
   89101     int nBound = 100;
   89102     int bSort = 0;
   89103     int bLookup = 0;
   89104 
   89105     /* Determine the values of nEq and nInMul */
   89106     for(nEq=0; nEq<pProbe->nColumn; nEq++){
   89107       WhereTerm *pTerm;           /* A single term of the WHERE clause */
   89108       int j = pProbe->aiColumn[nEq];
   89109       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
   89110       if( pTerm==0 ) break;
   89111       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
   89112       if( pTerm->eOperator & WO_IN ){
   89113         Expr *pExpr = pTerm->pExpr;
   89114         wsFlags |= WHERE_COLUMN_IN;
   89115         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   89116           nInMul *= 25;
   89117           bInEst = 1;
   89118         }else if( pExpr->x.pList ){
   89119           nInMul *= pExpr->x.pList->nExpr + 1;
   89120         }
   89121       }else if( pTerm->eOperator & WO_ISNULL ){
   89122         wsFlags |= WHERE_COLUMN_NULL;
   89123       }
   89124       used |= pTerm->prereqRight;
   89125     }
   89126 
   89127     /* Determine the value of nBound. */
   89128     if( nEq<pProbe->nColumn ){
   89129       int j = pProbe->aiColumn[nEq];
   89130       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
   89131         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
   89132         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
   89133         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &nBound);
   89134         if( pTop ){
   89135           wsFlags |= WHERE_TOP_LIMIT;
   89136           used |= pTop->prereqRight;
   89137         }
   89138         if( pBtm ){
   89139           wsFlags |= WHERE_BTM_LIMIT;
   89140           used |= pBtm->prereqRight;
   89141         }
   89142         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
   89143       }
   89144     }else if( pProbe->onError!=OE_None ){
   89145       testcase( wsFlags & WHERE_COLUMN_IN );
   89146       testcase( wsFlags & WHERE_COLUMN_NULL );
   89147       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
   89148         wsFlags |= WHERE_UNIQUE;
   89149       }
   89150     }
   89151 
   89152     /* If there is an ORDER BY clause and the index being considered will
   89153     ** naturally scan rows in the required order, set the appropriate flags
   89154     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
   89155     ** will scan rows in a different order, set the bSort variable.  */
   89156     if( pOrderBy ){
   89157       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
   89158         && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
   89159       ){
   89160         wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
   89161         wsFlags |= (rev ? WHERE_REVERSE : 0);
   89162       }else{
   89163         bSort = 1;
   89164       }
   89165     }
   89166 
   89167     /* If currently calculating the cost of using an index (not the IPK
   89168     ** index), determine if all required column data may be obtained without
   89169     ** seeking to entries in the main table (i.e. if the index is a covering
   89170     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
   89171     ** wsFlags. Otherwise, set the bLookup variable to true.  */
   89172     if( pIdx && wsFlags ){
   89173       Bitmask m = pSrc->colUsed;
   89174       int j;
   89175       for(j=0; j<pIdx->nColumn; j++){
   89176         int x = pIdx->aiColumn[j];
   89177         if( x<BMS-1 ){
   89178           m &= ~(((Bitmask)1)<<x);
   89179         }
   89180       }
   89181       if( m==0 ){
   89182         wsFlags |= WHERE_IDX_ONLY;
   89183       }else{
   89184         bLookup = 1;
   89185       }
   89186     }
   89187 
   89188     /**** Begin adding up the cost of using this index (Needs improvements)
   89189     **
   89190     ** Estimate the number of rows of output.  For an IN operator,
   89191     ** do not let the estimate exceed half the rows in the table.
   89192     */
   89193     nRow = (double)(aiRowEst[nEq] * nInMul);
   89194     if( bInEst && nRow*2>aiRowEst[0] ){
   89195       nRow = aiRowEst[0]/2;
   89196       nInMul = (int)(nRow / aiRowEst[nEq]);
   89197     }
   89198 
   89199     /* Assume constant cost to access a row and logarithmic cost to
   89200     ** do a binary search.  Hence, the initial cost is the number of output
   89201     ** rows plus log2(table-size) times the number of binary searches.
   89202     */
   89203     cost = nRow + nInMul*estLog(aiRowEst[0]);
   89204 
   89205     /* Adjust the number of rows and the cost downward to reflect rows
   89206     ** that are excluded by range constraints.
   89207     */
   89208     nRow = (nRow * (double)nBound) / (double)100;
   89209     cost = (cost * (double)nBound) / (double)100;
   89210 
   89211     /* Add in the estimated cost of sorting the result
   89212     */
   89213     if( bSort ){
   89214       cost += cost*estLog(cost);
   89215     }
   89216 
   89217     /* If all information can be taken directly from the index, we avoid
   89218     ** doing table lookups.  This reduces the cost by half.  (Not really -
   89219     ** this needs to be fixed.)
   89220     */
   89221     if( pIdx && bLookup==0 ){
   89222       cost /= (double)2;
   89223     }
   89224     /**** Cost of using this index has now been computed ****/
   89225 
   89226     WHERETRACE((
   89227       "tbl=%s idx=%s nEq=%d nInMul=%d nBound=%d bSort=%d bLookup=%d"
   89228       " wsFlags=%d   (nRow=%.2f cost=%.2f)\n",
   89229       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
   89230       nEq, nInMul, nBound, bSort, bLookup, wsFlags, nRow, cost
   89231     ));
   89232 
   89233     /* If this index is the best we have seen so far, then record this
   89234     ** index and its cost in the pCost structure.
   89235     */
   89236     if( (!pIdx || wsFlags) && cost<pCost->rCost ){
   89237       pCost->rCost = cost;
   89238       pCost->nRow = nRow;
   89239       pCost->used = used;
   89240       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
   89241       pCost->plan.nEq = nEq;
   89242       pCost->plan.u.pIdx = pIdx;
   89243     }
   89244 
   89245     /* If there was an INDEXED BY clause, then only that one index is
   89246     ** considered. */
   89247     if( pSrc->pIndex ) break;
   89248 
   89249     /* Reset masks for the next index in the loop */
   89250     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
   89251     eqTermMask = idxEqTermMask;
   89252   }
   89253 
   89254   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
   89255   ** is set, then reverse the order that the index will be scanned
   89256   ** in. This is used for application testing, to help find cases
   89257   ** where application behaviour depends on the (undefined) order that
   89258   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
   89259   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
   89260     pCost->plan.wsFlags |= WHERE_REVERSE;
   89261   }
   89262 
   89263   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
   89264   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
   89265   assert( pSrc->pIndex==0
   89266        || pCost->plan.u.pIdx==0
   89267        || pCost->plan.u.pIdx==pSrc->pIndex
   89268   );
   89269 
   89270   WHERETRACE(("best index is: %s\n",
   89271     (pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
   89272   ));
   89273 
   89274   bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
   89275   pCost->plan.wsFlags |= eqTermMask;
   89276 }
   89277 
   89278 /*
   89279 ** Find the query plan for accessing table pSrc->pTab. Write the
   89280 ** best query plan and its cost into the WhereCost object supplied
   89281 ** as the last parameter. This function may calculate the cost of
   89282 ** both real and virtual table scans.
   89283 */
   89284 static void bestIndex(
   89285   Parse *pParse,              /* The parsing context */
   89286   WhereClause *pWC,           /* The WHERE clause */
   89287   struct SrcList_item *pSrc,  /* The FROM clause term to search */
   89288   Bitmask notReady,           /* Mask of cursors that are not available */
   89289   ExprList *pOrderBy,         /* The ORDER BY clause */
   89290   WhereCost *pCost            /* Lowest cost query plan */
   89291 ){
   89292 #ifndef SQLITE_OMIT_VIRTUALTABLE
   89293   if( IsVirtual(pSrc->pTab) ){
   89294     sqlite3_index_info *p = 0;
   89295     bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p);
   89296     if( p->needToFreeIdxStr ){
   89297       sqlite3_free(p->idxStr);
   89298     }
   89299     sqlite3DbFree(pParse->db, p);
   89300   }else
   89301 #endif
   89302   {
   89303     bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
   89304   }
   89305 }
   89306 
   89307 /*
   89308 ** Disable a term in the WHERE clause.  Except, do not disable the term
   89309 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
   89310 ** or USING clause of that join.
   89311 **
   89312 ** Consider the term t2.z='ok' in the following queries:
   89313 **
   89314 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
   89315 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
   89316 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
   89317 **
   89318 ** The t2.z='ok' is disabled in the in (2) because it originates
   89319 ** in the ON clause.  The term is disabled in (3) because it is not part
   89320 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
   89321 **
   89322 ** Disabling a term causes that term to not be tested in the inner loop
   89323 ** of the join.  Disabling is an optimization.  When terms are satisfied
   89324 ** by indices, we disable them to prevent redundant tests in the inner
   89325 ** loop.  We would get the correct results if nothing were ever disabled,
   89326 ** but joins might run a little slower.  The trick is to disable as much
   89327 ** as we can without disabling too much.  If we disabled in (1), we'd get
   89328 ** the wrong answer.  See ticket #813.
   89329 */
   89330 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
   89331   if( pTerm
   89332       && ALWAYS((pTerm->wtFlags & TERM_CODED)==0)
   89333       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
   89334   ){
   89335     pTerm->wtFlags |= TERM_CODED;
   89336     if( pTerm->iParent>=0 ){
   89337       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
   89338       if( (--pOther->nChild)==0 ){
   89339         disableTerm(pLevel, pOther);
   89340       }
   89341     }
   89342   }
   89343 }
   89344 
   89345 /*
   89346 ** Code an OP_Affinity opcode to apply the column affinity string zAff
   89347 ** to the n registers starting at base.
   89348 **
   89349 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
   89350 ** beginning and end of zAff are ignored.  If all entries in zAff are
   89351 ** SQLITE_AFF_NONE, then no code gets generated.
   89352 **
   89353 ** This routine makes its own copy of zAff so that the caller is free
   89354 ** to modify zAff after this routine returns.
   89355 */
   89356 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
   89357   Vdbe *v = pParse->pVdbe;
   89358   if( zAff==0 ){
   89359     assert( pParse->db->mallocFailed );
   89360     return;
   89361   }
   89362   assert( v!=0 );
   89363 
   89364   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
   89365   ** and end of the affinity string.
   89366   */
   89367   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
   89368     n--;
   89369     base++;
   89370     zAff++;
   89371   }
   89372   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
   89373     n--;
   89374   }
   89375 
   89376   /* Code the OP_Affinity opcode if there is anything left to do. */
   89377   if( n>0 ){
   89378     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
   89379     sqlite3VdbeChangeP4(v, -1, zAff, n);
   89380     sqlite3ExprCacheAffinityChange(pParse, base, n);
   89381   }
   89382 }
   89383 
   89384 
   89385 /*
   89386 ** Generate code for a single equality term of the WHERE clause.  An equality
   89387 ** term can be either X=expr or X IN (...).   pTerm is the term to be
   89388 ** coded.
   89389 **
   89390 ** The current value for the constraint is left in register iReg.
   89391 **
   89392 ** For a constraint of the form X=expr, the expression is evaluated and its
   89393 ** result is left on the stack.  For constraints of the form X IN (...)
   89394 ** this routine sets up a loop that will iterate over all values of X.
   89395 */
   89396 static int codeEqualityTerm(
   89397   Parse *pParse,      /* The parsing context */
   89398   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
   89399   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
   89400   int iTarget         /* Attempt to leave results in this register */
   89401 ){
   89402   Expr *pX = pTerm->pExpr;
   89403   Vdbe *v = pParse->pVdbe;
   89404   int iReg;                  /* Register holding results */
   89405 
   89406   assert( iTarget>0 );
   89407   if( pX->op==TK_EQ ){
   89408     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
   89409   }else if( pX->op==TK_ISNULL ){
   89410     iReg = iTarget;
   89411     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
   89412 #ifndef SQLITE_OMIT_SUBQUERY
   89413   }else{
   89414     int eType;
   89415     int iTab;
   89416     struct InLoop *pIn;
   89417 
   89418     assert( pX->op==TK_IN );
   89419     iReg = iTarget;
   89420     eType = sqlite3FindInIndex(pParse, pX, 0);
   89421     iTab = pX->iTable;
   89422     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
   89423     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
   89424     if( pLevel->u.in.nIn==0 ){
   89425       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
   89426     }
   89427     pLevel->u.in.nIn++;
   89428     pLevel->u.in.aInLoop =
   89429        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
   89430                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
   89431     pIn = pLevel->u.in.aInLoop;
   89432     if( pIn ){
   89433       pIn += pLevel->u.in.nIn - 1;
   89434       pIn->iCur = iTab;
   89435       if( eType==IN_INDEX_ROWID ){
   89436         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
   89437       }else{
   89438         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
   89439       }
   89440       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
   89441     }else{
   89442       pLevel->u.in.nIn = 0;
   89443     }
   89444 #endif
   89445   }
   89446   disableTerm(pLevel, pTerm);
   89447   return iReg;
   89448 }
   89449 
   89450 /*
   89451 ** Generate code that will evaluate all == and IN constraints for an
   89452 ** index.
   89453 **
   89454 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
   89455 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
   89456 ** The index has as many as three equality constraints, but in this
   89457 ** example, the third "c" value is an inequality.  So only two
   89458 ** constraints are coded.  This routine will generate code to evaluate
   89459 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
   89460 ** in consecutive registers and the index of the first register is returned.
   89461 **
   89462 ** In the example above nEq==2.  But this subroutine works for any value
   89463 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
   89464 ** The only thing it does is allocate the pLevel->iMem memory cell and
   89465 ** compute the affinity string.
   89466 **
   89467 ** This routine always allocates at least one memory cell and returns
   89468 ** the index of that memory cell. The code that
   89469 ** calls this routine will use that memory cell to store the termination
   89470 ** key value of the loop.  If one or more IN operators appear, then
   89471 ** this routine allocates an additional nEq memory cells for internal
   89472 ** use.
   89473 **
   89474 ** Before returning, *pzAff is set to point to a buffer containing a
   89475 ** copy of the column affinity string of the index allocated using
   89476 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
   89477 ** with equality constraints that use NONE affinity are set to
   89478 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
   89479 **
   89480 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
   89481 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
   89482 **
   89483 ** In the example above, the index on t1(a) has TEXT affinity. But since
   89484 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
   89485 ** no conversion should be attempted before using a t2.b value as part of
   89486 ** a key to search the index. Hence the first byte in the returned affinity
   89487 ** string in this example would be set to SQLITE_AFF_NONE.
   89488 */
   89489 static int codeAllEqualityTerms(
   89490   Parse *pParse,        /* Parsing context */
   89491   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
   89492   WhereClause *pWC,     /* The WHERE clause */
   89493   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
   89494   int nExtraReg,        /* Number of extra registers to allocate */
   89495   char **pzAff          /* OUT: Set to point to affinity string */
   89496 ){
   89497   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
   89498   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
   89499   Index *pIdx;                  /* The index being used for this loop */
   89500   int iCur = pLevel->iTabCur;   /* The cursor of the table */
   89501   WhereTerm *pTerm;             /* A single constraint term */
   89502   int j;                        /* Loop counter */
   89503   int regBase;                  /* Base register */
   89504   int nReg;                     /* Number of registers to allocate */
   89505   char *zAff;                   /* Affinity string to return */
   89506 
   89507   /* This module is only called on query plans that use an index. */
   89508   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
   89509   pIdx = pLevel->plan.u.pIdx;
   89510 
   89511   /* Figure out how many memory cells we will need then allocate them.
   89512   */
   89513   regBase = pParse->nMem + 1;
   89514   nReg = pLevel->plan.nEq + nExtraReg;
   89515   pParse->nMem += nReg;
   89516 
   89517   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
   89518   if( !zAff ){
   89519     pParse->db->mallocFailed = 1;
   89520   }
   89521 
   89522   /* Evaluate the equality constraints
   89523   */
   89524   assert( pIdx->nColumn>=nEq );
   89525   for(j=0; j<nEq; j++){
   89526     int r1;
   89527     int k = pIdx->aiColumn[j];
   89528     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
   89529     if( NEVER(pTerm==0) ) break;
   89530     assert( (pTerm->wtFlags & TERM_CODED)==0 );
   89531     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
   89532     if( r1!=regBase+j ){
   89533       if( nReg==1 ){
   89534         sqlite3ReleaseTempReg(pParse, regBase);
   89535         regBase = r1;
   89536       }else{
   89537         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
   89538       }
   89539     }
   89540     testcase( pTerm->eOperator & WO_ISNULL );
   89541     testcase( pTerm->eOperator & WO_IN );
   89542     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
   89543       Expr *pRight = pTerm->pExpr->pRight;
   89544       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
   89545       if( zAff ){
   89546         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
   89547           zAff[j] = SQLITE_AFF_NONE;
   89548         }
   89549         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
   89550           zAff[j] = SQLITE_AFF_NONE;
   89551         }
   89552       }
   89553     }
   89554   }
   89555   *pzAff = zAff;
   89556   return regBase;
   89557 }
   89558 
   89559 /*
   89560 ** Generate code for the start of the iLevel-th loop in the WHERE clause
   89561 ** implementation described by pWInfo.
   89562 */
   89563 static Bitmask codeOneLoopStart(
   89564   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
   89565   int iLevel,          /* Which level of pWInfo->a[] should be coded */
   89566   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
   89567   Bitmask notReady     /* Which tables are currently available */
   89568 ){
   89569   int j, k;            /* Loop counters */
   89570   int iCur;            /* The VDBE cursor for the table */
   89571   int addrNxt;         /* Where to jump to continue with the next IN case */
   89572   int omitTable;       /* True if we use the index only */
   89573   int bRev;            /* True if we need to scan in reverse order */
   89574   WhereLevel *pLevel;  /* The where level to be coded */
   89575   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
   89576   WhereTerm *pTerm;               /* A WHERE clause term */
   89577   Parse *pParse;                  /* Parsing context */
   89578   Vdbe *v;                        /* The prepared stmt under constructions */
   89579   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
   89580   int addrBrk;                    /* Jump here to break out of the loop */
   89581   int addrCont;                   /* Jump here to continue with next cycle */
   89582   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
   89583   int iReleaseReg = 0;      /* Temp register to free before returning */
   89584 
   89585   pParse = pWInfo->pParse;
   89586   v = pParse->pVdbe;
   89587   pWC = pWInfo->pWC;
   89588   pLevel = &pWInfo->a[iLevel];
   89589   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
   89590   iCur = pTabItem->iCursor;
   89591   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
   89592   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
   89593            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
   89594 
   89595   /* Create labels for the "break" and "continue" instructions
   89596   ** for the current loop.  Jump to addrBrk to break out of a loop.
   89597   ** Jump to cont to go immediately to the next iteration of the
   89598   ** loop.
   89599   **
   89600   ** When there is an IN operator, we also have a "addrNxt" label that
   89601   ** means to continue with the next IN value combination.  When
   89602   ** there are no IN operators in the constraints, the "addrNxt" label
   89603   ** is the same as "addrBrk".
   89604   */
   89605   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
   89606   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
   89607 
   89608   /* If this is the right table of a LEFT OUTER JOIN, allocate and
   89609   ** initialize a memory cell that records if this table matches any
   89610   ** row of the left table of the join.
   89611   */
   89612   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
   89613     pLevel->iLeftJoin = ++pParse->nMem;
   89614     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
   89615     VdbeComment((v, "init LEFT JOIN no-match flag"));
   89616   }
   89617 
   89618 #ifndef SQLITE_OMIT_VIRTUALTABLE
   89619   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
   89620     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
   89621     **          to access the data.
   89622     */
   89623     int iReg;   /* P3 Value for OP_VFilter */
   89624     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
   89625     int nConstraint = pVtabIdx->nConstraint;
   89626     struct sqlite3_index_constraint_usage *aUsage =
   89627                                                 pVtabIdx->aConstraintUsage;
   89628     const struct sqlite3_index_constraint *aConstraint =
   89629                                                 pVtabIdx->aConstraint;
   89630 
   89631     sqlite3ExprCachePush(pParse);
   89632     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
   89633     for(j=1; j<=nConstraint; j++){
   89634       for(k=0; k<nConstraint; k++){
   89635         if( aUsage[k].argvIndex==j ){
   89636           int iTerm = aConstraint[k].iTermOffset;
   89637           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
   89638           break;
   89639         }
   89640       }
   89641       if( k==nConstraint ) break;
   89642     }
   89643     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
   89644     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
   89645     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
   89646                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
   89647     pVtabIdx->needToFreeIdxStr = 0;
   89648     for(j=0; j<nConstraint; j++){
   89649       if( aUsage[j].omit ){
   89650         int iTerm = aConstraint[j].iTermOffset;
   89651         disableTerm(pLevel, &pWC->a[iTerm]);
   89652       }
   89653     }
   89654     pLevel->op = OP_VNext;
   89655     pLevel->p1 = iCur;
   89656     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
   89657     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
   89658     sqlite3ExprCachePop(pParse, 1);
   89659   }else
   89660 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   89661 
   89662   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
   89663     /* Case 1:  We can directly reference a single row using an
   89664     **          equality comparison against the ROWID field.  Or
   89665     **          we reference multiple rows using a "rowid IN (...)"
   89666     **          construct.
   89667     */
   89668     iReleaseReg = sqlite3GetTempReg(pParse);
   89669     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
   89670     assert( pTerm!=0 );
   89671     assert( pTerm->pExpr!=0 );
   89672     assert( pTerm->leftCursor==iCur );
   89673     assert( omitTable==0 );
   89674     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
   89675     addrNxt = pLevel->addrNxt;
   89676     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
   89677     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
   89678     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   89679     VdbeComment((v, "pk"));
   89680     pLevel->op = OP_Noop;
   89681   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
   89682     /* Case 2:  We have an inequality comparison against the ROWID field.
   89683     */
   89684     int testOp = OP_Noop;
   89685     int start;
   89686     int memEndValue = 0;
   89687     WhereTerm *pStart, *pEnd;
   89688 
   89689     assert( omitTable==0 );
   89690     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
   89691     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
   89692     if( bRev ){
   89693       pTerm = pStart;
   89694       pStart = pEnd;
   89695       pEnd = pTerm;
   89696     }
   89697     if( pStart ){
   89698       Expr *pX;             /* The expression that defines the start bound */
   89699       int r1, rTemp;        /* Registers for holding the start boundary */
   89700 
   89701       /* The following constant maps TK_xx codes into corresponding
   89702       ** seek opcodes.  It depends on a particular ordering of TK_xx
   89703       */
   89704       const u8 aMoveOp[] = {
   89705            /* TK_GT */  OP_SeekGt,
   89706            /* TK_LE */  OP_SeekLe,
   89707            /* TK_LT */  OP_SeekLt,
   89708            /* TK_GE */  OP_SeekGe
   89709       };
   89710       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
   89711       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
   89712       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
   89713 
   89714       pX = pStart->pExpr;
   89715       assert( pX!=0 );
   89716       assert( pStart->leftCursor==iCur );
   89717       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
   89718       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
   89719       VdbeComment((v, "pk"));
   89720       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
   89721       sqlite3ReleaseTempReg(pParse, rTemp);
   89722       disableTerm(pLevel, pStart);
   89723     }else{
   89724       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
   89725     }
   89726     if( pEnd ){
   89727       Expr *pX;
   89728       pX = pEnd->pExpr;
   89729       assert( pX!=0 );
   89730       assert( pEnd->leftCursor==iCur );
   89731       memEndValue = ++pParse->nMem;
   89732       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
   89733       if( pX->op==TK_LT || pX->op==TK_GT ){
   89734         testOp = bRev ? OP_Le : OP_Ge;
   89735       }else{
   89736         testOp = bRev ? OP_Lt : OP_Gt;
   89737       }
   89738       disableTerm(pLevel, pEnd);
   89739     }
   89740     start = sqlite3VdbeCurrentAddr(v);
   89741     pLevel->op = bRev ? OP_Prev : OP_Next;
   89742     pLevel->p1 = iCur;
   89743     pLevel->p2 = start;
   89744     pLevel->p5 = (pStart==0 && pEnd==0) ?1:0;
   89745     if( testOp!=OP_Noop ){
   89746       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
   89747       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
   89748       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   89749       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
   89750       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
   89751     }
   89752   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
   89753     /* Case 3: A scan using an index.
   89754     **
   89755     **         The WHERE clause may contain zero or more equality
   89756     **         terms ("==" or "IN" operators) that refer to the N
   89757     **         left-most columns of the index. It may also contain
   89758     **         inequality constraints (>, <, >= or <=) on the indexed
   89759     **         column that immediately follows the N equalities. Only
   89760     **         the right-most column can be an inequality - the rest must
   89761     **         use the "==" and "IN" operators. For example, if the
   89762     **         index is on (x,y,z), then the following clauses are all
   89763     **         optimized:
   89764     **
   89765     **            x=5
   89766     **            x=5 AND y=10
   89767     **            x=5 AND y<10
   89768     **            x=5 AND y>5 AND y<10
   89769     **            x=5 AND y=5 AND z<=10
   89770     **
   89771     **         The z<10 term of the following cannot be used, only
   89772     **         the x=5 term:
   89773     **
   89774     **            x=5 AND z<10
   89775     **
   89776     **         N may be zero if there are inequality constraints.
   89777     **         If there are no inequality constraints, then N is at
   89778     **         least one.
   89779     **
   89780     **         This case is also used when there are no WHERE clause
   89781     **         constraints but an index is selected anyway, in order
   89782     **         to force the output order to conform to an ORDER BY.
   89783     */
   89784     int aStartOp[] = {
   89785       0,
   89786       0,
   89787       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
   89788       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
   89789       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
   89790       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
   89791       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
   89792       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
   89793     };
   89794     int aEndOp[] = {
   89795       OP_Noop,             /* 0: (!end_constraints) */
   89796       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
   89797       OP_IdxLT             /* 2: (end_constraints && bRev) */
   89798     };
   89799     int nEq = pLevel->plan.nEq;
   89800     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
   89801     int regBase;                 /* Base register holding constraint values */
   89802     int r1;                      /* Temp register */
   89803     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
   89804     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
   89805     int startEq;                 /* True if range start uses ==, >= or <= */
   89806     int endEq;                   /* True if range end uses ==, >= or <= */
   89807     int start_constraints;       /* Start of range is constrained */
   89808     int nConstraint;             /* Number of constraint terms */
   89809     Index *pIdx;         /* The index we will be using */
   89810     int iIdxCur;         /* The VDBE cursor for the index */
   89811     int nExtraReg = 0;   /* Number of extra registers needed */
   89812     int op;              /* Instruction opcode */
   89813     char *zAff;
   89814 
   89815     pIdx = pLevel->plan.u.pIdx;
   89816     iIdxCur = pLevel->iIdxCur;
   89817     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
   89818 
   89819     /* If this loop satisfies a sort order (pOrderBy) request that
   89820     ** was passed to this function to implement a "SELECT min(x) ..."
   89821     ** query, then the caller will only allow the loop to run for
   89822     ** a single iteration. This means that the first row returned
   89823     ** should not have a NULL value stored in 'x'. If column 'x' is
   89824     ** the first one after the nEq equality constraints in the index,
   89825     ** this requires some special handling.
   89826     */
   89827     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
   89828      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
   89829      && (pIdx->nColumn>nEq)
   89830     ){
   89831       /* assert( pOrderBy->nExpr==1 ); */
   89832       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
   89833       isMinQuery = 1;
   89834       nExtraReg = 1;
   89835     }
   89836 
   89837     /* Find any inequality constraint terms for the start and end
   89838     ** of the range.
   89839     */
   89840     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
   89841       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
   89842       nExtraReg = 1;
   89843     }
   89844     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
   89845       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
   89846       nExtraReg = 1;
   89847     }
   89848 
   89849     /* Generate code to evaluate all constraint terms using == or IN
   89850     ** and store the values of those terms in an array of registers
   89851     ** starting at regBase.
   89852     */
   89853     regBase = codeAllEqualityTerms(
   89854         pParse, pLevel, pWC, notReady, nExtraReg, &zAff
   89855     );
   89856     addrNxt = pLevel->addrNxt;
   89857 
   89858     /* If we are doing a reverse order scan on an ascending index, or
   89859     ** a forward order scan on a descending index, interchange the
   89860     ** start and end terms (pRangeStart and pRangeEnd).
   89861     */
   89862     if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
   89863       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
   89864     }
   89865 
   89866     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
   89867     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
   89868     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
   89869     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
   89870     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
   89871     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
   89872     start_constraints = pRangeStart || nEq>0;
   89873 
   89874     /* Seek the index cursor to the start of the range. */
   89875     nConstraint = nEq;
   89876     if( pRangeStart ){
   89877       Expr *pRight = pRangeStart->pExpr->pRight;
   89878       sqlite3ExprCode(pParse, pRight, regBase+nEq);
   89879       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
   89880       if( zAff ){
   89881         if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
   89882           /* Since the comparison is to be performed with no conversions
   89883           ** applied to the operands, set the affinity to apply to pRight to
   89884           ** SQLITE_AFF_NONE.  */
   89885           zAff[nConstraint] = SQLITE_AFF_NONE;
   89886         }
   89887         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
   89888           zAff[nConstraint] = SQLITE_AFF_NONE;
   89889         }
   89890       }
   89891       nConstraint++;
   89892     }else if( isMinQuery ){
   89893       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
   89894       nConstraint++;
   89895       startEq = 0;
   89896       start_constraints = 1;
   89897     }
   89898     codeApplyAffinity(pParse, regBase, nConstraint, zAff);
   89899     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
   89900     assert( op!=0 );
   89901     testcase( op==OP_Rewind );
   89902     testcase( op==OP_Last );
   89903     testcase( op==OP_SeekGt );
   89904     testcase( op==OP_SeekGe );
   89905     testcase( op==OP_SeekLe );
   89906     testcase( op==OP_SeekLt );
   89907     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
   89908 
   89909     /* Load the value for the inequality constraint at the end of the
   89910     ** range (if any).
   89911     */
   89912     nConstraint = nEq;
   89913     if( pRangeEnd ){
   89914       Expr *pRight = pRangeEnd->pExpr->pRight;
   89915       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
   89916       sqlite3ExprCode(pParse, pRight, regBase+nEq);
   89917       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
   89918       if( zAff ){
   89919         if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
   89920           /* Since the comparison is to be performed with no conversions
   89921           ** applied to the operands, set the affinity to apply to pRight to
   89922           ** SQLITE_AFF_NONE.  */
   89923           zAff[nConstraint] = SQLITE_AFF_NONE;
   89924         }
   89925         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
   89926           zAff[nConstraint] = SQLITE_AFF_NONE;
   89927         }
   89928       }
   89929       codeApplyAffinity(pParse, regBase, nEq+1, zAff);
   89930       nConstraint++;
   89931     }
   89932     sqlite3DbFree(pParse->db, zAff);
   89933 
   89934     /* Top of the loop body */
   89935     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
   89936 
   89937     /* Check if the index cursor is past the end of the range. */
   89938     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
   89939     testcase( op==OP_Noop );
   89940     testcase( op==OP_IdxGE );
   89941     testcase( op==OP_IdxLT );
   89942     if( op!=OP_Noop ){
   89943       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
   89944       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
   89945     }
   89946 
   89947     /* If there are inequality constraints, check that the value
   89948     ** of the table column that the inequality contrains is not NULL.
   89949     ** If it is, jump to the next iteration of the loop.
   89950     */
   89951     r1 = sqlite3GetTempReg(pParse);
   89952     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
   89953     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
   89954     if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
   89955       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
   89956       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
   89957     }
   89958     sqlite3ReleaseTempReg(pParse, r1);
   89959 
   89960     /* Seek the table cursor, if required */
   89961     disableTerm(pLevel, pRangeStart);
   89962     disableTerm(pLevel, pRangeEnd);
   89963     if( !omitTable ){
   89964       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
   89965       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
   89966       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   89967       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
   89968     }
   89969 
   89970     /* Record the instruction used to terminate the loop. Disable
   89971     ** WHERE clause terms made redundant by the index range scan.
   89972     */
   89973     pLevel->op = bRev ? OP_Prev : OP_Next;
   89974     pLevel->p1 = iIdxCur;
   89975   }else
   89976 
   89977 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
   89978   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
   89979     /* Case 4:  Two or more separately indexed terms connected by OR
   89980     **
   89981     ** Example:
   89982     **
   89983     **   CREATE TABLE t1(a,b,c,d);
   89984     **   CREATE INDEX i1 ON t1(a);
   89985     **   CREATE INDEX i2 ON t1(b);
   89986     **   CREATE INDEX i3 ON t1(c);
   89987     **
   89988     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
   89989     **
   89990     ** In the example, there are three indexed terms connected by OR.
   89991     ** The top of the loop looks like this:
   89992     **
   89993     **          Null       1                # Zero the rowset in reg 1
   89994     **
   89995     ** Then, for each indexed term, the following. The arguments to
   89996     ** RowSetTest are such that the rowid of the current row is inserted
   89997     ** into the RowSet. If it is already present, control skips the
   89998     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
   89999     **
   90000     **        sqlite3WhereBegin(<term>)
   90001     **          RowSetTest                  # Insert rowid into rowset
   90002     **          Gosub      2 A
   90003     **        sqlite3WhereEnd()
   90004     **
   90005     ** Following the above, code to terminate the loop. Label A, the target
   90006     ** of the Gosub above, jumps to the instruction right after the Goto.
   90007     **
   90008     **          Null       1                # Zero the rowset in reg 1
   90009     **          Goto       B                # The loop is finished.
   90010     **
   90011     **       A: <loop body>                 # Return data, whatever.
   90012     **
   90013     **          Return     2                # Jump back to the Gosub
   90014     **
   90015     **       B: <after the loop>
   90016     **
   90017     */
   90018     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
   90019     WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
   90020     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
   90021 
   90022     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
   90023     int regRowset = 0;                        /* Register for RowSet object */
   90024     int regRowid = 0;                         /* Register holding rowid */
   90025     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
   90026     int iRetInit;                             /* Address of regReturn init */
   90027     int untestedTerms = 0;             /* Some terms not completely tested */
   90028     int ii;
   90029 
   90030     pTerm = pLevel->plan.u.pTerm;
   90031     assert( pTerm!=0 );
   90032     assert( pTerm->eOperator==WO_OR );
   90033     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
   90034     pOrWc = &pTerm->u.pOrInfo->wc;
   90035     pFinal = &pOrWc->a[pOrWc->nTerm-1];
   90036     pLevel->op = OP_Return;
   90037     pLevel->p1 = regReturn;
   90038 
   90039     /* Set up a new SrcList ni pOrTab containing the table being scanned
   90040     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
   90041     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
   90042     */
   90043     if( pWInfo->nLevel>1 ){
   90044       int nNotReady;                 /* The number of notReady tables */
   90045       struct SrcList_item *origSrc;     /* Original list of tables */
   90046       nNotReady = pWInfo->nLevel - iLevel - 1;
   90047       pOrTab = sqlite3StackAllocRaw(pParse->db,
   90048                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
   90049       if( pOrTab==0 ) return notReady;
   90050       pOrTab->nAlloc = (i16)(nNotReady + 1);
   90051       pOrTab->nSrc = pOrTab->nAlloc;
   90052       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
   90053       origSrc = pWInfo->pTabList->a;
   90054       for(k=1; k<=nNotReady; k++){
   90055         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
   90056       }
   90057     }else{
   90058       pOrTab = pWInfo->pTabList;
   90059     }
   90060 
   90061     /* Initialize the rowset register to contain NULL. An SQL NULL is
   90062     ** equivalent to an empty rowset.
   90063     **
   90064     ** Also initialize regReturn to contain the address of the instruction
   90065     ** immediately following the OP_Return at the bottom of the loop. This
   90066     ** is required in a few obscure LEFT JOIN cases where control jumps
   90067     ** over the top of the loop into the body of it. In this case the
   90068     ** correct response for the end-of-loop code (the OP_Return) is to
   90069     ** fall through to the next instruction, just as an OP_Next does if
   90070     ** called on an uninitialized cursor.
   90071     */
   90072     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
   90073       regRowset = ++pParse->nMem;
   90074       regRowid = ++pParse->nMem;
   90075       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
   90076     }
   90077     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
   90078 
   90079     for(ii=0; ii<pOrWc->nTerm; ii++){
   90080       WhereTerm *pOrTerm = &pOrWc->a[ii];
   90081       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
   90082         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
   90083         /* Loop through table entries that match term pOrTerm. */
   90084         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
   90085                         WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
   90086                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
   90087         if( pSubWInfo ){
   90088           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
   90089             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
   90090             int r;
   90091             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
   90092                                          regRowid);
   90093             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
   90094                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
   90095           }
   90096           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
   90097 
   90098           /* The pSubWInfo->untestedTerms flag means that this OR term
   90099           ** contained one or more AND term from a notReady table.  The
   90100           ** terms from the notReady table could not be tested and will
   90101           ** need to be tested later.
   90102           */
   90103           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
   90104 
   90105           /* Finish the loop through table entries that match term pOrTerm. */
   90106           sqlite3WhereEnd(pSubWInfo);
   90107         }
   90108       }
   90109     }
   90110     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
   90111     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
   90112     sqlite3VdbeResolveLabel(v, iLoopBody);
   90113 
   90114     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
   90115     if( !untestedTerms ) disableTerm(pLevel, pTerm);
   90116   }else
   90117 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   90118 
   90119   {
   90120     /* Case 5:  There is no usable index.  We must do a complete
   90121     **          scan of the entire table.
   90122     */
   90123     static const u8 aStep[] = { OP_Next, OP_Prev };
   90124     static const u8 aStart[] = { OP_Rewind, OP_Last };
   90125     assert( bRev==0 || bRev==1 );
   90126     assert( omitTable==0 );
   90127     pLevel->op = aStep[bRev];
   90128     pLevel->p1 = iCur;
   90129     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
   90130     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
   90131   }
   90132   notReady &= ~getMask(pWC->pMaskSet, iCur);
   90133 
   90134   /* Insert code to test every subexpression that can be completely
   90135   ** computed using the current set of tables.
   90136   */
   90137   k = 0;
   90138   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
   90139     Expr *pE;
   90140     testcase( pTerm->wtFlags & TERM_VIRTUAL );
   90141     testcase( pTerm->wtFlags & TERM_CODED );
   90142     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   90143     if( (pTerm->prereqAll & notReady)!=0 ){
   90144       testcase( pWInfo->untestedTerms==0
   90145                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
   90146       pWInfo->untestedTerms = 1;
   90147       continue;
   90148     }
   90149     pE = pTerm->pExpr;
   90150     assert( pE!=0 );
   90151     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
   90152       continue;
   90153     }
   90154     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
   90155     k = 1;
   90156     pTerm->wtFlags |= TERM_CODED;
   90157   }
   90158 
   90159   /* For a LEFT OUTER JOIN, generate code that will record the fact that
   90160   ** at least one row of the right table has matched the left table.
   90161   */
   90162   if( pLevel->iLeftJoin ){
   90163     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
   90164     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
   90165     VdbeComment((v, "record LEFT JOIN hit"));
   90166     sqlite3ExprCacheClear(pParse);
   90167     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
   90168       testcase( pTerm->wtFlags & TERM_VIRTUAL );
   90169       testcase( pTerm->wtFlags & TERM_CODED );
   90170       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   90171       if( (pTerm->prereqAll & notReady)!=0 ){
   90172         assert( pWInfo->untestedTerms );
   90173         continue;
   90174       }
   90175       assert( pTerm->pExpr );
   90176       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
   90177       pTerm->wtFlags |= TERM_CODED;
   90178     }
   90179   }
   90180   sqlite3ReleaseTempReg(pParse, iReleaseReg);
   90181 
   90182   return notReady;
   90183 }
   90184 
   90185 #if defined(SQLITE_TEST)
   90186 /*
   90187 ** The following variable holds a text description of query plan generated
   90188 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
   90189 ** overwrites the previous.  This information is used for testing and
   90190 ** analysis only.
   90191 */
   90192 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
   90193 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
   90194 
   90195 #endif /* SQLITE_TEST */
   90196 
   90197 
   90198 /*
   90199 ** Free a WhereInfo structure
   90200 */
   90201 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
   90202   if( pWInfo ){
   90203     int i;
   90204     for(i=0; i<pWInfo->nLevel; i++){
   90205       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
   90206       if( pInfo ){
   90207         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
   90208         if( pInfo->needToFreeIdxStr ){
   90209           sqlite3_free(pInfo->idxStr);
   90210         }
   90211         sqlite3DbFree(db, pInfo);
   90212       }
   90213     }
   90214     whereClauseClear(pWInfo->pWC);
   90215     sqlite3DbFree(db, pWInfo);
   90216   }
   90217 }
   90218 
   90219 
   90220 /*
   90221 ** Generate the beginning of the loop used for WHERE clause processing.
   90222 ** The return value is a pointer to an opaque structure that contains
   90223 ** information needed to terminate the loop.  Later, the calling routine
   90224 ** should invoke sqlite3WhereEnd() with the return value of this function
   90225 ** in order to complete the WHERE clause processing.
   90226 **
   90227 ** If an error occurs, this routine returns NULL.
   90228 **
   90229 ** The basic idea is to do a nested loop, one loop for each table in
   90230 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
   90231 ** same as a SELECT with only a single table in the FROM clause.)  For
   90232 ** example, if the SQL is this:
   90233 **
   90234 **       SELECT * FROM t1, t2, t3 WHERE ...;
   90235 **
   90236 ** Then the code generated is conceptually like the following:
   90237 **
   90238 **      foreach row1 in t1 do       \    Code generated
   90239 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
   90240 **          foreach row3 in t3 do   /
   90241 **            ...
   90242 **          end                     \    Code generated
   90243 **        end                        |-- by sqlite3WhereEnd()
   90244 **      end                         /
   90245 **
   90246 ** Note that the loops might not be nested in the order in which they
   90247 ** appear in the FROM clause if a different order is better able to make
   90248 ** use of indices.  Note also that when the IN operator appears in
   90249 ** the WHERE clause, it might result in additional nested loops for
   90250 ** scanning through all values on the right-hand side of the IN.
   90251 **
   90252 ** There are Btree cursors associated with each table.  t1 uses cursor
   90253 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
   90254 ** And so forth.  This routine generates code to open those VDBE cursors
   90255 ** and sqlite3WhereEnd() generates the code to close them.
   90256 **
   90257 ** The code that sqlite3WhereBegin() generates leaves the cursors named
   90258 ** in pTabList pointing at their appropriate entries.  The [...] code
   90259 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
   90260 ** data from the various tables of the loop.
   90261 **
   90262 ** If the WHERE clause is empty, the foreach loops must each scan their
   90263 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
   90264 ** the tables have indices and there are terms in the WHERE clause that
   90265 ** refer to those indices, a complete table scan can be avoided and the
   90266 ** code will run much faster.  Most of the work of this routine is checking
   90267 ** to see if there are indices that can be used to speed up the loop.
   90268 **
   90269 ** Terms of the WHERE clause are also used to limit which rows actually
   90270 ** make it to the "..." in the middle of the loop.  After each "foreach",
   90271 ** terms of the WHERE clause that use only terms in that loop and outer
   90272 ** loops are evaluated and if false a jump is made around all subsequent
   90273 ** inner loops (or around the "..." if the test occurs within the inner-
   90274 ** most loop)
   90275 **
   90276 ** OUTER JOINS
   90277 **
   90278 ** An outer join of tables t1 and t2 is conceptally coded as follows:
   90279 **
   90280 **    foreach row1 in t1 do
   90281 **      flag = 0
   90282 **      foreach row2 in t2 do
   90283 **        start:
   90284 **          ...
   90285 **          flag = 1
   90286 **      end
   90287 **      if flag==0 then
   90288 **        move the row2 cursor to a null row
   90289 **        goto start
   90290 **      fi
   90291 **    end
   90292 **
   90293 ** ORDER BY CLAUSE PROCESSING
   90294 **
   90295 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
   90296 ** if there is one.  If there is no ORDER BY clause or if this routine
   90297 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
   90298 **
   90299 ** If an index can be used so that the natural output order of the table
   90300 ** scan is correct for the ORDER BY clause, then that index is used and
   90301 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
   90302 ** unnecessary sort of the result set if an index appropriate for the
   90303 ** ORDER BY clause already exists.
   90304 **
   90305 ** If the where clause loops cannot be arranged to provide the correct
   90306 ** output order, then the *ppOrderBy is unchanged.
   90307 */
   90308 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   90309   Parse *pParse,        /* The parser context */
   90310   SrcList *pTabList,    /* A list of all tables to be scanned */
   90311   Expr *pWhere,         /* The WHERE clause */
   90312   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
   90313   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
   90314 ){
   90315   int i;                     /* Loop counter */
   90316   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
   90317   int nTabList;              /* Number of elements in pTabList */
   90318   WhereInfo *pWInfo;         /* Will become the return value of this function */
   90319   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
   90320   Bitmask notReady;          /* Cursors that are not yet positioned */
   90321   WhereMaskSet *pMaskSet;    /* The expression mask set */
   90322   WhereClause *pWC;               /* Decomposition of the WHERE clause */
   90323   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
   90324   WhereLevel *pLevel;             /* A single level in the pWInfo list */
   90325   int iFrom;                      /* First unused FROM clause element */
   90326   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
   90327   sqlite3 *db;               /* Database connection */
   90328 
   90329   /* The number of tables in the FROM clause is limited by the number of
   90330   ** bits in a Bitmask
   90331   */
   90332   if( pTabList->nSrc>BMS ){
   90333     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
   90334     return 0;
   90335   }
   90336 
   90337   /* This function normally generates a nested loop for all tables in
   90338   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
   90339   ** only generate code for the first table in pTabList and assume that
   90340   ** any cursors associated with subsequent tables are uninitialized.
   90341   */
   90342   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
   90343 
   90344   /* Allocate and initialize the WhereInfo structure that will become the
   90345   ** return value. A single allocation is used to store the WhereInfo
   90346   ** struct, the contents of WhereInfo.a[], the WhereClause structure
   90347   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
   90348   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
   90349   ** some architectures. Hence the ROUND8() below.
   90350   */
   90351   db = pParse->db;
   90352   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
   90353   pWInfo = sqlite3DbMallocZero(db,
   90354       nByteWInfo +
   90355       sizeof(WhereClause) +
   90356       sizeof(WhereMaskSet)
   90357   );
   90358   if( db->mallocFailed ){
   90359     goto whereBeginError;
   90360   }
   90361   pWInfo->nLevel = nTabList;
   90362   pWInfo->pParse = pParse;
   90363   pWInfo->pTabList = pTabList;
   90364   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
   90365   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
   90366   pWInfo->wctrlFlags = wctrlFlags;
   90367   pMaskSet = (WhereMaskSet*)&pWC[1];
   90368 
   90369   /* Split the WHERE clause into separate subexpressions where each
   90370   ** subexpression is separated by an AND operator.
   90371   */
   90372   initMaskSet(pMaskSet);
   90373   whereClauseInit(pWC, pParse, pMaskSet);
   90374   sqlite3ExprCodeConstants(pParse, pWhere);
   90375   whereSplit(pWC, pWhere, TK_AND);
   90376 
   90377   /* Special case: a WHERE clause that is constant.  Evaluate the
   90378   ** expression and either jump over all of the code or fall thru.
   90379   */
   90380   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
   90381     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
   90382     pWhere = 0;
   90383   }
   90384 
   90385   /* Assign a bit from the bitmask to every term in the FROM clause.
   90386   **
   90387   ** When assigning bitmask values to FROM clause cursors, it must be
   90388   ** the case that if X is the bitmask for the N-th FROM clause term then
   90389   ** the bitmask for all FROM clause terms to the left of the N-th term
   90390   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
   90391   ** its Expr.iRightJoinTable value to find the bitmask of the right table
   90392   ** of the join.  Subtracting one from the right table bitmask gives a
   90393   ** bitmask for all tables to the left of the join.  Knowing the bitmask
   90394   ** for all tables to the left of a left join is important.  Ticket #3015.
   90395   **
   90396   ** Configure the WhereClause.vmask variable so that bits that correspond
   90397   ** to virtual table cursors are set. This is used to selectively disable
   90398   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
   90399   ** with virtual tables.
   90400   **
   90401   ** Note that bitmasks are created for all pTabList->nSrc tables in
   90402   ** pTabList, not just the first nTabList tables.  nTabList is normally
   90403   ** equal to pTabList->nSrc but might be shortened to 1 if the
   90404   ** WHERE_ONETABLE_ONLY flag is set.
   90405   */
   90406   assert( pWC->vmask==0 && pMaskSet->n==0 );
   90407   for(i=0; i<pTabList->nSrc; i++){
   90408     createMask(pMaskSet, pTabList->a[i].iCursor);
   90409 #ifndef SQLITE_OMIT_VIRTUALTABLE
   90410     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
   90411       pWC->vmask |= ((Bitmask)1 << i);
   90412     }
   90413 #endif
   90414   }
   90415 #ifndef NDEBUG
   90416   {
   90417     Bitmask toTheLeft = 0;
   90418     for(i=0; i<pTabList->nSrc; i++){
   90419       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
   90420       assert( (m-1)==toTheLeft );
   90421       toTheLeft |= m;
   90422     }
   90423   }
   90424 #endif
   90425 
   90426   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
   90427   ** add new virtual terms onto the end of the WHERE clause.  We do not
   90428   ** want to analyze these virtual terms, so start analyzing at the end
   90429   ** and work forward so that the added virtual terms are never processed.
   90430   */
   90431   exprAnalyzeAll(pTabList, pWC);
   90432   if( db->mallocFailed ){
   90433     goto whereBeginError;
   90434   }
   90435 
   90436   /* Chose the best index to use for each table in the FROM clause.
   90437   **
   90438   ** This loop fills in the following fields:
   90439   **
   90440   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
   90441   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
   90442   **   pWInfo->a[].nEq       The number of == and IN constraints
   90443   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
   90444   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
   90445   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
   90446   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
   90447   **
   90448   ** This loop also figures out the nesting order of tables in the FROM
   90449   ** clause.
   90450   */
   90451   notReady = ~(Bitmask)0;
   90452   pTabItem = pTabList->a;
   90453   pLevel = pWInfo->a;
   90454   andFlags = ~0;
   90455   WHERETRACE(("*** Optimizer Start ***\n"));
   90456   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
   90457     WhereCost bestPlan;         /* Most efficient plan seen so far */
   90458     Index *pIdx;                /* Index for FROM table at pTabItem */
   90459     int j;                      /* For looping over FROM tables */
   90460     int bestJ = -1;             /* The value of j */
   90461     Bitmask m;                  /* Bitmask value for j or bestJ */
   90462     int isOptimal;              /* Iterator for optimal/non-optimal search */
   90463 
   90464     memset(&bestPlan, 0, sizeof(bestPlan));
   90465     bestPlan.rCost = SQLITE_BIG_DBL;
   90466 
   90467     /* Loop through the remaining entries in the FROM clause to find the
   90468     ** next nested loop. The FROM clause entries may be iterated through
   90469     ** either once or twice.
   90470     **
   90471     ** The first iteration, which is always performed, searches for the
   90472     ** FROM clause entry that permits the lowest-cost, "optimal" scan. In
   90473     ** this context an optimal scan is one that uses the same strategy
   90474     ** for the given FROM clause entry as would be selected if the entry
   90475     ** were used as the innermost nested loop.  In other words, a table
   90476     ** is chosen such that the cost of running that table cannot be reduced
   90477     ** by waiting for other tables to run first.
   90478     **
   90479     ** The second iteration is only performed if no optimal scan strategies
   90480     ** were found by the first. This iteration is used to search for the
   90481     ** lowest cost scan overall.
   90482     **
   90483     ** Previous versions of SQLite performed only the second iteration -
   90484     ** the next outermost loop was always that with the lowest overall
   90485     ** cost. However, this meant that SQLite could select the wrong plan
   90486     ** for scripts such as the following:
   90487     **
   90488     **   CREATE TABLE t1(a, b);
   90489     **   CREATE TABLE t2(c, d);
   90490     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
   90491     **
   90492     ** The best strategy is to iterate through table t1 first. However it
   90493     ** is not possible to determine this with a simple greedy algorithm.
   90494     ** However, since the cost of a linear scan through table t2 is the same
   90495     ** as the cost of a linear scan through table t1, a simple greedy
   90496     ** algorithm may choose to use t2 for the outer loop, which is a much
   90497     ** costlier approach.
   90498     */
   90499     for(isOptimal=1; isOptimal>=0 && bestJ<0; isOptimal--){
   90500       Bitmask mask = (isOptimal ? 0 : notReady);
   90501       assert( (nTabList-iFrom)>1 || isOptimal );
   90502       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
   90503         int doNotReorder;    /* True if this table should not be reordered */
   90504         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
   90505         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
   90506 
   90507         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
   90508         if( j!=iFrom && doNotReorder ) break;
   90509         m = getMask(pMaskSet, pTabItem->iCursor);
   90510         if( (m & notReady)==0 ){
   90511           if( j==iFrom ) iFrom++;
   90512           continue;
   90513         }
   90514         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
   90515 
   90516         assert( pTabItem->pTab );
   90517 #ifndef SQLITE_OMIT_VIRTUALTABLE
   90518         if( IsVirtual(pTabItem->pTab) ){
   90519           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
   90520           bestVirtualIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost, pp);
   90521         }else
   90522 #endif
   90523         {
   90524           bestBtreeIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost);
   90525         }
   90526         assert( isOptimal || (sCost.used&notReady)==0 );
   90527 
   90528         if( (sCost.used&notReady)==0
   90529          && (j==iFrom || sCost.rCost<bestPlan.rCost)
   90530         ){
   90531           bestPlan = sCost;
   90532           bestJ = j;
   90533         }
   90534         if( doNotReorder ) break;
   90535       }
   90536     }
   90537     assert( bestJ>=0 );
   90538     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
   90539     WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
   90540            pLevel-pWInfo->a));
   90541     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
   90542       *ppOrderBy = 0;
   90543     }
   90544     andFlags &= bestPlan.plan.wsFlags;
   90545     pLevel->plan = bestPlan.plan;
   90546     if( bestPlan.plan.wsFlags & WHERE_INDEXED ){
   90547       pLevel->iIdxCur = pParse->nTab++;
   90548     }else{
   90549       pLevel->iIdxCur = -1;
   90550     }
   90551     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
   90552     pLevel->iFrom = (u8)bestJ;
   90553 
   90554     /* Check that if the table scanned by this loop iteration had an
   90555     ** INDEXED BY clause attached to it, that the named index is being
   90556     ** used for the scan. If not, then query compilation has failed.
   90557     ** Return an error.
   90558     */
   90559     pIdx = pTabList->a[bestJ].pIndex;
   90560     if( pIdx ){
   90561       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
   90562         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
   90563         goto whereBeginError;
   90564       }else{
   90565         /* If an INDEXED BY clause is used, the bestIndex() function is
   90566         ** guaranteed to find the index specified in the INDEXED BY clause
   90567         ** if it find an index at all. */
   90568         assert( bestPlan.plan.u.pIdx==pIdx );
   90569       }
   90570     }
   90571   }
   90572   WHERETRACE(("*** Optimizer Finished ***\n"));
   90573   if( pParse->nErr || db->mallocFailed ){
   90574     goto whereBeginError;
   90575   }
   90576 
   90577   /* If the total query only selects a single row, then the ORDER BY
   90578   ** clause is irrelevant.
   90579   */
   90580   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
   90581     *ppOrderBy = 0;
   90582   }
   90583 
   90584   /* If the caller is an UPDATE or DELETE statement that is requesting
   90585   ** to use a one-pass algorithm, determine if this is appropriate.
   90586   ** The one-pass algorithm only works if the WHERE clause constraints
   90587   ** the statement to update a single row.
   90588   */
   90589   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
   90590   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
   90591     pWInfo->okOnePass = 1;
   90592     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
   90593   }
   90594 
   90595   /* Open all tables in the pTabList and any indices selected for
   90596   ** searching those tables.
   90597   */
   90598   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
   90599   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
   90600     Table *pTab;     /* Table to open */
   90601     int iDb;         /* Index of database containing table/index */
   90602 
   90603 #ifndef SQLITE_OMIT_EXPLAIN
   90604     if( pParse->explain==2 ){
   90605       char *zMsg;
   90606       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
   90607       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
   90608       if( pItem->zAlias ){
   90609         zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
   90610       }
   90611       if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
   90612         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
   90613            zMsg, pLevel->plan.u.pIdx->zName);
   90614       }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
   90615         zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
   90616       }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
   90617         zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
   90618       }
   90619 #ifndef SQLITE_OMIT_VIRTUALTABLE
   90620       else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
   90621         sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
   90622         zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
   90623                     pVtabIdx->idxNum, pVtabIdx->idxStr);
   90624       }
   90625 #endif
   90626       if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
   90627         zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
   90628       }
   90629       sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
   90630     }
   90631 #endif /* SQLITE_OMIT_EXPLAIN */
   90632     pTabItem = &pTabList->a[pLevel->iFrom];
   90633     pTab = pTabItem->pTab;
   90634     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   90635     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
   90636 #ifndef SQLITE_OMIT_VIRTUALTABLE
   90637     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
   90638       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   90639       int iCur = pTabItem->iCursor;
   90640       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
   90641     }else
   90642 #endif
   90643     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
   90644          && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
   90645       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
   90646       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
   90647       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
   90648         Bitmask b = pTabItem->colUsed;
   90649         int n = 0;
   90650         for(; b; b=b>>1, n++){}
   90651         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
   90652                             SQLITE_INT_TO_PTR(n), P4_INT32);
   90653         assert( n<=pTab->nCol );
   90654       }
   90655     }else{
   90656       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   90657     }
   90658     pLevel->iTabCur = pTabItem->iCursor;
   90659     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
   90660       Index *pIx = pLevel->plan.u.pIdx;
   90661       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
   90662       int iIdxCur = pLevel->iIdxCur;
   90663       assert( pIx->pSchema==pTab->pSchema );
   90664       assert( iIdxCur>=0 );
   90665       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
   90666                         (char*)pKey, P4_KEYINFO_HANDOFF);
   90667       VdbeComment((v, "%s", pIx->zName));
   90668     }
   90669     sqlite3CodeVerifySchema(pParse, iDb);
   90670   }
   90671   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
   90672 
   90673   /* Generate the code to do the search.  Each iteration of the for
   90674   ** loop below generates code for a single nested loop of the VM
   90675   ** program.
   90676   */
   90677   notReady = ~(Bitmask)0;
   90678   for(i=0; i<nTabList; i++){
   90679     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
   90680     pWInfo->iContinue = pWInfo->a[i].addrCont;
   90681   }
   90682 
   90683 #ifdef SQLITE_TEST  /* For testing and debugging use only */
   90684   /* Record in the query plan information about the current table
   90685   ** and the index used to access it (if any).  If the table itself
   90686   ** is not used, its name is just '{}'.  If no index is used
   90687   ** the index is listed as "{}".  If the primary key is used the
   90688   ** index name is '*'.
   90689   */
   90690   for(i=0; i<nTabList; i++){
   90691     char *z;
   90692     int n;
   90693     pLevel = &pWInfo->a[i];
   90694     pTabItem = &pTabList->a[pLevel->iFrom];
   90695     z = pTabItem->zAlias;
   90696     if( z==0 ) z = pTabItem->pTab->zName;
   90697     n = sqlite3Strlen30(z);
   90698     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
   90699       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
   90700         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
   90701         nQPlan += 2;
   90702       }else{
   90703         memcpy(&sqlite3_query_plan[nQPlan], z, n);
   90704         nQPlan += n;
   90705       }
   90706       sqlite3_query_plan[nQPlan++] = ' ';
   90707     }
   90708     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
   90709     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
   90710     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
   90711       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
   90712       nQPlan += 2;
   90713     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
   90714       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
   90715       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
   90716         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
   90717         nQPlan += n;
   90718         sqlite3_query_plan[nQPlan++] = ' ';
   90719       }
   90720     }else{
   90721       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
   90722       nQPlan += 3;
   90723     }
   90724   }
   90725   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
   90726     sqlite3_query_plan[--nQPlan] = 0;
   90727   }
   90728   sqlite3_query_plan[nQPlan] = 0;
   90729   nQPlan = 0;
   90730 #endif /* SQLITE_TEST // Testing and debugging use only */
   90731 
   90732   /* Record the continuation address in the WhereInfo structure.  Then
   90733   ** clean up and return.
   90734   */
   90735   return pWInfo;
   90736 
   90737   /* Jump here if malloc fails */
   90738 whereBeginError:
   90739   whereInfoFree(db, pWInfo);
   90740   return 0;
   90741 }
   90742 
   90743 /*
   90744 ** Generate the end of the WHERE loop.  See comments on
   90745 ** sqlite3WhereBegin() for additional information.
   90746 */
   90747 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
   90748   Parse *pParse = pWInfo->pParse;
   90749   Vdbe *v = pParse->pVdbe;
   90750   int i;
   90751   WhereLevel *pLevel;
   90752   SrcList *pTabList = pWInfo->pTabList;
   90753   sqlite3 *db = pParse->db;
   90754 
   90755   /* Generate loop termination code.
   90756   */
   90757   sqlite3ExprCacheClear(pParse);
   90758   for(i=pWInfo->nLevel-1; i>=0; i--){
   90759     pLevel = &pWInfo->a[i];
   90760     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
   90761     if( pLevel->op!=OP_Noop ){
   90762       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
   90763       sqlite3VdbeChangeP5(v, pLevel->p5);
   90764     }
   90765     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
   90766       struct InLoop *pIn;
   90767       int j;
   90768       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
   90769       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
   90770         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
   90771         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
   90772         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
   90773       }
   90774       sqlite3DbFree(db, pLevel->u.in.aInLoop);
   90775     }
   90776     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
   90777     if( pLevel->iLeftJoin ){
   90778       int addr;
   90779       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
   90780       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
   90781            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
   90782       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
   90783         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
   90784       }
   90785       if( pLevel->iIdxCur>=0 ){
   90786         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
   90787       }
   90788       if( pLevel->op==OP_Return ){
   90789         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
   90790       }else{
   90791         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
   90792       }
   90793       sqlite3VdbeJumpHere(v, addr);
   90794     }
   90795   }
   90796 
   90797   /* The "break" point is here, just past the end of the outer loop.
   90798   ** Set it.
   90799   */
   90800   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
   90801 
   90802   /* Close all of the cursors that were opened by sqlite3WhereBegin.
   90803   */
   90804   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
   90805   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
   90806     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
   90807     Table *pTab = pTabItem->pTab;
   90808     assert( pTab!=0 );
   90809     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
   90810     if( (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0 ){
   90811       if( !pWInfo->okOnePass && (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
   90812         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
   90813       }
   90814       if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
   90815         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
   90816       }
   90817     }
   90818 
   90819     /* If this scan uses an index, make code substitutions to read data
   90820     ** from the index in preference to the table. Sometimes, this means
   90821     ** the table need never be read from. This is a performance boost,
   90822     ** as the vdbe level waits until the table is read before actually
   90823     ** seeking the table cursor to the record corresponding to the current
   90824     ** position in the index.
   90825     **
   90826     ** Calls to the code generator in between sqlite3WhereBegin and
   90827     ** sqlite3WhereEnd will have created code that references the table
   90828     ** directly.  This loop scans all that code looking for opcodes
   90829     ** that reference the table and converts them into opcodes that
   90830     ** reference the index.
   90831     */
   90832     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
   90833       int k, j, last;
   90834       VdbeOp *pOp;
   90835       Index *pIdx = pLevel->plan.u.pIdx;
   90836 
   90837       assert( pIdx!=0 );
   90838       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
   90839       last = sqlite3VdbeCurrentAddr(v);
   90840       for(k=pWInfo->iTop; k<last; k++, pOp++){
   90841         if( pOp->p1!=pLevel->iTabCur ) continue;
   90842         if( pOp->opcode==OP_Column ){
   90843           for(j=0; j<pIdx->nColumn; j++){
   90844             if( pOp->p2==pIdx->aiColumn[j] ){
   90845               pOp->p2 = j;
   90846               pOp->p1 = pLevel->iIdxCur;
   90847               break;
   90848             }
   90849           }
   90850           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
   90851                || j<pIdx->nColumn );
   90852         }else if( pOp->opcode==OP_Rowid ){
   90853           pOp->p1 = pLevel->iIdxCur;
   90854           pOp->opcode = OP_IdxRowid;
   90855         }
   90856       }
   90857     }
   90858   }
   90859 
   90860   /* Final cleanup
   90861   */
   90862   whereInfoFree(db, pWInfo);
   90863   return;
   90864 }
   90865 
   90866 /************** End of where.c ***********************************************/
   90867 /************** Begin file parse.c *******************************************/
   90868 /* Driver template for the LEMON parser generator.
   90869 ** The author disclaims copyright to this source code.
   90870 **
   90871 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
   90872 ** The only modifications are the addition of a couple of NEVER()
   90873 ** macros to disable tests that are needed in the case of a general
   90874 ** LALR(1) grammar but which are always false in the
   90875 ** specific grammar used by SQLite.
   90876 */
   90877 /* First off, code is included that follows the "include" declaration
   90878 ** in the input grammar file. */
   90879 
   90880 
   90881 /*
   90882 ** Disable all error recovery processing in the parser push-down
   90883 ** automaton.
   90884 */
   90885 #define YYNOERRORRECOVERY 1
   90886 
   90887 /*
   90888 ** Make yytestcase() the same as testcase()
   90889 */
   90890 #define yytestcase(X) testcase(X)
   90891 
   90892 /*
   90893 ** An instance of this structure holds information about the
   90894 ** LIMIT clause of a SELECT statement.
   90895 */
   90896 struct LimitVal {
   90897   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
   90898   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
   90899 };
   90900 
   90901 /*
   90902 ** An instance of this structure is used to store the LIKE,
   90903 ** GLOB, NOT LIKE, and NOT GLOB operators.
   90904 */
   90905 struct LikeOp {
   90906   Token eOperator;  /* "like" or "glob" or "regexp" */
   90907   int not;         /* True if the NOT keyword is present */
   90908 };
   90909 
   90910 /*
   90911 ** An instance of the following structure describes the event of a
   90912 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
   90913 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
   90914 **
   90915 **      UPDATE ON (a,b,c)
   90916 **
   90917 ** Then the "b" IdList records the list "a,b,c".
   90918 */
   90919 struct TrigEvent { int a; IdList * b; };
   90920 
   90921 /*
   90922 ** An instance of this structure holds the ATTACH key and the key type.
   90923 */
   90924 struct AttachKey { int type;  Token key; };
   90925 
   90926 
   90927   /* This is a utility routine used to set the ExprSpan.zStart and
   90928   ** ExprSpan.zEnd values of pOut so that the span covers the complete
   90929   ** range of text beginning with pStart and going to the end of pEnd.
   90930   */
   90931   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
   90932     pOut->zStart = pStart->z;
   90933     pOut->zEnd = &pEnd->z[pEnd->n];
   90934   }
   90935 
   90936   /* Construct a new Expr object from a single identifier.  Use the
   90937   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
   90938   ** that created the expression.
   90939   */
   90940   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
   90941     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
   90942     pOut->zStart = pValue->z;
   90943     pOut->zEnd = &pValue->z[pValue->n];
   90944   }
   90945 
   90946   /* This routine constructs a binary expression node out of two ExprSpan
   90947   ** objects and uses the result to populate a new ExprSpan object.
   90948   */
   90949   static void spanBinaryExpr(
   90950     ExprSpan *pOut,     /* Write the result here */
   90951     Parse *pParse,      /* The parsing context.  Errors accumulate here */
   90952     int op,             /* The binary operation */
   90953     ExprSpan *pLeft,    /* The left operand */
   90954     ExprSpan *pRight    /* The right operand */
   90955   ){
   90956     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
   90957     pOut->zStart = pLeft->zStart;
   90958     pOut->zEnd = pRight->zEnd;
   90959   }
   90960 
   90961   /* Construct an expression node for a unary postfix operator
   90962   */
   90963   static void spanUnaryPostfix(
   90964     ExprSpan *pOut,        /* Write the new expression node here */
   90965     Parse *pParse,         /* Parsing context to record errors */
   90966     int op,                /* The operator */
   90967     ExprSpan *pOperand,    /* The operand */
   90968     Token *pPostOp         /* The operand token for setting the span */
   90969   ){
   90970     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
   90971     pOut->zStart = pOperand->zStart;
   90972     pOut->zEnd = &pPostOp->z[pPostOp->n];
   90973   }
   90974 
   90975   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
   90976   ** unary TK_ISNULL or TK_NOTNULL expression. */
   90977   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
   90978     sqlite3 *db = pParse->db;
   90979     if( db->mallocFailed==0 && pY->op==TK_NULL ){
   90980       pA->op = (u8)op;
   90981       sqlite3ExprDelete(db, pA->pRight);
   90982       pA->pRight = 0;
   90983     }
   90984   }
   90985 
   90986   /* Construct an expression node for a unary prefix operator
   90987   */
   90988   static void spanUnaryPrefix(
   90989     ExprSpan *pOut,        /* Write the new expression node here */
   90990     Parse *pParse,         /* Parsing context to record errors */
   90991     int op,                /* The operator */
   90992     ExprSpan *pOperand,    /* The operand */
   90993     Token *pPreOp         /* The operand token for setting the span */
   90994   ){
   90995     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
   90996     pOut->zStart = pPreOp->z;
   90997     pOut->zEnd = pOperand->zEnd;
   90998   }
   90999 /* Next is all token values, in a form suitable for use by makeheaders.
   91000 ** This section will be null unless lemon is run with the -m switch.
   91001 */
   91002 /*
   91003 ** These constants (all generated automatically by the parser generator)
   91004 ** specify the various kinds of tokens (terminals) that the parser
   91005 ** understands.
   91006 **
   91007 ** Each symbol here is a terminal symbol in the grammar.
   91008 */
   91009 /* Make sure the INTERFACE macro is defined.
   91010 */
   91011 #ifndef INTERFACE
   91012 # define INTERFACE 1
   91013 #endif
   91014 /* The next thing included is series of defines which control
   91015 ** various aspects of the generated parser.
   91016 **    YYCODETYPE         is the data type used for storing terminal
   91017 **                       and nonterminal numbers.  "unsigned char" is
   91018 **                       used if there are fewer than 250 terminals
   91019 **                       and nonterminals.  "int" is used otherwise.
   91020 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
   91021 **                       to no legal terminal or nonterminal number.  This
   91022 **                       number is used to fill in empty slots of the hash
   91023 **                       table.
   91024 **    YYFALLBACK         If defined, this indicates that one or more tokens
   91025 **                       have fall-back values which should be used if the
   91026 **                       original value of the token will not parse.
   91027 **    YYACTIONTYPE       is the data type used for storing terminal
   91028 **                       and nonterminal numbers.  "unsigned char" is
   91029 **                       used if there are fewer than 250 rules and
   91030 **                       states combined.  "int" is used otherwise.
   91031 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
   91032 **                       directly to the parser from the tokenizer.
   91033 **    YYMINORTYPE        is the data type used for all minor tokens.
   91034 **                       This is typically a union of many types, one of
   91035 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
   91036 **                       for base tokens is called "yy0".
   91037 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
   91038 **                       zero the stack is dynamically sized using realloc()
   91039 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
   91040 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
   91041 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
   91042 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
   91043 **    YYNSTATE           the combined number of states.
   91044 **    YYNRULE            the number of rules in the grammar
   91045 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
   91046 **                       defined, then do no error processing.
   91047 */
   91048 #define YYCODETYPE unsigned char
   91049 #define YYNOCODE 254
   91050 #define YYACTIONTYPE unsigned short int
   91051 #define YYWILDCARD 67
   91052 #define sqlite3ParserTOKENTYPE Token
   91053 typedef union {
   91054   int yyinit;
   91055   sqlite3ParserTOKENTYPE yy0;
   91056   Select* yy3;
   91057   ExprList* yy14;
   91058   SrcList* yy65;
   91059   struct LikeOp yy96;
   91060   Expr* yy132;
   91061   u8 yy186;
   91062   int yy328;
   91063   ExprSpan yy346;
   91064   struct TrigEvent yy378;
   91065   IdList* yy408;
   91066   struct {int value; int mask;} yy429;
   91067   TriggerStep* yy473;
   91068   struct LimitVal yy476;
   91069 } YYMINORTYPE;
   91070 #ifndef YYSTACKDEPTH
   91071 #define YYSTACKDEPTH 100
   91072 #endif
   91073 #define sqlite3ParserARG_SDECL Parse *pParse;
   91074 #define sqlite3ParserARG_PDECL ,Parse *pParse
   91075 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
   91076 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
   91077 #define YYNSTATE 631
   91078 #define YYNRULE 330
   91079 #define YYFALLBACK 1
   91080 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
   91081 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
   91082 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
   91083 
   91084 /* The yyzerominor constant is used to initialize instances of
   91085 ** YYMINORTYPE objects to zero. */
   91086 static const YYMINORTYPE yyzerominor = { 0 };
   91087 
   91088 /* Define the yytestcase() macro to be a no-op if is not already defined
   91089 ** otherwise.
   91090 **
   91091 ** Applications can choose to define yytestcase() in the %include section
   91092 ** to a macro that can assist in verifying code coverage.  For production
   91093 ** code the yytestcase() macro should be turned off.  But it is useful
   91094 ** for testing.
   91095 */
   91096 #ifndef yytestcase
   91097 # define yytestcase(X)
   91098 #endif
   91099 
   91100 
   91101 /* Next are the tables used to determine what action to take based on the
   91102 ** current state and lookahead token.  These tables are used to implement
   91103 ** functions that take a state number and lookahead value and return an
   91104 ** action integer.
   91105 **
   91106 ** Suppose the action integer is N.  Then the action is determined as
   91107 ** follows
   91108 **
   91109 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
   91110 **                                      token onto the stack and goto state N.
   91111 **
   91112 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
   91113 **
   91114 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
   91115 **
   91116 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
   91117 **
   91118 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
   91119 **                                      slots in the yy_action[] table.
   91120 **
   91121 ** The action table is constructed as a single large table named yy_action[].
   91122 ** Given state S and lookahead X, the action is computed as
   91123 **
   91124 **      yy_action[ yy_shift_ofst[S] + X ]
   91125 **
   91126 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
   91127 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
   91128 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
   91129 ** and that yy_default[S] should be used instead.
   91130 **
   91131 ** The formula above is for computing the action when the lookahead is
   91132 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
   91133 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
   91134 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
   91135 ** YY_SHIFT_USE_DFLT.
   91136 **
   91137 ** The following are the tables generated in this section:
   91138 **
   91139 **  yy_action[]        A single table containing all actions.
   91140 **  yy_lookahead[]     A table containing the lookahead for each entry in
   91141 **                     yy_action.  Used to detect hash collisions.
   91142 **  yy_shift_ofst[]    For each state, the offset into yy_action for
   91143 **                     shifting terminals.
   91144 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
   91145 **                     shifting non-terminals after a reduce.
   91146 **  yy_default[]       Default action for each state.
   91147 */
   91148 #define YY_ACTTAB_COUNT (1543)
   91149 static const YYACTIONTYPE yy_action[] = {
   91150  /*     0 */   313,   49,  556,   46,  147,  172,  628,  598,   55,   55,
   91151  /*    10 */    55,   55,  302,   53,   53,   53,   53,   52,   52,   51,
   91152  /*    20 */    51,   51,   50,  238,  603,   66,  624,  623,  604,  598,
   91153  /*    30 */   591,  585,   48,   53,   53,   53,   53,   52,   52,   51,
   91154  /*    40 */    51,   51,   50,  238,   51,   51,   51,   50,  238,   56,
   91155  /*    50 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
   91156  /*    60 */    55,   55,  609,   53,   53,   53,   53,   52,   52,   51,
   91157  /*    70 */    51,   51,   50,  238,  313,  598,  672,  330,  411,  217,
   91158  /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
   91159  /*    90 */    50,  238,  330,  414,  621,  620,  166,  598,  673,  382,
   91160  /*   100 */   379,  378,  602,   73,  591,  585,  307,  424,  166,   58,
   91161  /*   110 */   377,  382,  379,  378,  516,  515,  624,  623,  254,  200,
   91162  /*   120 */   199,  198,  377,   56,   57,   47,  583,  582,  584,  584,
   91163  /*   130 */    54,   54,   55,   55,   55,   55,  581,   53,   53,   53,
   91164  /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  270,
   91165  /*   150 */   226,  422,  283,  133,  177,  139,  284,  385,  279,  384,
   91166  /*   160 */   169,  197,  251,  282,  253,  226,  411,  275,  440,  167,
   91167  /*   170 */   139,  284,  385,  279,  384,  169,  571,  236,  591,  585,
   91168  /*   180 */   240,  414,  275,  622,  621,  620,  674,  437,  441,  442,
   91169  /*   190 */   602,   88,  352,  266,  439,  268,  438,   56,   57,   47,
   91170  /*   200 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
   91171  /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
   91172  /*   220 */    50,  238,  313,  471,   52,   52,   51,   51,   51,   50,
   91173  /*   230 */   238,  234,  166,  491,  567,  382,  379,  378,    1,  440,
   91174  /*   240 */   252,  176,  624,  623,  608,   67,  377,  513,  622,  443,
   91175  /*   250 */   237,  577,  591,  585,  622,  172,  466,  598,  554,  441,
   91176  /*   260 */   340,  409,  526,  580,  580,  349,  596,  553,  194,  482,
   91177  /*   270 */   175,   56,   57,   47,  583,  582,  584,  584,   54,   54,
   91178  /*   280 */    55,   55,   55,   55,  562,   53,   53,   53,   53,   52,
   91179  /*   290 */    52,   51,   51,   51,   50,  238,  313,  594,  594,  594,
   91180  /*   300 */   561,  578,  469,   65,  259,  351,  258,  411,  624,  623,
   91181  /*   310 */   621,  620,  332,  576,  575,  240,  560,  568,  520,  411,
   91182  /*   320 */   341,  237,  414,  624,  623,  598,  591,  585,  542,  519,
   91183  /*   330 */   171,  602,   95,   68,  414,  624,  623,  624,  623,   38,
   91184  /*   340 */   877,  506,  507,  602,   88,   56,   57,   47,  583,  582,
   91185  /*   350 */   584,  584,   54,   54,   55,   55,   55,   55,  532,   53,
   91186  /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
   91187  /*   370 */   313,  411,  579,  398,  531,  237,  621,  620,  388,  625,
   91188  /*   380 */   500,  206,  167,  396,  233,  312,  414,  387,  569,  492,
   91189  /*   390 */   216,  621,  620,  566,  622,  602,   74,  533,  210,  491,
   91190  /*   400 */   591,  585,  548,  621,  620,  621,  620,  300,  598,  466,
   91191  /*   410 */   481,   67,  603,   35,  622,  601,  604,  547,    6,   56,
   91192  /*   420 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
   91193  /*   430 */    55,   55,  601,   53,   53,   53,   53,   52,   52,   51,
   91194  /*   440 */    51,   51,   50,  238,  313,  411,  184,  409,  528,  580,
   91195  /*   450 */   580,  551,  962,  186,  419,    2,  353,  259,  351,  258,
   91196  /*   460 */   414,  409,  411,  580,  580,   44,  411,  544,  240,  602,
   91197  /*   470 */    94,  190,    7,   62,  591,  585,  598,  414,  350,  607,
   91198  /*   480 */   493,  414,  409,  317,  580,  580,  602,   95,  496,  565,
   91199  /*   490 */   602,   80,  203,   56,   57,   47,  583,  582,  584,  584,
   91200  /*   500 */    54,   54,   55,   55,   55,   55,  535,   53,   53,   53,
   91201  /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  202,
   91202  /*   520 */   564,  293,  511,   49,  562,   46,  147,  411,  394,  183,
   91203  /*   530 */   563,  549,  505,  549,  174,  409,  322,  580,  580,   39,
   91204  /*   540 */   561,   37,  414,  624,  623,  192,  473,  383,  591,  585,
   91205  /*   550 */   474,  602,   80,  601,  504,  544,  560,  364,  402,  210,
   91206  /*   560 */   421,  952,  361,  952,  365,  201,  144,   56,   57,   47,
   91207  /*   570 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
   91208  /*   580 */   559,   53,   53,   53,   53,   52,   52,   51,   51,   51,
   91209  /*   590 */    50,  238,  313,  601,  232,  264,  272,  321,  374,  484,
   91210  /*   600 */   510,  146,  342,  146,  328,  425,  485,  407,  576,  575,
   91211  /*   610 */   622,  621,  620,   49,  168,   46,  147,  353,  546,  491,
   91212  /*   620 */   204,  240,  591,  585,  421,  951,  549,  951,  549,  168,
   91213  /*   630 */   429,   67,  390,  343,  622,  434,  307,  423,  338,  360,
   91214  /*   640 */   391,   56,   57,   47,  583,  582,  584,  584,   54,   54,
   91215  /*   650 */    55,   55,   55,   55,  601,   53,   53,   53,   53,   52,
   91216  /*   660 */    52,   51,   51,   51,   50,  238,  313,   34,  318,  425,
   91217  /*   670 */   237,   21,  359,  273,  411,  167,  411,  276,  411,  540,
   91218  /*   680 */   411,  422,   13,  318,  619,  618,  617,  622,  275,  414,
   91219  /*   690 */   336,  414,  622,  414,  622,  414,  591,  585,  602,   69,
   91220  /*   700 */   602,   97,  602,  100,  602,   98,  631,  629,  334,  475,
   91221  /*   710 */   475,  367,  319,  148,  327,   56,   57,   47,  583,  582,
   91222  /*   720 */   584,  584,   54,   54,   55,   55,   55,   55,  411,   53,
   91223  /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
   91224  /*   740 */   313,  411,  331,  414,  411,   49,  276,   46,  147,  569,
   91225  /*   750 */   406,  216,  602,  106,  573,  573,  414,  354,  524,  414,
   91226  /*   760 */   411,  622,  411,  224,    4,  602,  104,  605,  602,  108,
   91227  /*   770 */   591,  585,  622,   20,  375,  414,  167,  414,  215,  144,
   91228  /*   780 */   470,  239,  167,  225,  602,  109,  602,  134,   18,   56,
   91229  /*   790 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
   91230  /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
   91231  /*   810 */    51,   51,   50,  238,  313,  411,  276,  414,   12,  459,
   91232  /*   820 */   276,  171,  411,   16,  223,  189,  602,  135,  354,  170,
   91233  /*   830 */   414,  622,  630,    2,  411,  622,  540,  414,  143,  602,
   91234  /*   840 */    61,  359,  132,  622,  591,  585,  602,  105,  458,  414,
   91235  /*   850 */    23,  622,  446,  326,   23,  538,  622,  325,  602,  103,
   91236  /*   860 */   427,  530,  309,   56,   57,   47,  583,  582,  584,  584,
   91237  /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
   91238  /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
   91239  /*   890 */   264,  414,  411,  276,  359,  219,  157,  214,  357,  366,
   91240  /*   900 */   602,   96,  522,  521,  414,  622,  358,  414,  622,  622,
   91241  /*   910 */   411,  613,  612,  602,  102,  142,  602,   77,  591,  585,
   91242  /*   920 */   529,  540,  231,  426,  308,  414,  622,  622,  468,  521,
   91243  /*   930 */   324,  601,  257,  263,  602,   99,  622,   56,   45,   47,
   91244  /*   940 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
   91245  /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
   91246  /*   960 */    50,  238,  313,  264,  264,  414,  411,  213,  209,  544,
   91247  /*   970 */   544,  207,  611,   28,  602,  138,   50,  238,  622,  622,
   91248  /*   980 */   381,  414,  503,  140,  323,  222,  274,  622,  590,  589,
   91249  /*   990 */   602,  137,  591,  585,  629,  334,  606,   30,  622,  571,
   91250  /*  1000 */   236,  601,  601,  130,  496,  601,  453,  451,  288,  286,
   91251  /*  1010 */   587,  586,   57,   47,  583,  582,  584,  584,   54,   54,
   91252  /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
   91253  /*  1030 */    52,   51,   51,   51,   50,  238,  313,  588,  411,  414,
   91254  /*  1040 */   411,  264,  410,  129,  595,  400,   27,  376,  602,  136,
   91255  /*  1050 */   128,  165,  479,  414,  282,  414,  622,  622,  411,  622,
   91256  /*  1060 */   622,  411,  602,   76,  602,   93,  591,  585,  188,  372,
   91257  /*  1070 */   368,  125,  476,  414,  261,  160,  414,  171,  124,  472,
   91258  /*  1080 */   123,   15,  602,   92,  450,  602,   75,   47,  583,  582,
   91259  /*  1090 */   584,  584,   54,   54,   55,   55,   55,   55,  464,   53,
   91260  /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
   91261  /*  1110 */    43,  405,  264,    3,  558,  264,  545,  415,  623,  159,
   91262  /*  1120 */   541,  158,  539,  278,   25,  461,  121,  622,  408,  622,
   91263  /*  1130 */   622,  622,   24,   43,  405,  622,    3,  622,  622,  120,
   91264  /*  1140 */   415,  623,   11,  456,  411,  156,  452,  403,  509,  277,
   91265  /*  1150 */   118,  408,  489,  113,  205,  449,  271,  567,  221,  414,
   91266  /*  1160 */   269,  267,  155,  622,  622,  111,  411,  622,  602,   95,
   91267  /*  1170 */   403,  622,  411,  110,   10,  622,  622,   40,   41,  534,
   91268  /*  1180 */   567,  414,   64,  264,   42,  413,  412,  414,  601,  596,
   91269  /*  1190 */   602,   91,  445,  436,  150,  435,  602,   90,  622,  265,
   91270  /*  1200 */    40,   41,  337,  242,  411,  191,  333,   42,  413,  412,
   91271  /*  1210 */   398,  420,  596,  316,  622,  399,  260,  107,  230,  414,
   91272  /*  1220 */   594,  594,  594,  593,  592,   14,  220,  411,  602,  101,
   91273  /*  1230 */   240,  622,   43,  405,  362,    3,  149,  315,  626,  415,
   91274  /*  1240 */   623,  127,  414,  594,  594,  594,  593,  592,   14,  622,
   91275  /*  1250 */   408,  602,   89,  411,  181,   33,  405,  463,    3,  411,
   91276  /*  1260 */   264,  462,  415,  623,  616,  615,  614,  355,  414,  403,
   91277  /*  1270 */   417,  416,  622,  408,  414,  622,  622,  602,   87,  567,
   91278  /*  1280 */   418,  627,  622,  602,   86,    8,  241,  180,  126,  255,
   91279  /*  1290 */   600,  178,  403,  240,  208,  455,  395,  294,  444,   40,
   91280  /*  1300 */    41,  297,  567,  248,  622,  296,   42,  413,  412,  247,
   91281  /*  1310 */   622,  596,  244,  622,   30,   60,   31,  243,  430,  624,
   91282  /*  1320 */   623,  292,   40,   41,  622,  295,  145,  622,  601,   42,
   91283  /*  1330 */   413,  412,  622,  622,  596,  393,  622,  397,  599,   59,
   91284  /*  1340 */   235,  622,  594,  594,  594,  593,  592,   14,  218,  291,
   91285  /*  1350 */   622,   36,  344,  305,  304,  303,  179,  301,  411,  567,
   91286  /*  1360 */   454,  557,  173,  185,  622,  594,  594,  594,  593,  592,
   91287  /*  1370 */    14,  411,   29,  414,  151,  289,  246,  523,  411,  196,
   91288  /*  1380 */   195,  335,  602,   85,  411,  245,  414,  526,  392,  543,
   91289  /*  1390 */   411,  596,  287,  414,  285,  602,   72,  537,  153,  414,
   91290  /*  1400 */   466,  411,  602,   71,  154,  414,  411,  152,  602,   84,
   91291  /*  1410 */   386,  536,  329,  411,  602,   83,  414,  518,  280,  411,
   91292  /*  1420 */   513,  414,  594,  594,  594,  602,   82,  517,  414,  311,
   91293  /*  1430 */   602,   81,  411,  514,  414,  512,  131,  602,   70,  229,
   91294  /*  1440 */   228,  227,  494,  602,   17,  411,  488,  414,  259,  346,
   91295  /*  1450 */   249,  389,  487,  486,  314,  164,  602,   79,  310,  240,
   91296  /*  1460 */   414,  373,  480,  163,  262,  371,  414,  162,  369,  602,
   91297  /*  1470 */    78,  212,  478,   26,  477,  602,    9,  161,  467,  363,
   91298  /*  1480 */   141,  122,  339,  187,  119,  457,  348,  117,  347,  116,
   91299  /*  1490 */   115,  114,  448,  112,  182,  320,   22,  433,   19,  432,
   91300  /*  1500 */   431,   63,  428,  610,  193,  298,  597,  574,  572,  404,
   91301  /*  1510 */   555,  552,  290,  281,  510,  499,  498,  497,  495,  380,
   91302  /*  1520 */   356,  460,  256,  250,  345,  447,  306,    5,  570,  550,
   91303  /*  1530 */   299,  211,  370,  401,  550,  508,  502,  501,  490,  527,
   91304  /*  1540 */   525,  483,  238,
   91305 };
   91306 static const YYCODETYPE yy_lookahead[] = {
   91307  /*     0 */    19,  222,  223,  224,  225,   24,    1,   26,   77,   78,
   91308  /*    10 */    79,   80,   15,   82,   83,   84,   85,   86,   87,   88,
   91309  /*    20 */    89,   90,   91,   92,  113,   22,   26,   27,  117,   26,
   91310  /*    30 */    49,   50,   81,   82,   83,   84,   85,   86,   87,   88,
   91311  /*    40 */    89,   90,   91,   92,   88,   89,   90,   91,   92,   68,
   91312  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
   91313  /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
   91314  /*    70 */    89,   90,   91,   92,   19,   94,  118,   19,  150,   22,
   91315  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   91316  /*    90 */    91,   92,   19,  165,   94,   95,   96,   94,  118,   99,
   91317  /*   100 */   100,  101,  174,  175,   49,   50,   22,   23,   96,   54,
   91318  /*   110 */   110,   99,  100,  101,    7,    8,   26,   27,   16,  105,
   91319  /*   120 */   106,  107,  110,   68,   69,   70,   71,   72,   73,   74,
   91320  /*   130 */    75,   76,   77,   78,   79,   80,  113,   82,   83,   84,
   91321  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   16,
   91322  /*   150 */    92,   67,   98,   24,   96,   97,   98,   99,  100,  101,
   91323  /*   160 */   102,   25,   60,  109,   62,   92,  150,  109,  150,   25,
   91324  /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
   91325  /*   180 */   116,  165,  109,  165,   94,   95,  118,   97,  170,  171,
   91326  /*   190 */   174,  175,  128,   60,  104,   62,  106,   68,   69,   70,
   91327  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
   91328  /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   91329  /*   220 */    91,   92,   19,   21,   86,   87,   88,   89,   90,   91,
   91330  /*   230 */    92,  215,   96,  150,   66,   99,  100,  101,   22,  150,
   91331  /*   240 */   138,  118,   26,   27,  161,  162,  110,  103,  165,  231,
   91332  /*   250 */   232,   23,   49,   50,  165,   24,   57,   26,   32,  170,
   91333  /*   260 */   171,  112,   94,  114,  115,   63,   98,   41,  185,  186,
   91334  /*   270 */   118,   68,   69,   70,   71,   72,   73,   74,   75,   76,
   91335  /*   280 */    77,   78,   79,   80,   12,   82,   83,   84,   85,   86,
   91336  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
   91337  /*   300 */    28,   23,  100,   25,  105,  106,  107,  150,   26,   27,
   91338  /*   310 */    94,   95,  169,  170,  171,  116,   44,   23,   46,  150,
   91339  /*   320 */   231,  232,  165,   26,   27,   94,   49,   50,   23,   57,
   91340  /*   330 */    25,  174,  175,   22,  165,   26,   27,   26,   27,  136,
   91341  /*   340 */   138,   97,   98,  174,  175,   68,   69,   70,   71,   72,
   91342  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
   91343  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
   91344  /*   370 */    19,  150,   23,  216,   23,  232,   94,   95,  221,  150,
   91345  /*   380 */    23,  160,   25,  214,  215,  163,  165,   88,  166,  167,
   91346  /*   390 */   168,   94,   95,   23,  165,  174,  175,   88,  160,  150,
   91347  /*   400 */    49,   50,  120,   94,   95,   94,   95,  158,   26,   57,
   91348  /*   410 */   161,  162,  113,  136,  165,  194,  117,  120,   22,   68,
   91349  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
   91350  /*   430 */    79,   80,  194,   82,   83,   84,   85,   86,   87,   88,
   91351  /*   440 */    89,   90,   91,   92,   19,  150,   23,  112,   23,  114,
   91352  /*   450 */   115,   25,  142,  143,  144,  145,  218,  105,  106,  107,
   91353  /*   460 */   165,  112,  150,  114,  115,   22,  150,  166,  116,  174,
   91354  /*   470 */   175,   22,   76,  235,   49,   50,   94,  165,  240,  172,
   91355  /*   480 */   173,  165,  112,  155,  114,  115,  174,  175,  181,   11,
   91356  /*   490 */   174,  175,   22,   68,   69,   70,   71,   72,   73,   74,
   91357  /*   500 */    75,   76,   77,   78,   79,   80,  205,   82,   83,   84,
   91358  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  160,
   91359  /*   520 */    23,  226,   23,  222,   12,  224,  225,  150,  216,   23,
   91360  /*   530 */    23,   25,   36,   25,   25,  112,  220,  114,  115,  135,
   91361  /*   540 */    28,  137,  165,   26,   27,  119,   30,   51,   49,   50,
   91362  /*   550 */    34,  174,  175,  194,   58,  166,   44,  229,   46,  160,
   91363  /*   560 */    22,   23,  234,   25,   48,  206,  207,   68,   69,   70,
   91364  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
   91365  /*   580 */    23,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   91366  /*   590 */    91,   92,   19,  194,  205,  150,   23,  220,   19,  181,
   91367  /*   600 */   182,   95,   97,   95,  108,   67,  188,  169,  170,  171,
   91368  /*   610 */   165,   94,   95,  222,   50,  224,  225,  218,  120,  150,
   91369  /*   620 */   160,  116,   49,   50,   22,   23,  120,   25,  120,   50,
   91370  /*   630 */   161,  162,   19,  128,  165,  244,   22,   23,  193,  240,
   91371  /*   640 */    27,   68,   69,   70,   71,   72,   73,   74,   75,   76,
   91372  /*   650 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
   91373  /*   660 */    87,   88,   89,   90,   91,   92,   19,   25,  104,   67,
   91374  /*   670 */   232,   24,  150,   23,  150,   25,  150,  150,  150,  150,
   91375  /*   680 */   150,   67,   25,  104,    7,    8,    9,  165,  109,  165,
   91376  /*   690 */   245,  165,  165,  165,  165,  165,   49,   50,  174,  175,
   91377  /*   700 */   174,  175,  174,  175,  174,  175,    0,    1,    2,  105,
   91378  /*   710 */   106,  107,  248,  249,  187,   68,   69,   70,   71,   72,
   91379  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
   91380  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
   91381  /*   740 */    19,  150,  213,  165,  150,  222,  150,  224,  225,  166,
   91382  /*   750 */   167,  168,  174,  175,  129,  130,  165,  150,  165,  165,
   91383  /*   760 */   150,  165,  150,  241,   35,  174,  175,  174,  174,  175,
   91384  /*   770 */    49,   50,  165,   52,   23,  165,   25,  165,  206,  207,
   91385  /*   780 */    23,  197,   25,  187,  174,  175,  174,  175,  204,   68,
   91386  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
   91387  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
   91388  /*   810 */    89,   90,   91,   92,   19,  150,  150,  165,   35,   23,
   91389  /*   820 */   150,   25,  150,   22,  217,   24,  174,  175,  150,   35,
   91390  /*   830 */   165,  165,  144,  145,  150,  165,  150,  165,  118,  174,
   91391  /*   840 */   175,  150,   22,  165,   49,   50,  174,  175,   23,  165,
   91392  /*   850 */    25,  165,   23,  187,   25,   27,  165,  187,  174,  175,
   91393  /*   860 */    23,   23,   25,   68,   69,   70,   71,   72,   73,   74,
   91394  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
   91395  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
   91396  /*   890 */   150,  165,  150,  150,  150,  217,   25,  160,   19,  213,
   91397  /*   900 */   174,  175,  190,  191,  165,  165,   27,  165,  165,  165,
   91398  /*   910 */   150,  150,  150,  174,  175,   39,  174,  175,   49,   50,
   91399  /*   920 */    23,  150,   52,  250,  251,  165,  165,  165,  190,  191,
   91400  /*   930 */   187,  194,  241,  193,  174,  175,  165,   68,   69,   70,
   91401  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
   91402  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   91403  /*   960 */    91,   92,   19,  150,  150,  165,  150,  160,  160,  166,
   91404  /*   970 */   166,  160,  150,   22,  174,  175,   91,   92,  165,  165,
   91405  /*   980 */    52,  165,   29,  150,  213,  241,   23,  165,   49,   50,
   91406  /*   990 */   174,  175,   49,   50,    1,    2,  173,  126,  165,   86,
   91407  /*  1000 */    87,  194,  194,   22,  181,  194,  193,  193,  205,  205,
   91408  /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
   91409  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
   91410  /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
   91411  /*  1040 */   150,  150,  150,   22,  150,  150,   22,   52,  174,  175,
   91412  /*  1050 */    22,  102,   20,  165,  109,  165,  165,  165,  150,  165,
   91413  /*  1060 */   165,  150,  174,  175,  174,  175,   49,   50,   24,   19,
   91414  /*  1070 */    43,  104,   59,  165,  138,  104,  165,   25,   53,   53,
   91415  /*  1080 */    22,    5,  174,  175,  193,  174,  175,   70,   71,   72,
   91416  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,    1,   82,
   91417  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
   91418  /*  1110 */    19,   20,  150,   22,  150,  150,  150,   26,   27,  118,
   91419  /*  1120 */   150,   35,  150,  150,   76,   27,  108,  165,   37,  165,
   91420  /*  1130 */   165,  165,   76,   19,   20,  165,   22,  165,  165,  127,
   91421  /*  1140 */    26,   27,   22,    1,  150,   16,   20,   56,  150,  150,
   91422  /*  1150 */   119,   37,  150,  119,  160,  193,  150,   66,  193,  165,
   91423  /*  1160 */   150,  150,  121,  165,  165,  108,  150,  165,  174,  175,
   91424  /*  1170 */    56,  165,  150,  127,   22,  165,  165,   86,   87,   88,
   91425  /*  1180 */    66,  165,   16,  150,   93,   94,   95,  165,  194,   98,
   91426  /*  1190 */   174,  175,  128,   23,   15,   23,  174,  175,  165,  150,
   91427  /*  1200 */    86,   87,   65,  140,  150,   22,    3,   93,   94,   95,
   91428  /*  1210 */   216,    4,   98,  252,  165,  221,  150,  164,  180,  165,
   91429  /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
   91430  /*  1230 */   116,  165,   19,   20,  150,   22,  249,  252,  149,   26,
   91431  /*  1240 */    27,  180,  165,  129,  130,  131,  132,  133,  134,  165,
   91432  /*  1250 */    37,  174,  175,  150,    6,   19,   20,  150,   22,  150,
   91433  /*  1260 */   150,  150,   26,   27,  149,  149,   13,  150,  165,   56,
   91434  /*  1270 */   149,  159,  165,   37,  165,  165,  165,  174,  175,   66,
   91435  /*  1280 */   146,  147,  165,  174,  175,   25,  152,  151,  154,  150,
   91436  /*  1290 */   194,  151,   56,  116,  160,  150,  123,  202,  150,   86,
   91437  /*  1300 */    87,  199,   66,  193,  165,  200,   93,   94,   95,  150,
   91438  /*  1310 */   165,   98,  150,  165,  126,   22,  124,  150,  150,   26,
   91439  /*  1320 */    27,  150,   86,   87,  165,  201,  150,  165,  194,   93,
   91440  /*  1330 */    94,   95,  165,  165,   98,  150,  165,  122,  203,  125,
   91441  /*  1340 */   227,  165,  129,  130,  131,  132,  133,  134,    5,  150,
   91442  /*  1350 */   165,  135,  218,   10,   11,   12,   13,   14,  150,   66,
   91443  /*  1360 */    17,  157,  118,  157,  165,  129,  130,  131,  132,  133,
   91444  /*  1370 */   134,  150,  104,  165,   31,  210,   33,  176,  150,   86,
   91445  /*  1380 */    87,  247,  174,  175,  150,   42,  165,   94,  121,  211,
   91446  /*  1390 */   150,   98,  210,  165,  210,  174,  175,  211,   55,  165,
   91447  /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
   91448  /*  1410 */   104,  211,   47,  150,  174,  175,  165,  176,  176,  150,
   91449  /*  1420 */   103,  165,  129,  130,  131,  174,  175,  184,  165,  179,
   91450  /*  1430 */   174,  175,  150,  178,  165,  176,   22,  174,  175,  230,
   91451  /*  1440 */    92,  230,  184,  174,  175,  150,  176,  165,  105,  106,
   91452  /*  1450 */   107,  150,  176,  176,  111,  156,  174,  175,  179,  116,
   91453  /*  1460 */   165,   18,  157,  156,  238,  157,  165,  156,   45,  174,
   91454  /*  1470 */   175,  157,  157,  135,  239,  174,  175,  156,  189,  157,
   91455  /*  1480 */    68,  189,  139,  219,   22,  199,  157,  192,   18,  192,
   91456  /*  1490 */   192,  192,  199,  189,  219,  157,  243,   40,  243,  157,
   91457  /*  1500 */   157,  246,   38,  153,  196,  198,  166,  233,  233,  228,
   91458  /*  1510 */   177,  177,  209,  177,  182,  177,  166,  177,  166,  178,
   91459  /*  1520 */   242,  199,  242,  209,  209,  199,  148,  196,  166,  208,
   91460  /*  1530 */   195,  236,  237,  191,  208,  183,  183,  183,  186,  174,
   91461  /*  1540 */   174,  186,   92,
   91462 };
   91463 #define YY_SHIFT_USE_DFLT (-90)
   91464 #define YY_SHIFT_COUNT (418)
   91465 #define YY_SHIFT_MIN   (-89)
   91466 #define YY_SHIFT_MAX   (1470)
   91467 static const short yy_shift_ofst[] = {
   91468  /*     0 */   993, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
   91469  /*    10 */  1213, 1213, 1213, 1213, 1213,  352,  517,  721, 1091, 1213,
   91470  /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
   91471  /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
   91472  /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
   91473  /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
   91474  /*    60 */  1213,  -49,  199,  517,  517,  913,  913,  382, 1177,   55,
   91475  /*    70 */   647,  573,  499,  425,  351,  277,  203,  129,  795,  795,
   91476  /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
   91477  /*    90 */   795,  795,  795,  795,  795,  795,  869,  795,  943, 1017,
   91478  /*   100 */  1017,  -69,  -69,  -69,  -69,   -1,   -1,   58,  138,  -44,
   91479  /*   110 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
   91480  /*   120 */   517,  517,  517,  517,  517,  517,  202,  579,  517,  517,
   91481  /*   130 */   517,  517,  517,  382,  885, 1450,  -90,  -90,  -90, 1293,
   91482  /*   140 */    73,  272,  272,  309,  311,  297,  282,  216,  602,  538,
   91483  /*   150 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
   91484  /*   160 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
   91485  /*   170 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
   91486  /*   180 */   517,  517,  505,  231,  231,  231,  706,   64, 1177, 1177,
   91487  /*   190 */  1177,  -90,  -90,  -90,  136,  168,  168,   12,  496,  496,
   91488  /*   200 */   496,  506,  423,  512,  370,  349,  335,  149,  149,  149,
   91489  /*   210 */   149,  604,  516,  149,  149,  508,    3,  299,  677,  871,
   91490  /*   220 */   613,  613,  879,  871,  879,  144,  382,  226,  382,  226,
   91491  /*   230 */   564,  226,  613,  226,  226,  404,  625,  625,  382,  426,
   91492  /*   240 */   -89,  801, 1464, 1244, 1244, 1457, 1457, 1244, 1462, 1412,
   91493  /*   250 */  1188, 1470, 1470, 1470, 1470, 1244, 1188, 1462, 1412, 1412,
   91494  /*   260 */  1244, 1443, 1338, 1423, 1244, 1244, 1443, 1244, 1443, 1244,
   91495  /*   270 */  1443, 1414, 1306, 1306, 1306, 1365, 1348, 1348, 1414, 1306,
   91496  /*   280 */  1317, 1306, 1365, 1306, 1306, 1267, 1268, 1267, 1268, 1267,
   91497  /*   290 */  1268, 1244, 1244, 1216, 1214, 1215, 1192, 1173, 1188, 1177,
   91498  /*   300 */  1260, 1253, 1253, 1248, 1248, 1248, 1248,  -90,  -90,  -90,
   91499  /*   310 */   -90,  -90,  -90,  939,  102,  614,   84,  133,   14,  837,
   91500  /*   320 */   396,  829,  825,  796,  757,  751,  650,  357,  244,  107,
   91501  /*   330 */    54,  305,  278, 1207, 1203, 1183, 1063, 1179, 1137, 1166,
   91502  /*   340 */  1172, 1170, 1064, 1152, 1046, 1057, 1034, 1126, 1041, 1129,
   91503  /*   350 */  1142, 1031, 1120, 1012, 1056, 1048, 1018, 1098, 1086, 1001,
   91504  /*   360 */  1097, 1076, 1058,  971,  936, 1026, 1052, 1025, 1013, 1027,
   91505  /*   370 */   967, 1044, 1032, 1050,  945,  949, 1028,  995, 1024, 1021,
   91506  /*   380 */   963,  981,  928,  953,  951,  870,  876,  897,  838,  720,
   91507  /*   390 */   828,  794,  820,  498,  642,  783,  657,  729,  642,  557,
   91508  /*   400 */   507,  509,  497,  470,  478,  449,  294,  228,  443,   23,
   91509  /*   410 */   152,  123,   68,  -20,  -42,   57,   39,   -3,    5,
   91510 };
   91511 #define YY_REDUCE_USE_DFLT (-222)
   91512 #define YY_REDUCE_COUNT (312)
   91513 #define YY_REDUCE_MIN   (-221)
   91514 #define YY_REDUCE_MAX   (1378)
   91515 static const short yy_reduce_ofst[] = {
   91516  /*     0 */   310,  994, 1134,  221,  169,  157,   89,   18,   83,  301,
   91517  /*    10 */   377,  316,  312,   16,  295,  238,  249,  391, 1301, 1295,
   91518  /*    20 */  1282, 1269, 1263, 1256, 1251, 1240, 1234, 1228, 1221, 1208,
   91519  /*    30 */  1109, 1103, 1077, 1054, 1022, 1016,  911,  908,  890,  888,
   91520  /*    40 */   874,  816,  800,  760,  742,  739,  726,  684,  672,  665,
   91521  /*    50 */   652,  612,  610,  594,  591,  578,  530,  528,  526,  524,
   91522  /*    60 */   -72, -221,  399,  469,  445,  438,  143,  222,  359,  523,
   91523  /*    70 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
   91524  /*    80 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
   91525  /*    90 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
   91526  /*   100 */   523,  523,  523,  523,  523,  523,  523,  307,  523,  523,
   91527  /*   110 */  1110,  678, 1033,  965,  962,  891,  814,  813,  744,  771,
   91528  /*   120 */   691,  607,  522,  743,  686,  740,  328,  418,  670,  666,
   91529  /*   130 */   596,  527,  529,  583,  523,  523,  523,  523,  523,  593,
   91530  /*   140 */   823,  738,  712,  892, 1199, 1185, 1176, 1171,  673,  673,
   91531  /*   150 */  1168, 1167, 1162, 1159, 1148, 1145, 1139, 1117, 1111, 1107,
   91532  /*   160 */  1084, 1066, 1049, 1011, 1010, 1006, 1002,  999,  998,  973,
   91533  /*   170 */   972,  970,  966,  964,  895,  894,  892,  833,  822,  762,
   91534  /*   180 */   761,  229,  811,  804,  803,  389,  688,  808,  807,  737,
   91535  /*   190 */   460,  464,  572,  584, 1355, 1366, 1365, 1352, 1354, 1353,
   91536  /*   200 */  1352, 1326, 1335, 1342, 1335, 1335, 1335, 1335, 1335, 1335,
   91537  /*   210 */  1335, 1295, 1295, 1335, 1335, 1321, 1362, 1331, 1378, 1326,
   91538  /*   220 */  1315, 1314, 1280, 1322, 1278, 1341, 1352, 1340, 1350, 1338,
   91539  /*   230 */  1332, 1336, 1303, 1334, 1333, 1281, 1275, 1274, 1340, 1307,
   91540  /*   240 */  1308, 1350, 1255, 1343, 1342, 1255, 1253, 1338, 1275, 1304,
   91541  /*   250 */  1293, 1299, 1298, 1297, 1295, 1329, 1286, 1264, 1292, 1289,
   91542  /*   260 */  1322, 1321, 1235, 1226, 1315, 1314, 1311, 1308, 1307, 1305,
   91543  /*   270 */  1299, 1279, 1277, 1276, 1270, 1258, 1211, 1209, 1250, 1259,
   91544  /*   280 */  1255, 1242, 1243, 1241, 1201, 1200, 1184, 1186, 1182, 1178,
   91545  /*   290 */  1165, 1206, 1204, 1113, 1135, 1095, 1124, 1105, 1102, 1096,
   91546  /*   300 */  1112, 1140, 1136, 1121, 1116, 1115, 1089,  985,  961,  987,
   91547  /*   310 */  1061, 1038, 1053,
   91548 };
   91549 static const YYACTIONTYPE yy_default[] = {
   91550  /*     0 */   636,  872,  961,  961,  961,  872,  901,  901,  961,  760,
   91551  /*    10 */   961,  961,  961,  961,  870,  961,  961,  935,  961,  961,
   91552  /*    20 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
   91553  /*    30 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
   91554  /*    40 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
   91555  /*    50 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
   91556  /*    60 */   961,  844,  961,  961,  961,  901,  901,  675,  764,  795,
   91557  /*    70 */   961,  961,  961,  961,  961,  961,  961,  961,  934,  936,
   91558  /*    80 */   810,  809,  803,  802,  914,  775,  800,  793,  786,  797,
   91559  /*    90 */   873,  866,  867,  865,  869,  874,  961,  796,  832,  850,
   91560  /*   100 */   831,  849,  856,  848,  834,  843,  833,  667,  835,  836,
   91561  /*   110 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
   91562  /*   120 */   961,  961,  961,  961,  961,  961,  662,  729,  961,  961,
   91563  /*   130 */   961,  961,  961,  961,  837,  838,  853,  852,  851,  961,
   91564  /*   140 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
   91565  /*   150 */   961,  941,  939,  961,  885,  961,  961,  961,  961,  961,
   91566  /*   160 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
   91567  /*   170 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
   91568  /*   180 */   961,  642,  961,  760,  760,  760,  636,  961,  961,  961,
   91569  /*   190 */   961,  953,  764,  754,  720,  961,  961,  961,  961,  961,
   91570  /*   200 */   961,  961,  961,  961,  961,  961,  961,  805,  743,  924,
   91571  /*   210 */   926,  961,  907,  741,  664,  762,  677,  752,  644,  799,
   91572  /*   220 */   777,  777,  919,  799,  919,  701,  961,  789,  961,  789,
   91573  /*   230 */   698,  789,  777,  789,  789,  868,  961,  961,  961,  761,
   91574  /*   240 */   752,  961,  946,  768,  768,  938,  938,  768,  811,  733,
   91575  /*   250 */   799,  740,  740,  740,  740,  768,  799,  811,  733,  733,
   91576  /*   260 */   768,  659,  913,  911,  768,  768,  659,  768,  659,  768,
   91577  /*   270 */   659,  878,  731,  731,  731,  716,  882,  882,  878,  731,
   91578  /*   280 */   701,  731,  716,  731,  731,  781,  776,  781,  776,  781,
   91579  /*   290 */   776,  768,  768,  961,  794,  782,  792,  790,  799,  961,
   91580  /*   300 */   719,  652,  652,  641,  641,  641,  641,  958,  958,  953,
   91581  /*   310 */   703,  703,  685,  961,  961,  961,  961,  961,  961,  961,
   91582  /*   320 */   887,  961,  961,  961,  961,  961,  961,  961,  961,  961,
   91583  /*   330 */   961,  961,  961,  961,  637,  948,  961,  961,  945,  961,
   91584  /*   340 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
   91585  /*   350 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  917,
   91586  /*   360 */   961,  961,  961,  961,  961,  961,  910,  909,  961,  961,
   91587  /*   370 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
   91588  /*   380 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
   91589  /*   390 */   961,  961,  961,  961,  791,  961,  783,  961,  871,  961,
   91590  /*   400 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  746,
   91591  /*   410 */   820,  961,  819,  823,  818,  669,  961,  650,  961,  633,
   91592  /*   420 */   638,  957,  960,  959,  956,  955,  954,  949,  947,  944,
   91593  /*   430 */   943,  942,  940,  937,  933,  891,  889,  896,  895,  894,
   91594  /*   440 */   893,  892,  890,  888,  886,  806,  804,  801,  798,  932,
   91595  /*   450 */   884,  742,  739,  738,  658,  950,  916,  925,  923,  812,
   91596  /*   460 */   922,  921,  920,  918,  915,  902,  808,  807,  734,  876,
   91597  /*   470 */   875,  661,  906,  905,  904,  908,  912,  903,  770,  660,
   91598  /*   480 */   657,  666,  723,  722,  730,  728,  727,  726,  725,  724,
   91599  /*   490 */   721,  668,  676,  687,  715,  700,  699,  881,  883,  880,
   91600  /*   500 */   879,  708,  707,  713,  712,  711,  710,  709,  706,  705,
   91601  /*   510 */   704,  697,  696,  702,  695,  718,  717,  714,  694,  737,
   91602  /*   520 */   736,  735,  732,  693,  692,  691,  823,  690,  689,  829,
   91603  /*   530 */   828,  816,  860,  757,  756,  755,  767,  766,  779,  778,
   91604  /*   540 */   814,  813,  780,  765,  759,  758,  774,  773,  772,  771,
   91605  /*   550 */   763,  753,  785,  788,  787,  784,  845,  862,  769,  859,
   91606  /*   560 */   931,  930,  929,  928,  927,  864,  863,  830,  827,  680,
   91607  /*   570 */   681,  900,  898,  899,  897,  683,  682,  679,  678,  861,
   91608  /*   580 */   748,  747,  857,  854,  846,  841,  858,  855,  847,  842,
   91609  /*   590 */   840,  839,  825,  824,  822,  821,  817,  826,  671,  749,
   91610  /*   600 */   745,  744,  815,  751,  750,  688,  686,  684,  665,  663,
   91611  /*   610 */   656,  654,  653,  655,  651,  649,  648,  647,  646,  645,
   91612  /*   620 */   674,  673,  672,  670,  669,  643,  640,  639,  635,  634,
   91613  /*   630 */   632,
   91614 };
   91615 
   91616 /* The next table maps tokens into fallback tokens.  If a construct
   91617 ** like the following:
   91618 **
   91619 **      %fallback ID X Y Z.
   91620 **
   91621 ** appears in the grammar, then ID becomes a fallback token for X, Y,
   91622 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
   91623 ** but it does not parse, the type of the token is changed to ID and
   91624 ** the parse is retried before an error is thrown.
   91625 */
   91626 #ifdef YYFALLBACK
   91627 static const YYCODETYPE yyFallback[] = {
   91628     0,  /*          $ => nothing */
   91629     0,  /*       SEMI => nothing */
   91630    26,  /*    EXPLAIN => ID */
   91631    26,  /*      QUERY => ID */
   91632    26,  /*       PLAN => ID */
   91633    26,  /*      BEGIN => ID */
   91634     0,  /* TRANSACTION => nothing */
   91635    26,  /*   DEFERRED => ID */
   91636    26,  /*  IMMEDIATE => ID */
   91637    26,  /*  EXCLUSIVE => ID */
   91638     0,  /*     COMMIT => nothing */
   91639    26,  /*        END => ID */
   91640    26,  /*   ROLLBACK => ID */
   91641    26,  /*  SAVEPOINT => ID */
   91642    26,  /*    RELEASE => ID */
   91643     0,  /*         TO => nothing */
   91644     0,  /*      TABLE => nothing */
   91645     0,  /*     CREATE => nothing */
   91646    26,  /*         IF => ID */
   91647     0,  /*        NOT => nothing */
   91648     0,  /*     EXISTS => nothing */
   91649    26,  /*       TEMP => ID */
   91650     0,  /*         LP => nothing */
   91651     0,  /*         RP => nothing */
   91652     0,  /*         AS => nothing */
   91653     0,  /*      COMMA => nothing */
   91654     0,  /*         ID => nothing */
   91655     0,  /*    INDEXED => nothing */
   91656    26,  /*      ABORT => ID */
   91657    26,  /*     ACTION => ID */
   91658    26,  /*      AFTER => ID */
   91659    26,  /*    ANALYZE => ID */
   91660    26,  /*        ASC => ID */
   91661    26,  /*     ATTACH => ID */
   91662    26,  /*     BEFORE => ID */
   91663    26,  /*         BY => ID */
   91664    26,  /*    CASCADE => ID */
   91665    26,  /*       CAST => ID */
   91666    26,  /*   COLUMNKW => ID */
   91667    26,  /*   CONFLICT => ID */
   91668    26,  /*   DATABASE => ID */
   91669    26,  /*       DESC => ID */
   91670    26,  /*     DETACH => ID */
   91671    26,  /*       EACH => ID */
   91672    26,  /*       FAIL => ID */
   91673    26,  /*        FOR => ID */
   91674    26,  /*     IGNORE => ID */
   91675    26,  /*  INITIALLY => ID */
   91676    26,  /*    INSTEAD => ID */
   91677    26,  /*    LIKE_KW => ID */
   91678    26,  /*      MATCH => ID */
   91679    26,  /*         NO => ID */
   91680    26,  /*        KEY => ID */
   91681    26,  /*         OF => ID */
   91682    26,  /*     OFFSET => ID */
   91683    26,  /*     PRAGMA => ID */
   91684    26,  /*      RAISE => ID */
   91685    26,  /*    REPLACE => ID */
   91686    26,  /*   RESTRICT => ID */
   91687    26,  /*        ROW => ID */
   91688    26,  /*    TRIGGER => ID */
   91689    26,  /*     VACUUM => ID */
   91690    26,  /*       VIEW => ID */
   91691    26,  /*    VIRTUAL => ID */
   91692    26,  /*    REINDEX => ID */
   91693    26,  /*     RENAME => ID */
   91694    26,  /*   CTIME_KW => ID */
   91695 };
   91696 #endif /* YYFALLBACK */
   91697 
   91698 /* The following structure represents a single element of the
   91699 ** parser's stack.  Information stored includes:
   91700 **
   91701 **   +  The state number for the parser at this level of the stack.
   91702 **
   91703 **   +  The value of the token stored at this level of the stack.
   91704 **      (In other words, the "major" token.)
   91705 **
   91706 **   +  The semantic value stored at this level of the stack.  This is
   91707 **      the information used by the action routines in the grammar.
   91708 **      It is sometimes called the "minor" token.
   91709 */
   91710 struct yyStackEntry {
   91711   YYACTIONTYPE stateno;  /* The state-number */
   91712   YYCODETYPE major;      /* The major token value.  This is the code
   91713                          ** number for the token at this stack level */
   91714   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
   91715                          ** is the value of the token  */
   91716 };
   91717 typedef struct yyStackEntry yyStackEntry;
   91718 
   91719 /* The state of the parser is completely contained in an instance of
   91720 ** the following structure */
   91721 struct yyParser {
   91722   int yyidx;                    /* Index of top element in stack */
   91723 #ifdef YYTRACKMAXSTACKDEPTH
   91724   int yyidxMax;                 /* Maximum value of yyidx */
   91725 #endif
   91726   int yyerrcnt;                 /* Shifts left before out of the error */
   91727   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
   91728 #if YYSTACKDEPTH<=0
   91729   int yystksz;                  /* Current side of the stack */
   91730   yyStackEntry *yystack;        /* The parser's stack */
   91731 #else
   91732   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
   91733 #endif
   91734 };
   91735 typedef struct yyParser yyParser;
   91736 
   91737 #ifndef NDEBUG
   91738 static FILE *yyTraceFILE = 0;
   91739 static char *yyTracePrompt = 0;
   91740 #endif /* NDEBUG */
   91741 
   91742 #ifndef NDEBUG
   91743 /*
   91744 ** Turn parser tracing on by giving a stream to which to write the trace
   91745 ** and a prompt to preface each trace message.  Tracing is turned off
   91746 ** by making either argument NULL
   91747 **
   91748 ** Inputs:
   91749 ** <ul>
   91750 ** <li> A FILE* to which trace output should be written.
   91751 **      If NULL, then tracing is turned off.
   91752 ** <li> A prefix string written at the beginning of every
   91753 **      line of trace output.  If NULL, then tracing is
   91754 **      turned off.
   91755 ** </ul>
   91756 **
   91757 ** Outputs:
   91758 ** None.
   91759 */
   91760 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
   91761   yyTraceFILE = TraceFILE;
   91762   yyTracePrompt = zTracePrompt;
   91763   if( yyTraceFILE==0 ) yyTracePrompt = 0;
   91764   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
   91765 }
   91766 #endif /* NDEBUG */
   91767 
   91768 #ifndef NDEBUG
   91769 /* For tracing shifts, the names of all terminals and nonterminals
   91770 ** are required.  The following table supplies these names */
   91771 static const char *const yyTokenName[] = {
   91772   "$",             "SEMI",          "EXPLAIN",       "QUERY",
   91773   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
   91774   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
   91775   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
   91776   "TABLE",         "CREATE",        "IF",            "NOT",
   91777   "EXISTS",        "TEMP",          "LP",            "RP",
   91778   "AS",            "COMMA",         "ID",            "INDEXED",
   91779   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
   91780   "ASC",           "ATTACH",        "BEFORE",        "BY",
   91781   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
   91782   "DATABASE",      "DESC",          "DETACH",        "EACH",
   91783   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
   91784   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
   91785   "KEY",           "OF",            "OFFSET",        "PRAGMA",
   91786   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
   91787   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
   91788   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
   91789   "OR",            "AND",           "IS",            "BETWEEN",
   91790   "IN",            "ISNULL",        "NOTNULL",       "NE",
   91791   "EQ",            "GT",            "LE",            "LT",
   91792   "GE",            "ESCAPE",        "BITAND",        "BITOR",
   91793   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
   91794   "STAR",          "SLASH",         "REM",           "CONCAT",
   91795   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
   91796   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
   91797   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
   91798   "ON",            "INSERT",        "DELETE",        "UPDATE",
   91799   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
   91800   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
   91801   "SELECT",        "DISTINCT",      "DOT",           "FROM",
   91802   "JOIN",          "USING",         "ORDER",         "GROUP",
   91803   "HAVING",        "LIMIT",         "WHERE",         "INTO",
   91804   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
   91805   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
   91806   "THEN",          "ELSE",          "INDEX",         "ALTER",
   91807   "ADD",           "error",         "input",         "cmdlist",
   91808   "ecmd",          "explain",       "cmdx",          "cmd",
   91809   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
   91810   "create_table",  "create_table_args",  "createkw",      "temp",
   91811   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
   91812   "select",        "column",        "columnid",      "type",
   91813   "carglist",      "id",            "ids",           "typetoken",
   91814   "typename",      "signed",        "plus_num",      "minus_num",
   91815   "carg",          "ccons",         "term",          "expr",
   91816   "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
   91817   "refargs",       "defer_subclause",  "refarg",        "refact",
   91818   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",
   91819   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
   91820   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
   91821   "distinct",      "selcollist",    "from",          "where_opt",
   91822   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
   91823   "sclp",          "as",            "seltablist",    "stl_prefix",
   91824   "joinop",        "indexed_opt",   "on_opt",        "using_opt",
   91825   "joinop2",       "inscollist",    "sortlist",      "sortitem",
   91826   "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
   91827   "itemlist",      "exprlist",      "likeop",        "escape",
   91828   "between_op",    "in_op",         "case_operand",  "case_exprlist",
   91829   "case_else",     "uniqueflag",    "collate",       "nmnum",
   91830   "plus_opt",      "number",        "trigger_decl",  "trigger_cmd_list",
   91831   "trigger_time",  "trigger_event",  "foreach_clause",  "when_clause",
   91832   "trigger_cmd",   "trnm",          "tridxby",       "database_kw_opt",
   91833   "key_opt",       "add_column_fullname",  "kwcolumn_opt",  "create_vtab",
   91834   "vtabarglist",   "vtabarg",       "vtabargtoken",  "lp",
   91835   "anylist",
   91836 };
   91837 #endif /* NDEBUG */
   91838 
   91839 #ifndef NDEBUG
   91840 /* For tracing reduce actions, the names of all rules are required.
   91841 */
   91842 static const char *const yyRuleName[] = {
   91843  /*   0 */ "input ::= cmdlist",
   91844  /*   1 */ "cmdlist ::= cmdlist ecmd",
   91845  /*   2 */ "cmdlist ::= ecmd",
   91846  /*   3 */ "ecmd ::= SEMI",
   91847  /*   4 */ "ecmd ::= explain cmdx SEMI",
   91848  /*   5 */ "explain ::=",
   91849  /*   6 */ "explain ::= EXPLAIN",
   91850  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
   91851  /*   8 */ "cmdx ::= cmd",
   91852  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
   91853  /*  10 */ "trans_opt ::=",
   91854  /*  11 */ "trans_opt ::= TRANSACTION",
   91855  /*  12 */ "trans_opt ::= TRANSACTION nm",
   91856  /*  13 */ "transtype ::=",
   91857  /*  14 */ "transtype ::= DEFERRED",
   91858  /*  15 */ "transtype ::= IMMEDIATE",
   91859  /*  16 */ "transtype ::= EXCLUSIVE",
   91860  /*  17 */ "cmd ::= COMMIT trans_opt",
   91861  /*  18 */ "cmd ::= END trans_opt",
   91862  /*  19 */ "cmd ::= ROLLBACK trans_opt",
   91863  /*  20 */ "savepoint_opt ::= SAVEPOINT",
   91864  /*  21 */ "savepoint_opt ::=",
   91865  /*  22 */ "cmd ::= SAVEPOINT nm",
   91866  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
   91867  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
   91868  /*  25 */ "cmd ::= create_table create_table_args",
   91869  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
   91870  /*  27 */ "createkw ::= CREATE",
   91871  /*  28 */ "ifnotexists ::=",
   91872  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
   91873  /*  30 */ "temp ::= TEMP",
   91874  /*  31 */ "temp ::=",
   91875  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
   91876  /*  33 */ "create_table_args ::= AS select",
   91877  /*  34 */ "columnlist ::= columnlist COMMA column",
   91878  /*  35 */ "columnlist ::= column",
   91879  /*  36 */ "column ::= columnid type carglist",
   91880  /*  37 */ "columnid ::= nm",
   91881  /*  38 */ "id ::= ID",
   91882  /*  39 */ "id ::= INDEXED",
   91883  /*  40 */ "ids ::= ID|STRING",
   91884  /*  41 */ "nm ::= id",
   91885  /*  42 */ "nm ::= STRING",
   91886  /*  43 */ "nm ::= JOIN_KW",
   91887  /*  44 */ "type ::=",
   91888  /*  45 */ "type ::= typetoken",
   91889  /*  46 */ "typetoken ::= typename",
   91890  /*  47 */ "typetoken ::= typename LP signed RP",
   91891  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
   91892  /*  49 */ "typename ::= ids",
   91893  /*  50 */ "typename ::= typename ids",
   91894  /*  51 */ "signed ::= plus_num",
   91895  /*  52 */ "signed ::= minus_num",
   91896  /*  53 */ "carglist ::= carglist carg",
   91897  /*  54 */ "carglist ::=",
   91898  /*  55 */ "carg ::= CONSTRAINT nm ccons",
   91899  /*  56 */ "carg ::= ccons",
   91900  /*  57 */ "ccons ::= DEFAULT term",
   91901  /*  58 */ "ccons ::= DEFAULT LP expr RP",
   91902  /*  59 */ "ccons ::= DEFAULT PLUS term",
   91903  /*  60 */ "ccons ::= DEFAULT MINUS term",
   91904  /*  61 */ "ccons ::= DEFAULT id",
   91905  /*  62 */ "ccons ::= NULL onconf",
   91906  /*  63 */ "ccons ::= NOT NULL onconf",
   91907  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
   91908  /*  65 */ "ccons ::= UNIQUE onconf",
   91909  /*  66 */ "ccons ::= CHECK LP expr RP",
   91910  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
   91911  /*  68 */ "ccons ::= defer_subclause",
   91912  /*  69 */ "ccons ::= COLLATE ids",
   91913  /*  70 */ "autoinc ::=",
   91914  /*  71 */ "autoinc ::= AUTOINCR",
   91915  /*  72 */ "refargs ::=",
   91916  /*  73 */ "refargs ::= refargs refarg",
   91917  /*  74 */ "refarg ::= MATCH nm",
   91918  /*  75 */ "refarg ::= ON INSERT refact",
   91919  /*  76 */ "refarg ::= ON DELETE refact",
   91920  /*  77 */ "refarg ::= ON UPDATE refact",
   91921  /*  78 */ "refact ::= SET NULL",
   91922  /*  79 */ "refact ::= SET DEFAULT",
   91923  /*  80 */ "refact ::= CASCADE",
   91924  /*  81 */ "refact ::= RESTRICT",
   91925  /*  82 */ "refact ::= NO ACTION",
   91926  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
   91927  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
   91928  /*  85 */ "init_deferred_pred_opt ::=",
   91929  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
   91930  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
   91931  /*  88 */ "conslist_opt ::=",
   91932  /*  89 */ "conslist_opt ::= COMMA conslist",
   91933  /*  90 */ "conslist ::= conslist COMMA tcons",
   91934  /*  91 */ "conslist ::= conslist tcons",
   91935  /*  92 */ "conslist ::= tcons",
   91936  /*  93 */ "tcons ::= CONSTRAINT nm",
   91937  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
   91938  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
   91939  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
   91940  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
   91941  /*  98 */ "defer_subclause_opt ::=",
   91942  /*  99 */ "defer_subclause_opt ::= defer_subclause",
   91943  /* 100 */ "onconf ::=",
   91944  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
   91945  /* 102 */ "orconf ::=",
   91946  /* 103 */ "orconf ::= OR resolvetype",
   91947  /* 104 */ "resolvetype ::= raisetype",
   91948  /* 105 */ "resolvetype ::= IGNORE",
   91949  /* 106 */ "resolvetype ::= REPLACE",
   91950  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
   91951  /* 108 */ "ifexists ::= IF EXISTS",
   91952  /* 109 */ "ifexists ::=",
   91953  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
   91954  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
   91955  /* 112 */ "cmd ::= select",
   91956  /* 113 */ "select ::= oneselect",
   91957  /* 114 */ "select ::= select multiselect_op oneselect",
   91958  /* 115 */ "multiselect_op ::= UNION",
   91959  /* 116 */ "multiselect_op ::= UNION ALL",
   91960  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
   91961  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
   91962  /* 119 */ "distinct ::= DISTINCT",
   91963  /* 120 */ "distinct ::= ALL",
   91964  /* 121 */ "distinct ::=",
   91965  /* 122 */ "sclp ::= selcollist COMMA",
   91966  /* 123 */ "sclp ::=",
   91967  /* 124 */ "selcollist ::= sclp expr as",
   91968  /* 125 */ "selcollist ::= sclp STAR",
   91969  /* 126 */ "selcollist ::= sclp nm DOT STAR",
   91970  /* 127 */ "as ::= AS nm",
   91971  /* 128 */ "as ::= ids",
   91972  /* 129 */ "as ::=",
   91973  /* 130 */ "from ::=",
   91974  /* 131 */ "from ::= FROM seltablist",
   91975  /* 132 */ "stl_prefix ::= seltablist joinop",
   91976  /* 133 */ "stl_prefix ::=",
   91977  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
   91978  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
   91979  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
   91980  /* 137 */ "dbnm ::=",
   91981  /* 138 */ "dbnm ::= DOT nm",
   91982  /* 139 */ "fullname ::= nm dbnm",
   91983  /* 140 */ "joinop ::= COMMA|JOIN",
   91984  /* 141 */ "joinop ::= JOIN_KW JOIN",
   91985  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
   91986  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
   91987  /* 144 */ "on_opt ::= ON expr",
   91988  /* 145 */ "on_opt ::=",
   91989  /* 146 */ "indexed_opt ::=",
   91990  /* 147 */ "indexed_opt ::= INDEXED BY nm",
   91991  /* 148 */ "indexed_opt ::= NOT INDEXED",
   91992  /* 149 */ "using_opt ::= USING LP inscollist RP",
   91993  /* 150 */ "using_opt ::=",
   91994  /* 151 */ "orderby_opt ::=",
   91995  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
   91996  /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
   91997  /* 154 */ "sortlist ::= sortitem sortorder",
   91998  /* 155 */ "sortitem ::= expr",
   91999  /* 156 */ "sortorder ::= ASC",
   92000  /* 157 */ "sortorder ::= DESC",
   92001  /* 158 */ "sortorder ::=",
   92002  /* 159 */ "groupby_opt ::=",
   92003  /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
   92004  /* 161 */ "having_opt ::=",
   92005  /* 162 */ "having_opt ::= HAVING expr",
   92006  /* 163 */ "limit_opt ::=",
   92007  /* 164 */ "limit_opt ::= LIMIT expr",
   92008  /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
   92009  /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
   92010  /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
   92011  /* 168 */ "where_opt ::=",
   92012  /* 169 */ "where_opt ::= WHERE expr",
   92013  /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
   92014  /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
   92015  /* 172 */ "setlist ::= nm EQ expr",
   92016  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
   92017  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
   92018  /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
   92019  /* 176 */ "insert_cmd ::= INSERT orconf",
   92020  /* 177 */ "insert_cmd ::= REPLACE",
   92021  /* 178 */ "itemlist ::= itemlist COMMA expr",
   92022  /* 179 */ "itemlist ::= expr",
   92023  /* 180 */ "inscollist_opt ::=",
   92024  /* 181 */ "inscollist_opt ::= LP inscollist RP",
   92025  /* 182 */ "inscollist ::= inscollist COMMA nm",
   92026  /* 183 */ "inscollist ::= nm",
   92027  /* 184 */ "expr ::= term",
   92028  /* 185 */ "expr ::= LP expr RP",
   92029  /* 186 */ "term ::= NULL",
   92030  /* 187 */ "expr ::= id",
   92031  /* 188 */ "expr ::= JOIN_KW",
   92032  /* 189 */ "expr ::= nm DOT nm",
   92033  /* 190 */ "expr ::= nm DOT nm DOT nm",
   92034  /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
   92035  /* 192 */ "term ::= STRING",
   92036  /* 193 */ "expr ::= REGISTER",
   92037  /* 194 */ "expr ::= VARIABLE",
   92038  /* 195 */ "expr ::= expr COLLATE ids",
   92039  /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
   92040  /* 197 */ "expr ::= ID LP distinct exprlist RP",
   92041  /* 198 */ "expr ::= ID LP STAR RP",
   92042  /* 199 */ "term ::= CTIME_KW",
   92043  /* 200 */ "expr ::= expr AND expr",
   92044  /* 201 */ "expr ::= expr OR expr",
   92045  /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
   92046  /* 203 */ "expr ::= expr EQ|NE expr",
   92047  /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
   92048  /* 205 */ "expr ::= expr PLUS|MINUS expr",
   92049  /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
   92050  /* 207 */ "expr ::= expr CONCAT expr",
   92051  /* 208 */ "likeop ::= LIKE_KW",
   92052  /* 209 */ "likeop ::= NOT LIKE_KW",
   92053  /* 210 */ "likeop ::= MATCH",
   92054  /* 211 */ "likeop ::= NOT MATCH",
   92055  /* 212 */ "escape ::= ESCAPE expr",
   92056  /* 213 */ "escape ::=",
   92057  /* 214 */ "expr ::= expr likeop expr escape",
   92058  /* 215 */ "expr ::= expr ISNULL|NOTNULL",
   92059  /* 216 */ "expr ::= expr NOT NULL",
   92060  /* 217 */ "expr ::= expr IS expr",
   92061  /* 218 */ "expr ::= expr IS NOT expr",
   92062  /* 219 */ "expr ::= NOT expr",
   92063  /* 220 */ "expr ::= BITNOT expr",
   92064  /* 221 */ "expr ::= MINUS expr",
   92065  /* 222 */ "expr ::= PLUS expr",
   92066  /* 223 */ "between_op ::= BETWEEN",
   92067  /* 224 */ "between_op ::= NOT BETWEEN",
   92068  /* 225 */ "expr ::= expr between_op expr AND expr",
   92069  /* 226 */ "in_op ::= IN",
   92070  /* 227 */ "in_op ::= NOT IN",
   92071  /* 228 */ "expr ::= expr in_op LP exprlist RP",
   92072  /* 229 */ "expr ::= LP select RP",
   92073  /* 230 */ "expr ::= expr in_op LP select RP",
   92074  /* 231 */ "expr ::= expr in_op nm dbnm",
   92075  /* 232 */ "expr ::= EXISTS LP select RP",
   92076  /* 233 */ "expr ::= CASE case_operand case_exprlist case_else END",
   92077  /* 234 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
   92078  /* 235 */ "case_exprlist ::= WHEN expr THEN expr",
   92079  /* 236 */ "case_else ::= ELSE expr",
   92080  /* 237 */ "case_else ::=",
   92081  /* 238 */ "case_operand ::= expr",
   92082  /* 239 */ "case_operand ::=",
   92083  /* 240 */ "exprlist ::= nexprlist",
   92084  /* 241 */ "exprlist ::=",
   92085  /* 242 */ "nexprlist ::= nexprlist COMMA expr",
   92086  /* 243 */ "nexprlist ::= expr",
   92087  /* 244 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
   92088  /* 245 */ "uniqueflag ::= UNIQUE",
   92089  /* 246 */ "uniqueflag ::=",
   92090  /* 247 */ "idxlist_opt ::=",
   92091  /* 248 */ "idxlist_opt ::= LP idxlist RP",
   92092  /* 249 */ "idxlist ::= idxlist COMMA nm collate sortorder",
   92093  /* 250 */ "idxlist ::= nm collate sortorder",
   92094  /* 251 */ "collate ::=",
   92095  /* 252 */ "collate ::= COLLATE ids",
   92096  /* 253 */ "cmd ::= DROP INDEX ifexists fullname",
   92097  /* 254 */ "cmd ::= VACUUM",
   92098  /* 255 */ "cmd ::= VACUUM nm",
   92099  /* 256 */ "cmd ::= PRAGMA nm dbnm",
   92100  /* 257 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
   92101  /* 258 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
   92102  /* 259 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
   92103  /* 260 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
   92104  /* 261 */ "nmnum ::= plus_num",
   92105  /* 262 */ "nmnum ::= nm",
   92106  /* 263 */ "nmnum ::= ON",
   92107  /* 264 */ "nmnum ::= DELETE",
   92108  /* 265 */ "nmnum ::= DEFAULT",
   92109  /* 266 */ "plus_num ::= plus_opt number",
   92110  /* 267 */ "minus_num ::= MINUS number",
   92111  /* 268 */ "number ::= INTEGER|FLOAT",
   92112  /* 269 */ "plus_opt ::= PLUS",
   92113  /* 270 */ "plus_opt ::=",
   92114  /* 271 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
   92115  /* 272 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
   92116  /* 273 */ "trigger_time ::= BEFORE",
   92117  /* 274 */ "trigger_time ::= AFTER",
   92118  /* 275 */ "trigger_time ::= INSTEAD OF",
   92119  /* 276 */ "trigger_time ::=",
   92120  /* 277 */ "trigger_event ::= DELETE|INSERT",
   92121  /* 278 */ "trigger_event ::= UPDATE",
   92122  /* 279 */ "trigger_event ::= UPDATE OF inscollist",
   92123  /* 280 */ "foreach_clause ::=",
   92124  /* 281 */ "foreach_clause ::= FOR EACH ROW",
   92125  /* 282 */ "when_clause ::=",
   92126  /* 283 */ "when_clause ::= WHEN expr",
   92127  /* 284 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
   92128  /* 285 */ "trigger_cmd_list ::= trigger_cmd SEMI",
   92129  /* 286 */ "trnm ::= nm",
   92130  /* 287 */ "trnm ::= nm DOT nm",
   92131  /* 288 */ "tridxby ::=",
   92132  /* 289 */ "tridxby ::= INDEXED BY nm",
   92133  /* 290 */ "tridxby ::= NOT INDEXED",
   92134  /* 291 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
   92135  /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
   92136  /* 293 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
   92137  /* 294 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
   92138  /* 295 */ "trigger_cmd ::= select",
   92139  /* 296 */ "expr ::= RAISE LP IGNORE RP",
   92140  /* 297 */ "expr ::= RAISE LP raisetype COMMA nm RP",
   92141  /* 298 */ "raisetype ::= ROLLBACK",
   92142  /* 299 */ "raisetype ::= ABORT",
   92143  /* 300 */ "raisetype ::= FAIL",
   92144  /* 301 */ "cmd ::= DROP TRIGGER ifexists fullname",
   92145  /* 302 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
   92146  /* 303 */ "cmd ::= DETACH database_kw_opt expr",
   92147  /* 304 */ "key_opt ::=",
   92148  /* 305 */ "key_opt ::= KEY expr",
   92149  /* 306 */ "database_kw_opt ::= DATABASE",
   92150  /* 307 */ "database_kw_opt ::=",
   92151  /* 308 */ "cmd ::= REINDEX",
   92152  /* 309 */ "cmd ::= REINDEX nm dbnm",
   92153  /* 310 */ "cmd ::= ANALYZE",
   92154  /* 311 */ "cmd ::= ANALYZE nm dbnm",
   92155  /* 312 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
   92156  /* 313 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
   92157  /* 314 */ "add_column_fullname ::= fullname",
   92158  /* 315 */ "kwcolumn_opt ::=",
   92159  /* 316 */ "kwcolumn_opt ::= COLUMNKW",
   92160  /* 317 */ "cmd ::= create_vtab",
   92161  /* 318 */ "cmd ::= create_vtab LP vtabarglist RP",
   92162  /* 319 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
   92163  /* 320 */ "vtabarglist ::= vtabarg",
   92164  /* 321 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
   92165  /* 322 */ "vtabarg ::=",
   92166  /* 323 */ "vtabarg ::= vtabarg vtabargtoken",
   92167  /* 324 */ "vtabargtoken ::= ANY",
   92168  /* 325 */ "vtabargtoken ::= lp anylist RP",
   92169  /* 326 */ "lp ::= LP",
   92170  /* 327 */ "anylist ::=",
   92171  /* 328 */ "anylist ::= anylist LP anylist RP",
   92172  /* 329 */ "anylist ::= anylist ANY",
   92173 };
   92174 #endif /* NDEBUG */
   92175 
   92176 
   92177 #if YYSTACKDEPTH<=0
   92178 /*
   92179 ** Try to increase the size of the parser stack.
   92180 */
   92181 static void yyGrowStack(yyParser *p){
   92182   int newSize;
   92183   yyStackEntry *pNew;
   92184 
   92185   newSize = p->yystksz*2 + 100;
   92186   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
   92187   if( pNew ){
   92188     p->yystack = pNew;
   92189     p->yystksz = newSize;
   92190 #ifndef NDEBUG
   92191     if( yyTraceFILE ){
   92192       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
   92193               yyTracePrompt, p->yystksz);
   92194     }
   92195 #endif
   92196   }
   92197 }
   92198 #endif
   92199 
   92200 /*
   92201 ** This function allocates a new parser.
   92202 ** The only argument is a pointer to a function which works like
   92203 ** malloc.
   92204 **
   92205 ** Inputs:
   92206 ** A pointer to the function used to allocate memory.
   92207 **
   92208 ** Outputs:
   92209 ** A pointer to a parser.  This pointer is used in subsequent calls
   92210 ** to sqlite3Parser and sqlite3ParserFree.
   92211 */
   92212 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
   92213   yyParser *pParser;
   92214   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
   92215   if( pParser ){
   92216     pParser->yyidx = -1;
   92217 #ifdef YYTRACKMAXSTACKDEPTH
   92218     pParser->yyidxMax = 0;
   92219 #endif
   92220 #if YYSTACKDEPTH<=0
   92221     pParser->yystack = NULL;
   92222     pParser->yystksz = 0;
   92223     yyGrowStack(pParser);
   92224 #endif
   92225   }
   92226   return pParser;
   92227 }
   92228 
   92229 /* The following function deletes the value associated with a
   92230 ** symbol.  The symbol can be either a terminal or nonterminal.
   92231 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
   92232 ** the value.
   92233 */
   92234 static void yy_destructor(
   92235   yyParser *yypParser,    /* The parser */
   92236   YYCODETYPE yymajor,     /* Type code for object to destroy */
   92237   YYMINORTYPE *yypminor   /* The object to be destroyed */
   92238 ){
   92239   sqlite3ParserARG_FETCH;
   92240   switch( yymajor ){
   92241     /* Here is inserted the actions which take place when a
   92242     ** terminal or non-terminal is destroyed.  This can happen
   92243     ** when the symbol is popped from the stack during a
   92244     ** reduce or during error processing or when a parser is
   92245     ** being destroyed before it is finished parsing.
   92246     **
   92247     ** Note: during a reduce, the only symbols destroyed are those
   92248     ** which appear on the RHS of the rule, but which are not used
   92249     ** inside the C code.
   92250     */
   92251     case 160: /* select */
   92252     case 194: /* oneselect */
   92253 {
   92254 sqlite3SelectDelete(pParse->db, (yypminor->yy3));
   92255 }
   92256       break;
   92257     case 174: /* term */
   92258     case 175: /* expr */
   92259     case 223: /* escape */
   92260 {
   92261 sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
   92262 }
   92263       break;
   92264     case 179: /* idxlist_opt */
   92265     case 187: /* idxlist */
   92266     case 197: /* selcollist */
   92267     case 200: /* groupby_opt */
   92268     case 202: /* orderby_opt */
   92269     case 204: /* sclp */
   92270     case 214: /* sortlist */
   92271     case 216: /* nexprlist */
   92272     case 217: /* setlist */
   92273     case 220: /* itemlist */
   92274     case 221: /* exprlist */
   92275     case 227: /* case_exprlist */
   92276 {
   92277 sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
   92278 }
   92279       break;
   92280     case 193: /* fullname */
   92281     case 198: /* from */
   92282     case 206: /* seltablist */
   92283     case 207: /* stl_prefix */
   92284 {
   92285 sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
   92286 }
   92287       break;
   92288     case 199: /* where_opt */
   92289     case 201: /* having_opt */
   92290     case 210: /* on_opt */
   92291     case 215: /* sortitem */
   92292     case 226: /* case_operand */
   92293     case 228: /* case_else */
   92294     case 239: /* when_clause */
   92295     case 244: /* key_opt */
   92296 {
   92297 sqlite3ExprDelete(pParse->db, (yypminor->yy132));
   92298 }
   92299       break;
   92300     case 211: /* using_opt */
   92301     case 213: /* inscollist */
   92302     case 219: /* inscollist_opt */
   92303 {
   92304 sqlite3IdListDelete(pParse->db, (yypminor->yy408));
   92305 }
   92306       break;
   92307     case 235: /* trigger_cmd_list */
   92308     case 240: /* trigger_cmd */
   92309 {
   92310 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
   92311 }
   92312       break;
   92313     case 237: /* trigger_event */
   92314 {
   92315 sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
   92316 }
   92317       break;
   92318     default:  break;   /* If no destructor action specified: do nothing */
   92319   }
   92320 }
   92321 
   92322 /*
   92323 ** Pop the parser's stack once.
   92324 **
   92325 ** If there is a destructor routine associated with the token which
   92326 ** is popped from the stack, then call it.
   92327 **
   92328 ** Return the major token number for the symbol popped.
   92329 */
   92330 static int yy_pop_parser_stack(yyParser *pParser){
   92331   YYCODETYPE yymajor;
   92332   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
   92333 
   92334   /* There is no mechanism by which the parser stack can be popped below
   92335   ** empty in SQLite.  */
   92336   if( NEVER(pParser->yyidx<0) ) return 0;
   92337 #ifndef NDEBUG
   92338   if( yyTraceFILE && pParser->yyidx>=0 ){
   92339     fprintf(yyTraceFILE,"%sPopping %s\n",
   92340       yyTracePrompt,
   92341       yyTokenName[yytos->major]);
   92342   }
   92343 #endif
   92344   yymajor = yytos->major;
   92345   yy_destructor(pParser, yymajor, &yytos->minor);
   92346   pParser->yyidx--;
   92347   return yymajor;
   92348 }
   92349 
   92350 /*
   92351 ** Deallocate and destroy a parser.  Destructors are all called for
   92352 ** all stack elements before shutting the parser down.
   92353 **
   92354 ** Inputs:
   92355 ** <ul>
   92356 ** <li>  A pointer to the parser.  This should be a pointer
   92357 **       obtained from sqlite3ParserAlloc.
   92358 ** <li>  A pointer to a function used to reclaim memory obtained
   92359 **       from malloc.
   92360 ** </ul>
   92361 */
   92362 SQLITE_PRIVATE void sqlite3ParserFree(
   92363   void *p,                    /* The parser to be deleted */
   92364   void (*freeProc)(void*)     /* Function used to reclaim memory */
   92365 ){
   92366   yyParser *pParser = (yyParser*)p;
   92367   /* In SQLite, we never try to destroy a parser that was not successfully
   92368   ** created in the first place. */
   92369   if( NEVER(pParser==0) ) return;
   92370   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
   92371 #if YYSTACKDEPTH<=0
   92372   free(pParser->yystack);
   92373 #endif
   92374   (*freeProc)((void*)pParser);
   92375 }
   92376 
   92377 /*
   92378 ** Return the peak depth of the stack for a parser.
   92379 */
   92380 #ifdef YYTRACKMAXSTACKDEPTH
   92381 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
   92382   yyParser *pParser = (yyParser*)p;
   92383   return pParser->yyidxMax;
   92384 }
   92385 #endif
   92386 
   92387 /*
   92388 ** Find the appropriate action for a parser given the terminal
   92389 ** look-ahead token iLookAhead.
   92390 **
   92391 ** If the look-ahead token is YYNOCODE, then check to see if the action is
   92392 ** independent of the look-ahead.  If it is, return the action, otherwise
   92393 ** return YY_NO_ACTION.
   92394 */
   92395 static int yy_find_shift_action(
   92396   yyParser *pParser,        /* The parser */
   92397   YYCODETYPE iLookAhead     /* The look-ahead token */
   92398 ){
   92399   int i;
   92400   int stateno = pParser->yystack[pParser->yyidx].stateno;
   92401 
   92402   if( stateno>YY_SHIFT_COUNT
   92403    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
   92404     return yy_default[stateno];
   92405   }
   92406   assert( iLookAhead!=YYNOCODE );
   92407   i += iLookAhead;
   92408   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
   92409     if( iLookAhead>0 ){
   92410 #ifdef YYFALLBACK
   92411       YYCODETYPE iFallback;            /* Fallback token */
   92412       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
   92413              && (iFallback = yyFallback[iLookAhead])!=0 ){
   92414 #ifndef NDEBUG
   92415         if( yyTraceFILE ){
   92416           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
   92417              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
   92418         }
   92419 #endif
   92420         return yy_find_shift_action(pParser, iFallback);
   92421       }
   92422 #endif
   92423 #ifdef YYWILDCARD
   92424       {
   92425         int j = i - iLookAhead + YYWILDCARD;
   92426         if(
   92427 #if YY_SHIFT_MIN+YYWILDCARD<0
   92428           j>=0 &&
   92429 #endif
   92430 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
   92431           j<YY_ACTTAB_COUNT &&
   92432 #endif
   92433           yy_lookahead[j]==YYWILDCARD
   92434         ){
   92435 #ifndef NDEBUG
   92436           if( yyTraceFILE ){
   92437             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
   92438                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
   92439           }
   92440 #endif /* NDEBUG */
   92441           return yy_action[j];
   92442         }
   92443       }
   92444 #endif /* YYWILDCARD */
   92445     }
   92446     return yy_default[stateno];
   92447   }else{
   92448     return yy_action[i];
   92449   }
   92450 }
   92451 
   92452 /*
   92453 ** Find the appropriate action for a parser given the non-terminal
   92454 ** look-ahead token iLookAhead.
   92455 **
   92456 ** If the look-ahead token is YYNOCODE, then check to see if the action is
   92457 ** independent of the look-ahead.  If it is, return the action, otherwise
   92458 ** return YY_NO_ACTION.
   92459 */
   92460 static int yy_find_reduce_action(
   92461   int stateno,              /* Current state number */
   92462   YYCODETYPE iLookAhead     /* The look-ahead token */
   92463 ){
   92464   int i;
   92465 #ifdef YYERRORSYMBOL
   92466   if( stateno>YY_REDUCE_COUNT ){
   92467     return yy_default[stateno];
   92468   }
   92469 #else
   92470   assert( stateno<=YY_REDUCE_COUNT );
   92471 #endif
   92472   i = yy_reduce_ofst[stateno];
   92473   assert( i!=YY_REDUCE_USE_DFLT );
   92474   assert( iLookAhead!=YYNOCODE );
   92475   i += iLookAhead;
   92476 #ifdef YYERRORSYMBOL
   92477   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
   92478     return yy_default[stateno];
   92479   }
   92480 #else
   92481   assert( i>=0 && i<YY_ACTTAB_COUNT );
   92482   assert( yy_lookahead[i]==iLookAhead );
   92483 #endif
   92484   return yy_action[i];
   92485 }
   92486 
   92487 /*
   92488 ** The following routine is called if the stack overflows.
   92489 */
   92490 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
   92491    sqlite3ParserARG_FETCH;
   92492    yypParser->yyidx--;
   92493 #ifndef NDEBUG
   92494    if( yyTraceFILE ){
   92495      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
   92496    }
   92497 #endif
   92498    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   92499    /* Here code is inserted which will execute if the parser
   92500    ** stack every overflows */
   92501 
   92502   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
   92503   sqlite3ErrorMsg(pParse, "parser stack overflow");
   92504   pParse->parseError = 1;
   92505    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
   92506 }
   92507 
   92508 /*
   92509 ** Perform a shift action.
   92510 */
   92511 static void yy_shift(
   92512   yyParser *yypParser,          /* The parser to be shifted */
   92513   int yyNewState,               /* The new state to shift in */
   92514   int yyMajor,                  /* The major token to shift in */
   92515   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
   92516 ){
   92517   yyStackEntry *yytos;
   92518   yypParser->yyidx++;
   92519 #ifdef YYTRACKMAXSTACKDEPTH
   92520   if( yypParser->yyidx>yypParser->yyidxMax ){
   92521     yypParser->yyidxMax = yypParser->yyidx;
   92522   }
   92523 #endif
   92524 #if YYSTACKDEPTH>0
   92525   if( yypParser->yyidx>=YYSTACKDEPTH ){
   92526     yyStackOverflow(yypParser, yypMinor);
   92527     return;
   92528   }
   92529 #else
   92530   if( yypParser->yyidx>=yypParser->yystksz ){
   92531     yyGrowStack(yypParser);
   92532     if( yypParser->yyidx>=yypParser->yystksz ){
   92533       yyStackOverflow(yypParser, yypMinor);
   92534       return;
   92535     }
   92536   }
   92537 #endif
   92538   yytos = &yypParser->yystack[yypParser->yyidx];
   92539   yytos->stateno = (YYACTIONTYPE)yyNewState;
   92540   yytos->major = (YYCODETYPE)yyMajor;
   92541   yytos->minor = *yypMinor;
   92542 #ifndef NDEBUG
   92543   if( yyTraceFILE && yypParser->yyidx>0 ){
   92544     int i;
   92545     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
   92546     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
   92547     for(i=1; i<=yypParser->yyidx; i++)
   92548       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
   92549     fprintf(yyTraceFILE,"\n");
   92550   }
   92551 #endif
   92552 }
   92553 
   92554 /* The following table contains information about every rule that
   92555 ** is used during the reduce.
   92556 */
   92557 static const struct {
   92558   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
   92559   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
   92560 } yyRuleInfo[] = {
   92561   { 142, 1 },
   92562   { 143, 2 },
   92563   { 143, 1 },
   92564   { 144, 1 },
   92565   { 144, 3 },
   92566   { 145, 0 },
   92567   { 145, 1 },
   92568   { 145, 3 },
   92569   { 146, 1 },
   92570   { 147, 3 },
   92571   { 149, 0 },
   92572   { 149, 1 },
   92573   { 149, 2 },
   92574   { 148, 0 },
   92575   { 148, 1 },
   92576   { 148, 1 },
   92577   { 148, 1 },
   92578   { 147, 2 },
   92579   { 147, 2 },
   92580   { 147, 2 },
   92581   { 151, 1 },
   92582   { 151, 0 },
   92583   { 147, 2 },
   92584   { 147, 3 },
   92585   { 147, 5 },
   92586   { 147, 2 },
   92587   { 152, 6 },
   92588   { 154, 1 },
   92589   { 156, 0 },
   92590   { 156, 3 },
   92591   { 155, 1 },
   92592   { 155, 0 },
   92593   { 153, 4 },
   92594   { 153, 2 },
   92595   { 158, 3 },
   92596   { 158, 1 },
   92597   { 161, 3 },
   92598   { 162, 1 },
   92599   { 165, 1 },
   92600   { 165, 1 },
   92601   { 166, 1 },
   92602   { 150, 1 },
   92603   { 150, 1 },
   92604   { 150, 1 },
   92605   { 163, 0 },
   92606   { 163, 1 },
   92607   { 167, 1 },
   92608   { 167, 4 },
   92609   { 167, 6 },
   92610   { 168, 1 },
   92611   { 168, 2 },
   92612   { 169, 1 },
   92613   { 169, 1 },
   92614   { 164, 2 },
   92615   { 164, 0 },
   92616   { 172, 3 },
   92617   { 172, 1 },
   92618   { 173, 2 },
   92619   { 173, 4 },
   92620   { 173, 3 },
   92621   { 173, 3 },
   92622   { 173, 2 },
   92623   { 173, 2 },
   92624   { 173, 3 },
   92625   { 173, 5 },
   92626   { 173, 2 },
   92627   { 173, 4 },
   92628   { 173, 4 },
   92629   { 173, 1 },
   92630   { 173, 2 },
   92631   { 178, 0 },
   92632   { 178, 1 },
   92633   { 180, 0 },
   92634   { 180, 2 },
   92635   { 182, 2 },
   92636   { 182, 3 },
   92637   { 182, 3 },
   92638   { 182, 3 },
   92639   { 183, 2 },
   92640   { 183, 2 },
   92641   { 183, 1 },
   92642   { 183, 1 },
   92643   { 183, 2 },
   92644   { 181, 3 },
   92645   { 181, 2 },
   92646   { 184, 0 },
   92647   { 184, 2 },
   92648   { 184, 2 },
   92649   { 159, 0 },
   92650   { 159, 2 },
   92651   { 185, 3 },
   92652   { 185, 2 },
   92653   { 185, 1 },
   92654   { 186, 2 },
   92655   { 186, 7 },
   92656   { 186, 5 },
   92657   { 186, 5 },
   92658   { 186, 10 },
   92659   { 188, 0 },
   92660   { 188, 1 },
   92661   { 176, 0 },
   92662   { 176, 3 },
   92663   { 189, 0 },
   92664   { 189, 2 },
   92665   { 190, 1 },
   92666   { 190, 1 },
   92667   { 190, 1 },
   92668   { 147, 4 },
   92669   { 192, 2 },
   92670   { 192, 0 },
   92671   { 147, 8 },
   92672   { 147, 4 },
   92673   { 147, 1 },
   92674   { 160, 1 },
   92675   { 160, 3 },
   92676   { 195, 1 },
   92677   { 195, 2 },
   92678   { 195, 1 },
   92679   { 194, 9 },
   92680   { 196, 1 },
   92681   { 196, 1 },
   92682   { 196, 0 },
   92683   { 204, 2 },
   92684   { 204, 0 },
   92685   { 197, 3 },
   92686   { 197, 2 },
   92687   { 197, 4 },
   92688   { 205, 2 },
   92689   { 205, 1 },
   92690   { 205, 0 },
   92691   { 198, 0 },
   92692   { 198, 2 },
   92693   { 207, 2 },
   92694   { 207, 0 },
   92695   { 206, 7 },
   92696   { 206, 7 },
   92697   { 206, 7 },
   92698   { 157, 0 },
   92699   { 157, 2 },
   92700   { 193, 2 },
   92701   { 208, 1 },
   92702   { 208, 2 },
   92703   { 208, 3 },
   92704   { 208, 4 },
   92705   { 210, 2 },
   92706   { 210, 0 },
   92707   { 209, 0 },
   92708   { 209, 3 },
   92709   { 209, 2 },
   92710   { 211, 4 },
   92711   { 211, 0 },
   92712   { 202, 0 },
   92713   { 202, 3 },
   92714   { 214, 4 },
   92715   { 214, 2 },
   92716   { 215, 1 },
   92717   { 177, 1 },
   92718   { 177, 1 },
   92719   { 177, 0 },
   92720   { 200, 0 },
   92721   { 200, 3 },
   92722   { 201, 0 },
   92723   { 201, 2 },
   92724   { 203, 0 },
   92725   { 203, 2 },
   92726   { 203, 4 },
   92727   { 203, 4 },
   92728   { 147, 5 },
   92729   { 199, 0 },
   92730   { 199, 2 },
   92731   { 147, 7 },
   92732   { 217, 5 },
   92733   { 217, 3 },
   92734   { 147, 8 },
   92735   { 147, 5 },
   92736   { 147, 6 },
   92737   { 218, 2 },
   92738   { 218, 1 },
   92739   { 220, 3 },
   92740   { 220, 1 },
   92741   { 219, 0 },
   92742   { 219, 3 },
   92743   { 213, 3 },
   92744   { 213, 1 },
   92745   { 175, 1 },
   92746   { 175, 3 },
   92747   { 174, 1 },
   92748   { 175, 1 },
   92749   { 175, 1 },
   92750   { 175, 3 },
   92751   { 175, 5 },
   92752   { 174, 1 },
   92753   { 174, 1 },
   92754   { 175, 1 },
   92755   { 175, 1 },
   92756   { 175, 3 },
   92757   { 175, 6 },
   92758   { 175, 5 },
   92759   { 175, 4 },
   92760   { 174, 1 },
   92761   { 175, 3 },
   92762   { 175, 3 },
   92763   { 175, 3 },
   92764   { 175, 3 },
   92765   { 175, 3 },
   92766   { 175, 3 },
   92767   { 175, 3 },
   92768   { 175, 3 },
   92769   { 222, 1 },
   92770   { 222, 2 },
   92771   { 222, 1 },
   92772   { 222, 2 },
   92773   { 223, 2 },
   92774   { 223, 0 },
   92775   { 175, 4 },
   92776   { 175, 2 },
   92777   { 175, 3 },
   92778   { 175, 3 },
   92779   { 175, 4 },
   92780   { 175, 2 },
   92781   { 175, 2 },
   92782   { 175, 2 },
   92783   { 175, 2 },
   92784   { 224, 1 },
   92785   { 224, 2 },
   92786   { 175, 5 },
   92787   { 225, 1 },
   92788   { 225, 2 },
   92789   { 175, 5 },
   92790   { 175, 3 },
   92791   { 175, 5 },
   92792   { 175, 4 },
   92793   { 175, 4 },
   92794   { 175, 5 },
   92795   { 227, 5 },
   92796   { 227, 4 },
   92797   { 228, 2 },
   92798   { 228, 0 },
   92799   { 226, 1 },
   92800   { 226, 0 },
   92801   { 221, 1 },
   92802   { 221, 0 },
   92803   { 216, 3 },
   92804   { 216, 1 },
   92805   { 147, 11 },
   92806   { 229, 1 },
   92807   { 229, 0 },
   92808   { 179, 0 },
   92809   { 179, 3 },
   92810   { 187, 5 },
   92811   { 187, 3 },
   92812   { 230, 0 },
   92813   { 230, 2 },
   92814   { 147, 4 },
   92815   { 147, 1 },
   92816   { 147, 2 },
   92817   { 147, 3 },
   92818   { 147, 5 },
   92819   { 147, 6 },
   92820   { 147, 5 },
   92821   { 147, 6 },
   92822   { 231, 1 },
   92823   { 231, 1 },
   92824   { 231, 1 },
   92825   { 231, 1 },
   92826   { 231, 1 },
   92827   { 170, 2 },
   92828   { 171, 2 },
   92829   { 233, 1 },
   92830   { 232, 1 },
   92831   { 232, 0 },
   92832   { 147, 5 },
   92833   { 234, 11 },
   92834   { 236, 1 },
   92835   { 236, 1 },
   92836   { 236, 2 },
   92837   { 236, 0 },
   92838   { 237, 1 },
   92839   { 237, 1 },
   92840   { 237, 3 },
   92841   { 238, 0 },
   92842   { 238, 3 },
   92843   { 239, 0 },
   92844   { 239, 2 },
   92845   { 235, 3 },
   92846   { 235, 2 },
   92847   { 241, 1 },
   92848   { 241, 3 },
   92849   { 242, 0 },
   92850   { 242, 3 },
   92851   { 242, 2 },
   92852   { 240, 7 },
   92853   { 240, 8 },
   92854   { 240, 5 },
   92855   { 240, 5 },
   92856   { 240, 1 },
   92857   { 175, 4 },
   92858   { 175, 6 },
   92859   { 191, 1 },
   92860   { 191, 1 },
   92861   { 191, 1 },
   92862   { 147, 4 },
   92863   { 147, 6 },
   92864   { 147, 3 },
   92865   { 244, 0 },
   92866   { 244, 2 },
   92867   { 243, 1 },
   92868   { 243, 0 },
   92869   { 147, 1 },
   92870   { 147, 3 },
   92871   { 147, 1 },
   92872   { 147, 3 },
   92873   { 147, 6 },
   92874   { 147, 6 },
   92875   { 245, 1 },
   92876   { 246, 0 },
   92877   { 246, 1 },
   92878   { 147, 1 },
   92879   { 147, 4 },
   92880   { 247, 7 },
   92881   { 248, 1 },
   92882   { 248, 3 },
   92883   { 249, 0 },
   92884   { 249, 2 },
   92885   { 250, 1 },
   92886   { 250, 3 },
   92887   { 251, 1 },
   92888   { 252, 0 },
   92889   { 252, 4 },
   92890   { 252, 2 },
   92891 };
   92892 
   92893 static void yy_accept(yyParser*);  /* Forward Declaration */
   92894 
   92895 /*
   92896 ** Perform a reduce action and the shift that must immediately
   92897 ** follow the reduce.
   92898 */
   92899 static void yy_reduce(
   92900   yyParser *yypParser,         /* The parser */
   92901   int yyruleno                 /* Number of the rule by which to reduce */
   92902 ){
   92903   int yygoto;                     /* The next state */
   92904   int yyact;                      /* The next action */
   92905   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
   92906   yyStackEntry *yymsp;            /* The top of the parser's stack */
   92907   int yysize;                     /* Amount to pop the stack */
   92908   sqlite3ParserARG_FETCH;
   92909   yymsp = &yypParser->yystack[yypParser->yyidx];
   92910 #ifndef NDEBUG
   92911   if( yyTraceFILE && yyruleno>=0
   92912         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
   92913     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
   92914       yyRuleName[yyruleno]);
   92915   }
   92916 #endif /* NDEBUG */
   92917 
   92918   /* Silence complaints from purify about yygotominor being uninitialized
   92919   ** in some cases when it is copied into the stack after the following
   92920   ** switch.  yygotominor is uninitialized when a rule reduces that does
   92921   ** not set the value of its left-hand side nonterminal.  Leaving the
   92922   ** value of the nonterminal uninitialized is utterly harmless as long
   92923   ** as the value is never used.  So really the only thing this code
   92924   ** accomplishes is to quieten purify.
   92925   **
   92926   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
   92927   ** without this code, their parser segfaults.  I'm not sure what there
   92928   ** parser is doing to make this happen.  This is the second bug report
   92929   ** from wireshark this week.  Clearly they are stressing Lemon in ways
   92930   ** that it has not been previously stressed...  (SQLite ticket #2172)
   92931   */
   92932   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
   92933   yygotominor = yyzerominor;
   92934 
   92935 
   92936   switch( yyruleno ){
   92937   /* Beginning here are the reduction cases.  A typical example
   92938   ** follows:
   92939   **   case 0:
   92940   **  #line <lineno> <grammarfile>
   92941   **     { ... }           // User supplied code
   92942   **  #line <lineno> <thisfile>
   92943   **     break;
   92944   */
   92945       case 5: /* explain ::= */
   92946 { sqlite3BeginParse(pParse, 0); }
   92947         break;
   92948       case 6: /* explain ::= EXPLAIN */
   92949 { sqlite3BeginParse(pParse, 1); }
   92950         break;
   92951       case 7: /* explain ::= EXPLAIN QUERY PLAN */
   92952 { sqlite3BeginParse(pParse, 2); }
   92953         break;
   92954       case 8: /* cmdx ::= cmd */
   92955 { sqlite3FinishCoding(pParse); }
   92956         break;
   92957       case 9: /* cmd ::= BEGIN transtype trans_opt */
   92958 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
   92959         break;
   92960       case 13: /* transtype ::= */
   92961 {yygotominor.yy328 = (pParse->db->flags&SQLITE_BeginImmediate) ? TK_IMMEDIATE : TK_DEFERRED;}/* Android Change */
   92962         break;
   92963       case 14: /* transtype ::= DEFERRED */
   92964       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
   92965       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
   92966       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
   92967       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
   92968 {yygotominor.yy328 = yymsp[0].major;}
   92969         break;
   92970       case 17: /* cmd ::= COMMIT trans_opt */
   92971       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
   92972 {sqlite3CommitTransaction(pParse);}
   92973         break;
   92974       case 19: /* cmd ::= ROLLBACK trans_opt */
   92975 {sqlite3RollbackTransaction(pParse);}
   92976         break;
   92977       case 22: /* cmd ::= SAVEPOINT nm */
   92978 {
   92979   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
   92980 }
   92981         break;
   92982       case 23: /* cmd ::= RELEASE savepoint_opt nm */
   92983 {
   92984   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
   92985 }
   92986         break;
   92987       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
   92988 {
   92989   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
   92990 }
   92991         break;
   92992       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
   92993 {
   92994    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
   92995 }
   92996         break;
   92997       case 27: /* createkw ::= CREATE */
   92998 {
   92999   pParse->db->lookaside.bEnabled = 0;
   93000   yygotominor.yy0 = yymsp[0].minor.yy0;
   93001 }
   93002         break;
   93003       case 28: /* ifnotexists ::= */
   93004       case 31: /* temp ::= */ yytestcase(yyruleno==31);
   93005       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
   93006       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
   93007       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
   93008       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
   93009       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
   93010       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
   93011       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
   93012       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
   93013       case 223: /* between_op ::= BETWEEN */ yytestcase(yyruleno==223);
   93014       case 226: /* in_op ::= IN */ yytestcase(yyruleno==226);
   93015 {yygotominor.yy328 = 0;}
   93016         break;
   93017       case 29: /* ifnotexists ::= IF NOT EXISTS */
   93018       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
   93019       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
   93020       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
   93021       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
   93022       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
   93023       case 224: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==224);
   93024       case 227: /* in_op ::= NOT IN */ yytestcase(yyruleno==227);
   93025 {yygotominor.yy328 = 1;}
   93026         break;
   93027       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
   93028 {
   93029   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
   93030 }
   93031         break;
   93032       case 33: /* create_table_args ::= AS select */
   93033 {
   93034   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy3);
   93035   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
   93036 }
   93037         break;
   93038       case 36: /* column ::= columnid type carglist */
   93039 {
   93040   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
   93041   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
   93042 }
   93043         break;
   93044       case 37: /* columnid ::= nm */
   93045 {
   93046   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
   93047   yygotominor.yy0 = yymsp[0].minor.yy0;
   93048 }
   93049         break;
   93050       case 38: /* id ::= ID */
   93051       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
   93052       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
   93053       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
   93054       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
   93055       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
   93056       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
   93057       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
   93058       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
   93059       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
   93060       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
   93061       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
   93062       case 252: /* collate ::= COLLATE ids */ yytestcase(yyruleno==252);
   93063       case 261: /* nmnum ::= plus_num */ yytestcase(yyruleno==261);
   93064       case 262: /* nmnum ::= nm */ yytestcase(yyruleno==262);
   93065       case 263: /* nmnum ::= ON */ yytestcase(yyruleno==263);
   93066       case 264: /* nmnum ::= DELETE */ yytestcase(yyruleno==264);
   93067       case 265: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==265);
   93068       case 266: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==266);
   93069       case 267: /* minus_num ::= MINUS number */ yytestcase(yyruleno==267);
   93070       case 268: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==268);
   93071       case 286: /* trnm ::= nm */ yytestcase(yyruleno==286);
   93072 {yygotominor.yy0 = yymsp[0].minor.yy0;}
   93073         break;
   93074       case 45: /* type ::= typetoken */
   93075 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
   93076         break;
   93077       case 47: /* typetoken ::= typename LP signed RP */
   93078 {
   93079   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
   93080   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
   93081 }
   93082         break;
   93083       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
   93084 {
   93085   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
   93086   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
   93087 }
   93088         break;
   93089       case 50: /* typename ::= typename ids */
   93090 {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);}
   93091         break;
   93092       case 57: /* ccons ::= DEFAULT term */
   93093       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
   93094 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
   93095         break;
   93096       case 58: /* ccons ::= DEFAULT LP expr RP */
   93097 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
   93098         break;
   93099       case 60: /* ccons ::= DEFAULT MINUS term */
   93100 {
   93101   ExprSpan v;
   93102   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
   93103   v.zStart = yymsp[-1].minor.yy0.z;
   93104   v.zEnd = yymsp[0].minor.yy346.zEnd;
   93105   sqlite3AddDefaultValue(pParse,&v);
   93106 }
   93107         break;
   93108       case 61: /* ccons ::= DEFAULT id */
   93109 {
   93110   ExprSpan v;
   93111   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
   93112   sqlite3AddDefaultValue(pParse,&v);
   93113 }
   93114         break;
   93115       case 63: /* ccons ::= NOT NULL onconf */
   93116 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
   93117         break;
   93118       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
   93119 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
   93120         break;
   93121       case 65: /* ccons ::= UNIQUE onconf */
   93122 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
   93123         break;
   93124       case 66: /* ccons ::= CHECK LP expr RP */
   93125 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
   93126         break;
   93127       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
   93128 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
   93129         break;
   93130       case 68: /* ccons ::= defer_subclause */
   93131 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
   93132         break;
   93133       case 69: /* ccons ::= COLLATE ids */
   93134 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
   93135         break;
   93136       case 72: /* refargs ::= */
   93137 { yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
   93138         break;
   93139       case 73: /* refargs ::= refargs refarg */
   93140 { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
   93141         break;
   93142       case 74: /* refarg ::= MATCH nm */
   93143       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
   93144 { yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
   93145         break;
   93146       case 76: /* refarg ::= ON DELETE refact */
   93147 { yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
   93148         break;
   93149       case 77: /* refarg ::= ON UPDATE refact */
   93150 { yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
   93151         break;
   93152       case 78: /* refact ::= SET NULL */
   93153 { yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
   93154         break;
   93155       case 79: /* refact ::= SET DEFAULT */
   93156 { yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
   93157         break;
   93158       case 80: /* refact ::= CASCADE */
   93159 { yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
   93160         break;
   93161       case 81: /* refact ::= RESTRICT */
   93162 { yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
   93163         break;
   93164       case 82: /* refact ::= NO ACTION */
   93165 { yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
   93166         break;
   93167       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
   93168       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
   93169       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
   93170       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
   93171 {yygotominor.yy328 = yymsp[0].minor.yy328;}
   93172         break;
   93173       case 88: /* conslist_opt ::= */
   93174 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
   93175         break;
   93176       case 89: /* conslist_opt ::= COMMA conslist */
   93177 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
   93178         break;
   93179       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
   93180 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
   93181         break;
   93182       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
   93183 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
   93184         break;
   93185       case 96: /* tcons ::= CHECK LP expr RP onconf */
   93186 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
   93187         break;
   93188       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
   93189 {
   93190     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
   93191     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
   93192 }
   93193         break;
   93194       case 100: /* onconf ::= */
   93195 {yygotominor.yy328 = OE_Default;}
   93196         break;
   93197       case 102: /* orconf ::= */
   93198 {yygotominor.yy186 = OE_Default;}
   93199         break;
   93200       case 103: /* orconf ::= OR resolvetype */
   93201 {yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
   93202         break;
   93203       case 105: /* resolvetype ::= IGNORE */
   93204 {yygotominor.yy328 = OE_Ignore;}
   93205         break;
   93206       case 106: /* resolvetype ::= REPLACE */
   93207 {yygotominor.yy328 = OE_Replace;}
   93208         break;
   93209       case 107: /* cmd ::= DROP TABLE ifexists fullname */
   93210 {
   93211   sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
   93212 }
   93213         break;
   93214       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
   93215 {
   93216   sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy3, yymsp[-6].minor.yy328, yymsp[-4].minor.yy328);
   93217 }
   93218         break;
   93219       case 111: /* cmd ::= DROP VIEW ifexists fullname */
   93220 {
   93221   sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
   93222 }
   93223         break;
   93224       case 112: /* cmd ::= select */
   93225 {
   93226   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
   93227   sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
   93228   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
   93229 }
   93230         break;
   93231       case 113: /* select ::= oneselect */
   93232 {yygotominor.yy3 = yymsp[0].minor.yy3;}
   93233         break;
   93234       case 114: /* select ::= select multiselect_op oneselect */
   93235 {
   93236   if( yymsp[0].minor.yy3 ){
   93237     yymsp[0].minor.yy3->op = (u8)yymsp[-1].minor.yy328;
   93238     yymsp[0].minor.yy3->pPrior = yymsp[-2].minor.yy3;
   93239   }else{
   93240     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
   93241   }
   93242   yygotominor.yy3 = yymsp[0].minor.yy3;
   93243 }
   93244         break;
   93245       case 116: /* multiselect_op ::= UNION ALL */
   93246 {yygotominor.yy328 = TK_ALL;}
   93247         break;
   93248       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
   93249 {
   93250   yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy14,yymsp[-5].minor.yy65,yymsp[-4].minor.yy132,yymsp[-3].minor.yy14,yymsp[-2].minor.yy132,yymsp[-1].minor.yy14,yymsp[-7].minor.yy328,yymsp[0].minor.yy476.pLimit,yymsp[0].minor.yy476.pOffset);
   93251 }
   93252         break;
   93253       case 122: /* sclp ::= selcollist COMMA */
   93254       case 248: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==248);
   93255 {yygotominor.yy14 = yymsp[-1].minor.yy14;}
   93256         break;
   93257       case 123: /* sclp ::= */
   93258       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
   93259       case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
   93260       case 241: /* exprlist ::= */ yytestcase(yyruleno==241);
   93261       case 247: /* idxlist_opt ::= */ yytestcase(yyruleno==247);
   93262 {yygotominor.yy14 = 0;}
   93263         break;
   93264       case 124: /* selcollist ::= sclp expr as */
   93265 {
   93266    yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
   93267    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
   93268    sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
   93269 }
   93270         break;
   93271       case 125: /* selcollist ::= sclp STAR */
   93272 {
   93273   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
   93274   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
   93275 }
   93276         break;
   93277       case 126: /* selcollist ::= sclp nm DOT STAR */
   93278 {
   93279   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
   93280   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   93281   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
   93282   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
   93283 }
   93284         break;
   93285       case 129: /* as ::= */
   93286 {yygotominor.yy0.n = 0;}
   93287         break;
   93288       case 130: /* from ::= */
   93289 {yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
   93290         break;
   93291       case 131: /* from ::= FROM seltablist */
   93292 {
   93293   yygotominor.yy65 = yymsp[0].minor.yy65;
   93294   sqlite3SrcListShiftJoinType(yygotominor.yy65);
   93295 }
   93296         break;
   93297       case 132: /* stl_prefix ::= seltablist joinop */
   93298 {
   93299    yygotominor.yy65 = yymsp[-1].minor.yy65;
   93300    if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
   93301 }
   93302         break;
   93303       case 133: /* stl_prefix ::= */
   93304 {yygotominor.yy65 = 0;}
   93305         break;
   93306       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
   93307 {
   93308   yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
   93309   sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
   93310 }
   93311         break;
   93312       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
   93313 {
   93314     yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy3,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
   93315   }
   93316         break;
   93317       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
   93318 {
   93319     if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
   93320       yygotominor.yy65 = yymsp[-4].minor.yy65;
   93321     }else{
   93322       Select *pSubquery;
   93323       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
   93324       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,0,0,0);
   93325       yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
   93326     }
   93327   }
   93328         break;
   93329       case 137: /* dbnm ::= */
   93330       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
   93331 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
   93332         break;
   93333       case 139: /* fullname ::= nm dbnm */
   93334 {yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
   93335         break;
   93336       case 140: /* joinop ::= COMMA|JOIN */
   93337 { yygotominor.yy328 = JT_INNER; }
   93338         break;
   93339       case 141: /* joinop ::= JOIN_KW JOIN */
   93340 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
   93341         break;
   93342       case 142: /* joinop ::= JOIN_KW nm JOIN */
   93343 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
   93344         break;
   93345       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
   93346 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
   93347         break;
   93348       case 144: /* on_opt ::= ON expr */
   93349       case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
   93350       case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
   93351       case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
   93352       case 236: /* case_else ::= ELSE expr */ yytestcase(yyruleno==236);
   93353       case 238: /* case_operand ::= expr */ yytestcase(yyruleno==238);
   93354 {yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
   93355         break;
   93356       case 145: /* on_opt ::= */
   93357       case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
   93358       case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
   93359       case 237: /* case_else ::= */ yytestcase(yyruleno==237);
   93360       case 239: /* case_operand ::= */ yytestcase(yyruleno==239);
   93361 {yygotominor.yy132 = 0;}
   93362         break;
   93363       case 148: /* indexed_opt ::= NOT INDEXED */
   93364 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
   93365         break;
   93366       case 149: /* using_opt ::= USING LP inscollist RP */
   93367       case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
   93368 {yygotominor.yy408 = yymsp[-1].minor.yy408;}
   93369         break;
   93370       case 150: /* using_opt ::= */
   93371       case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
   93372 {yygotominor.yy408 = 0;}
   93373         break;
   93374       case 152: /* orderby_opt ::= ORDER BY sortlist */
   93375       case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
   93376       case 240: /* exprlist ::= nexprlist */ yytestcase(yyruleno==240);
   93377 {yygotominor.yy14 = yymsp[0].minor.yy14;}
   93378         break;
   93379       case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
   93380 {
   93381   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy132);
   93382   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
   93383 }
   93384         break;
   93385       case 154: /* sortlist ::= sortitem sortorder */
   93386 {
   93387   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy132);
   93388   if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
   93389 }
   93390         break;
   93391       case 156: /* sortorder ::= ASC */
   93392       case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
   93393 {yygotominor.yy328 = SQLITE_SO_ASC;}
   93394         break;
   93395       case 157: /* sortorder ::= DESC */
   93396 {yygotominor.yy328 = SQLITE_SO_DESC;}
   93397         break;
   93398       case 163: /* limit_opt ::= */
   93399 {yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
   93400         break;
   93401       case 164: /* limit_opt ::= LIMIT expr */
   93402 {yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
   93403         break;
   93404       case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
   93405 {yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
   93406         break;
   93407       case 166: /* limit_opt ::= LIMIT expr COMMA expr */
   93408 {yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
   93409         break;
   93410       case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
   93411 {
   93412   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
   93413   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
   93414 }
   93415         break;
   93416       case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
   93417 {
   93418   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
   93419   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
   93420   sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
   93421 }
   93422         break;
   93423       case 171: /* setlist ::= setlist COMMA nm EQ expr */
   93424 {
   93425   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
   93426   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
   93427 }
   93428         break;
   93429       case 172: /* setlist ::= nm EQ expr */
   93430 {
   93431   yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
   93432   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
   93433 }
   93434         break;
   93435       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
   93436 {sqlite3Insert(pParse, yymsp[-5].minor.yy65, yymsp[-1].minor.yy14, 0, yymsp[-4].minor.yy408, yymsp[-7].minor.yy186);}
   93437         break;
   93438       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
   93439 {sqlite3Insert(pParse, yymsp[-2].minor.yy65, 0, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);}
   93440         break;
   93441       case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
   93442 {sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);}
   93443         break;
   93444       case 176: /* insert_cmd ::= INSERT orconf */
   93445 {yygotominor.yy186 = yymsp[0].minor.yy186;}
   93446         break;
   93447       case 177: /* insert_cmd ::= REPLACE */
   93448 {yygotominor.yy186 = OE_Replace;}
   93449         break;
   93450       case 178: /* itemlist ::= itemlist COMMA expr */
   93451       case 242: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==242);
   93452 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
   93453         break;
   93454       case 179: /* itemlist ::= expr */
   93455       case 243: /* nexprlist ::= expr */ yytestcase(yyruleno==243);
   93456 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
   93457         break;
   93458       case 182: /* inscollist ::= inscollist COMMA nm */
   93459 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
   93460         break;
   93461       case 183: /* inscollist ::= nm */
   93462 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
   93463         break;
   93464       case 184: /* expr ::= term */
   93465       case 212: /* escape ::= ESCAPE expr */ yytestcase(yyruleno==212);
   93466 {yygotominor.yy346 = yymsp[0].minor.yy346;}
   93467         break;
   93468       case 185: /* expr ::= LP expr RP */
   93469 {yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
   93470         break;
   93471       case 186: /* term ::= NULL */
   93472       case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
   93473       case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
   93474 {spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
   93475         break;
   93476       case 187: /* expr ::= id */
   93477       case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
   93478 {spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
   93479         break;
   93480       case 189: /* expr ::= nm DOT nm */
   93481 {
   93482   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   93483   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
   93484   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
   93485   spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
   93486 }
   93487         break;
   93488       case 190: /* expr ::= nm DOT nm DOT nm */
   93489 {
   93490   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
   93491   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   93492   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
   93493   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
   93494   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
   93495   spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
   93496 }
   93497         break;
   93498       case 193: /* expr ::= REGISTER */
   93499 {
   93500   /* When doing a nested parse, one can include terms in an expression
   93501   ** that look like this:   #1 #2 ...  These terms refer to registers
   93502   ** in the virtual machine.  #N is the N-th register. */
   93503   if( pParse->nested==0 ){
   93504     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
   93505     yygotominor.yy346.pExpr = 0;
   93506   }else{
   93507     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
   93508     if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
   93509   }
   93510   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
   93511 }
   93512         break;
   93513       case 194: /* expr ::= VARIABLE */
   93514 {
   93515   spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
   93516   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
   93517   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
   93518 }
   93519         break;
   93520       case 195: /* expr ::= expr COLLATE ids */
   93521 {
   93522   yygotominor.yy346.pExpr = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
   93523   yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
   93524   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   93525 }
   93526         break;
   93527       case 196: /* expr ::= CAST LP expr AS typetoken RP */
   93528 {
   93529   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
   93530   spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
   93531 }
   93532         break;
   93533       case 197: /* expr ::= ID LP distinct exprlist RP */
   93534 {
   93535   if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
   93536     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
   93537   }
   93538   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
   93539   spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
   93540   if( yymsp[-2].minor.yy328 && yygotominor.yy346.pExpr ){
   93541     yygotominor.yy346.pExpr->flags |= EP_Distinct;
   93542   }
   93543 }
   93544         break;
   93545       case 198: /* expr ::= ID LP STAR RP */
   93546 {
   93547   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
   93548   spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
   93549 }
   93550         break;
   93551       case 199: /* term ::= CTIME_KW */
   93552 {
   93553   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
   93554   ** treated as functions that return constants */
   93555   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
   93556   if( yygotominor.yy346.pExpr ){
   93557     yygotominor.yy346.pExpr->op = TK_CONST_FUNC;
   93558   }
   93559   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
   93560 }
   93561         break;
   93562       case 200: /* expr ::= expr AND expr */
   93563       case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
   93564       case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
   93565       case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
   93566       case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
   93567       case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
   93568       case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
   93569       case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
   93570 {spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
   93571         break;
   93572       case 208: /* likeop ::= LIKE_KW */
   93573       case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
   93574 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 0;}
   93575         break;
   93576       case 209: /* likeop ::= NOT LIKE_KW */
   93577       case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
   93578 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 1;}
   93579         break;
   93580       case 213: /* escape ::= */
   93581 {memset(&yygotominor.yy346,0,sizeof(yygotominor.yy346));}
   93582         break;
   93583       case 214: /* expr ::= expr likeop expr escape */
   93584 {
   93585   ExprList *pList;
   93586   pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy346.pExpr);
   93587   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy346.pExpr);
   93588   if( yymsp[0].minor.yy346.pExpr ){
   93589     pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
   93590   }
   93591   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy96.eOperator);
   93592   if( yymsp[-2].minor.yy96.not ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   93593   yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
   93594   yygotominor.yy346.zEnd = yymsp[-1].minor.yy346.zEnd;
   93595   if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
   93596 }
   93597         break;
   93598       case 215: /* expr ::= expr ISNULL|NOTNULL */
   93599 {spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
   93600         break;
   93601       case 216: /* expr ::= expr NOT NULL */
   93602 {spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
   93603         break;
   93604       case 217: /* expr ::= expr IS expr */
   93605 {
   93606   spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
   93607   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
   93608 }
   93609         break;
   93610       case 218: /* expr ::= expr IS NOT expr */
   93611 {
   93612   spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
   93613   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
   93614 }
   93615         break;
   93616       case 219: /* expr ::= NOT expr */
   93617       case 220: /* expr ::= BITNOT expr */ yytestcase(yyruleno==220);
   93618 {spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
   93619         break;
   93620       case 221: /* expr ::= MINUS expr */
   93621 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
   93622         break;
   93623       case 222: /* expr ::= PLUS expr */
   93624 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
   93625         break;
   93626       case 225: /* expr ::= expr between_op expr AND expr */
   93627 {
   93628   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
   93629   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
   93630   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
   93631   if( yygotominor.yy346.pExpr ){
   93632     yygotominor.yy346.pExpr->x.pList = pList;
   93633   }else{
   93634     sqlite3ExprListDelete(pParse->db, pList);
   93635   }
   93636   if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   93637   yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
   93638   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
   93639 }
   93640         break;
   93641       case 228: /* expr ::= expr in_op LP exprlist RP */
   93642 {
   93643     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
   93644     if( yygotominor.yy346.pExpr ){
   93645       yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
   93646       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
   93647     }else{
   93648       sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
   93649     }
   93650     if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   93651     yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
   93652     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   93653   }
   93654         break;
   93655       case 229: /* expr ::= LP select RP */
   93656 {
   93657     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
   93658     if( yygotominor.yy346.pExpr ){
   93659       yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
   93660       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
   93661       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
   93662     }else{
   93663       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
   93664     }
   93665     yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
   93666     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   93667   }
   93668         break;
   93669       case 230: /* expr ::= expr in_op LP select RP */
   93670 {
   93671     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
   93672     if( yygotominor.yy346.pExpr ){
   93673       yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
   93674       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
   93675       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
   93676     }else{
   93677       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
   93678     }
   93679     if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   93680     yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
   93681     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   93682   }
   93683         break;
   93684       case 231: /* expr ::= expr in_op nm dbnm */
   93685 {
   93686     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
   93687     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
   93688     if( yygotominor.yy346.pExpr ){
   93689       yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
   93690       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
   93691       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
   93692     }else{
   93693       sqlite3SrcListDelete(pParse->db, pSrc);
   93694     }
   93695     if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
   93696     yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
   93697     yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
   93698   }
   93699         break;
   93700       case 232: /* expr ::= EXISTS LP select RP */
   93701 {
   93702     Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
   93703     if( p ){
   93704       p->x.pSelect = yymsp[-1].minor.yy3;
   93705       ExprSetProperty(p, EP_xIsSelect);
   93706       sqlite3ExprSetHeight(pParse, p);
   93707     }else{
   93708       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
   93709     }
   93710     yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
   93711     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   93712   }
   93713         break;
   93714       case 233: /* expr ::= CASE case_operand case_exprlist case_else END */
   93715 {
   93716   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, yymsp[-1].minor.yy132, 0);
   93717   if( yygotominor.yy346.pExpr ){
   93718     yygotominor.yy346.pExpr->x.pList = yymsp[-2].minor.yy14;
   93719     sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
   93720   }else{
   93721     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
   93722   }
   93723   yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
   93724   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   93725 }
   93726         break;
   93727       case 234: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
   93728 {
   93729   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
   93730   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
   93731 }
   93732         break;
   93733       case 235: /* case_exprlist ::= WHEN expr THEN expr */
   93734 {
   93735   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
   93736   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
   93737 }
   93738         break;
   93739       case 244: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
   93740 {
   93741   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
   93742                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy14, yymsp[-9].minor.yy328,
   93743                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy328);
   93744 }
   93745         break;
   93746       case 245: /* uniqueflag ::= UNIQUE */
   93747       case 299: /* raisetype ::= ABORT */ yytestcase(yyruleno==299);
   93748 {yygotominor.yy328 = OE_Abort;}
   93749         break;
   93750       case 246: /* uniqueflag ::= */
   93751 {yygotominor.yy328 = OE_None;}
   93752         break;
   93753       case 249: /* idxlist ::= idxlist COMMA nm collate sortorder */
   93754 {
   93755   Expr *p = 0;
   93756   if( yymsp[-1].minor.yy0.n>0 ){
   93757     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
   93758     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
   93759   }
   93760   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
   93761   sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
   93762   sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
   93763   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
   93764 }
   93765         break;
   93766       case 250: /* idxlist ::= nm collate sortorder */
   93767 {
   93768   Expr *p = 0;
   93769   if( yymsp[-1].minor.yy0.n>0 ){
   93770     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
   93771     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
   93772   }
   93773   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
   93774   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
   93775   sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
   93776   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
   93777 }
   93778         break;
   93779       case 251: /* collate ::= */
   93780 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
   93781         break;
   93782       case 253: /* cmd ::= DROP INDEX ifexists fullname */
   93783 {sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
   93784         break;
   93785       case 254: /* cmd ::= VACUUM */
   93786       case 255: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==255);
   93787 {sqlite3Vacuum(pParse);}
   93788         break;
   93789       case 256: /* cmd ::= PRAGMA nm dbnm */
   93790 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
   93791         break;
   93792       case 257: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
   93793 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
   93794         break;
   93795       case 258: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
   93796 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
   93797         break;
   93798       case 259: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
   93799 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
   93800         break;
   93801       case 260: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
   93802 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
   93803         break;
   93804       case 271: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
   93805 {
   93806   Token all;
   93807   all.z = yymsp[-3].minor.yy0.z;
   93808   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
   93809   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
   93810 }
   93811         break;
   93812       case 272: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
   93813 {
   93814   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy328, yymsp[-4].minor.yy378.a, yymsp[-4].minor.yy378.b, yymsp[-2].minor.yy65, yymsp[0].minor.yy132, yymsp[-10].minor.yy328, yymsp[-8].minor.yy328);
   93815   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
   93816 }
   93817         break;
   93818       case 273: /* trigger_time ::= BEFORE */
   93819       case 276: /* trigger_time ::= */ yytestcase(yyruleno==276);
   93820 { yygotominor.yy328 = TK_BEFORE; }
   93821         break;
   93822       case 274: /* trigger_time ::= AFTER */
   93823 { yygotominor.yy328 = TK_AFTER;  }
   93824         break;
   93825       case 275: /* trigger_time ::= INSTEAD OF */
   93826 { yygotominor.yy328 = TK_INSTEAD;}
   93827         break;
   93828       case 277: /* trigger_event ::= DELETE|INSERT */
   93829       case 278: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==278);
   93830 {yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
   93831         break;
   93832       case 279: /* trigger_event ::= UPDATE OF inscollist */
   93833 {yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
   93834         break;
   93835       case 282: /* when_clause ::= */
   93836       case 304: /* key_opt ::= */ yytestcase(yyruleno==304);
   93837 { yygotominor.yy132 = 0; }
   93838         break;
   93839       case 283: /* when_clause ::= WHEN expr */
   93840       case 305: /* key_opt ::= KEY expr */ yytestcase(yyruleno==305);
   93841 { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
   93842         break;
   93843       case 284: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
   93844 {
   93845   assert( yymsp[-2].minor.yy473!=0 );
   93846   yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
   93847   yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
   93848   yygotominor.yy473 = yymsp[-2].minor.yy473;
   93849 }
   93850         break;
   93851       case 285: /* trigger_cmd_list ::= trigger_cmd SEMI */
   93852 {
   93853   assert( yymsp[-1].minor.yy473!=0 );
   93854   yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
   93855   yygotominor.yy473 = yymsp[-1].minor.yy473;
   93856 }
   93857         break;
   93858       case 287: /* trnm ::= nm DOT nm */
   93859 {
   93860   yygotominor.yy0 = yymsp[0].minor.yy0;
   93861   sqlite3ErrorMsg(pParse,
   93862         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
   93863         "statements within triggers");
   93864 }
   93865         break;
   93866       case 289: /* tridxby ::= INDEXED BY nm */
   93867 {
   93868   sqlite3ErrorMsg(pParse,
   93869         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
   93870         "within triggers");
   93871 }
   93872         break;
   93873       case 290: /* tridxby ::= NOT INDEXED */
   93874 {
   93875   sqlite3ErrorMsg(pParse,
   93876         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
   93877         "within triggers");
   93878 }
   93879         break;
   93880       case 291: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
   93881 { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
   93882         break;
   93883       case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
   93884 {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy408, yymsp[-1].minor.yy14, 0, yymsp[-7].minor.yy186);}
   93885         break;
   93886       case 293: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
   93887 {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, 0, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
   93888         break;
   93889       case 294: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
   93890 {yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
   93891         break;
   93892       case 295: /* trigger_cmd ::= select */
   93893 {yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
   93894         break;
   93895       case 296: /* expr ::= RAISE LP IGNORE RP */
   93896 {
   93897   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
   93898   if( yygotominor.yy346.pExpr ){
   93899     yygotominor.yy346.pExpr->affinity = OE_Ignore;
   93900   }
   93901   yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
   93902   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   93903 }
   93904         break;
   93905       case 297: /* expr ::= RAISE LP raisetype COMMA nm RP */
   93906 {
   93907   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
   93908   if( yygotominor.yy346.pExpr ) {
   93909     yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
   93910   }
   93911   yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
   93912   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   93913 }
   93914         break;
   93915       case 298: /* raisetype ::= ROLLBACK */
   93916 {yygotominor.yy328 = OE_Rollback;}
   93917         break;
   93918       case 300: /* raisetype ::= FAIL */
   93919 {yygotominor.yy328 = OE_Fail;}
   93920         break;
   93921       case 301: /* cmd ::= DROP TRIGGER ifexists fullname */
   93922 {
   93923   sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
   93924 }
   93925         break;
   93926       case 302: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
   93927 {
   93928   sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
   93929 }
   93930         break;
   93931       case 303: /* cmd ::= DETACH database_kw_opt expr */
   93932 {
   93933   sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
   93934 }
   93935         break;
   93936       case 308: /* cmd ::= REINDEX */
   93937 {sqlite3Reindex(pParse, 0, 0);}
   93938         break;
   93939       case 309: /* cmd ::= REINDEX nm dbnm */
   93940 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
   93941         break;
   93942       case 310: /* cmd ::= ANALYZE */
   93943 {sqlite3Analyze(pParse, 0, 0);}
   93944         break;
   93945       case 311: /* cmd ::= ANALYZE nm dbnm */
   93946 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
   93947         break;
   93948       case 312: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
   93949 {
   93950   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
   93951 }
   93952         break;
   93953       case 313: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
   93954 {
   93955   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
   93956 }
   93957         break;
   93958       case 314: /* add_column_fullname ::= fullname */
   93959 {
   93960   pParse->db->lookaside.bEnabled = 0;
   93961   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
   93962 }
   93963         break;
   93964       case 317: /* cmd ::= create_vtab */
   93965 {sqlite3VtabFinishParse(pParse,0);}
   93966         break;
   93967       case 318: /* cmd ::= create_vtab LP vtabarglist RP */
   93968 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
   93969         break;
   93970       case 319: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
   93971 {
   93972     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
   93973 }
   93974         break;
   93975       case 322: /* vtabarg ::= */
   93976 {sqlite3VtabArgInit(pParse);}
   93977         break;
   93978       case 324: /* vtabargtoken ::= ANY */
   93979       case 325: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==325);
   93980       case 326: /* lp ::= LP */ yytestcase(yyruleno==326);
   93981 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
   93982         break;
   93983       default:
   93984       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
   93985       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
   93986       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
   93987       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
   93988       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
   93989       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
   93990       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
   93991       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
   93992       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
   93993       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
   93994       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
   93995       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
   93996       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
   93997       /* (44) type ::= */ yytestcase(yyruleno==44);
   93998       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
   93999       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
   94000       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
   94001       /* (54) carglist ::= */ yytestcase(yyruleno==54);
   94002       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
   94003       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
   94004       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
   94005       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
   94006       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
   94007       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
   94008       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
   94009       /* (269) plus_opt ::= PLUS */ yytestcase(yyruleno==269);
   94010       /* (270) plus_opt ::= */ yytestcase(yyruleno==270);
   94011       /* (280) foreach_clause ::= */ yytestcase(yyruleno==280);
   94012       /* (281) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==281);
   94013       /* (288) tridxby ::= */ yytestcase(yyruleno==288);
   94014       /* (306) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==306);
   94015       /* (307) database_kw_opt ::= */ yytestcase(yyruleno==307);
   94016       /* (315) kwcolumn_opt ::= */ yytestcase(yyruleno==315);
   94017       /* (316) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==316);
   94018       /* (320) vtabarglist ::= vtabarg */ yytestcase(yyruleno==320);
   94019       /* (321) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==321);
   94020       /* (323) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==323);
   94021       /* (327) anylist ::= */ yytestcase(yyruleno==327);
   94022       /* (328) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==328);
   94023       /* (329) anylist ::= anylist ANY */ yytestcase(yyruleno==329);
   94024         break;
   94025   };
   94026   yygoto = yyRuleInfo[yyruleno].lhs;
   94027   yysize = yyRuleInfo[yyruleno].nrhs;
   94028   yypParser->yyidx -= yysize;
   94029   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
   94030   if( yyact < YYNSTATE ){
   94031 #ifdef NDEBUG
   94032     /* If we are not debugging and the reduce action popped at least
   94033     ** one element off the stack, then we can push the new element back
   94034     ** onto the stack here, and skip the stack overflow test in yy_shift().
   94035     ** That gives a significant speed improvement. */
   94036     if( yysize ){
   94037       yypParser->yyidx++;
   94038       yymsp -= yysize-1;
   94039       yymsp->stateno = (YYACTIONTYPE)yyact;
   94040       yymsp->major = (YYCODETYPE)yygoto;
   94041       yymsp->minor = yygotominor;
   94042     }else
   94043 #endif
   94044     {
   94045       yy_shift(yypParser,yyact,yygoto,&yygotominor);
   94046     }
   94047   }else{
   94048     assert( yyact == YYNSTATE + YYNRULE + 1 );
   94049     yy_accept(yypParser);
   94050   }
   94051 }
   94052 
   94053 /*
   94054 ** The following code executes when the parse fails
   94055 */
   94056 #ifndef YYNOERRORRECOVERY
   94057 static void yy_parse_failed(
   94058   yyParser *yypParser           /* The parser */
   94059 ){
   94060   sqlite3ParserARG_FETCH;
   94061 #ifndef NDEBUG
   94062   if( yyTraceFILE ){
   94063     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
   94064   }
   94065 #endif
   94066   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   94067   /* Here code is inserted which will be executed whenever the
   94068   ** parser fails */
   94069   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   94070 }
   94071 #endif /* YYNOERRORRECOVERY */
   94072 
   94073 /*
   94074 ** The following code executes when a syntax error first occurs.
   94075 */
   94076 static void yy_syntax_error(
   94077   yyParser *yypParser,           /* The parser */
   94078   int yymajor,                   /* The major type of the error token */
   94079   YYMINORTYPE yyminor            /* The minor type of the error token */
   94080 ){
   94081   sqlite3ParserARG_FETCH;
   94082 #define TOKEN (yyminor.yy0)
   94083 
   94084   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
   94085   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
   94086   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
   94087   pParse->parseError = 1;
   94088   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   94089 }
   94090 
   94091 /*
   94092 ** The following is executed when the parser accepts
   94093 */
   94094 static void yy_accept(
   94095   yyParser *yypParser           /* The parser */
   94096 ){
   94097   sqlite3ParserARG_FETCH;
   94098 #ifndef NDEBUG
   94099   if( yyTraceFILE ){
   94100     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
   94101   }
   94102 #endif
   94103   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   94104   /* Here code is inserted which will be executed whenever the
   94105   ** parser accepts */
   94106   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   94107 }
   94108 
   94109 /* The main parser program.
   94110 ** The first argument is a pointer to a structure obtained from
   94111 ** "sqlite3ParserAlloc" which describes the current state of the parser.
   94112 ** The second argument is the major token number.  The third is
   94113 ** the minor token.  The fourth optional argument is whatever the
   94114 ** user wants (and specified in the grammar) and is available for
   94115 ** use by the action routines.
   94116 **
   94117 ** Inputs:
   94118 ** <ul>
   94119 ** <li> A pointer to the parser (an opaque structure.)
   94120 ** <li> The major token number.
   94121 ** <li> The minor token number.
   94122 ** <li> An option argument of a grammar-specified type.
   94123 ** </ul>
   94124 **
   94125 ** Outputs:
   94126 ** None.
   94127 */
   94128 SQLITE_PRIVATE void sqlite3Parser(
   94129   void *yyp,                   /* The parser */
   94130   int yymajor,                 /* The major token code number */
   94131   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
   94132   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
   94133 ){
   94134   YYMINORTYPE yyminorunion;
   94135   int yyact;            /* The parser action. */
   94136   int yyendofinput;     /* True if we are at the end of input */
   94137 #ifdef YYERRORSYMBOL
   94138   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
   94139 #endif
   94140   yyParser *yypParser;  /* The parser */
   94141 
   94142   /* (re)initialize the parser, if necessary */
   94143   yypParser = (yyParser*)yyp;
   94144   if( yypParser->yyidx<0 ){
   94145 #if YYSTACKDEPTH<=0
   94146     if( yypParser->yystksz <=0 ){
   94147       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
   94148       yyminorunion = yyzerominor;
   94149       yyStackOverflow(yypParser, &yyminorunion);
   94150       return;
   94151     }
   94152 #endif
   94153     yypParser->yyidx = 0;
   94154     yypParser->yyerrcnt = -1;
   94155     yypParser->yystack[0].stateno = 0;
   94156     yypParser->yystack[0].major = 0;
   94157   }
   94158   yyminorunion.yy0 = yyminor;
   94159   yyendofinput = (yymajor==0);
   94160   sqlite3ParserARG_STORE;
   94161 
   94162 #ifndef NDEBUG
   94163   if( yyTraceFILE ){
   94164     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
   94165   }
   94166 #endif
   94167 
   94168   do{
   94169     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
   94170     if( yyact<YYNSTATE ){
   94171       assert( !yyendofinput );  /* Impossible to shift the $ token */
   94172       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
   94173       yypParser->yyerrcnt--;
   94174       yymajor = YYNOCODE;
   94175     }else if( yyact < YYNSTATE + YYNRULE ){
   94176       yy_reduce(yypParser,yyact-YYNSTATE);
   94177     }else{
   94178       assert( yyact == YY_ERROR_ACTION );
   94179 #ifdef YYERRORSYMBOL
   94180       int yymx;
   94181 #endif
   94182 #ifndef NDEBUG
   94183       if( yyTraceFILE ){
   94184         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
   94185       }
   94186 #endif
   94187 #ifdef YYERRORSYMBOL
   94188       /* A syntax error has occurred.
   94189       ** The response to an error depends upon whether or not the
   94190       ** grammar defines an error token "ERROR".
   94191       **
   94192       ** This is what we do if the grammar does define ERROR:
   94193       **
   94194       **  * Call the %syntax_error function.
   94195       **
   94196       **  * Begin popping the stack until we enter a state where
   94197       **    it is legal to shift the error symbol, then shift
   94198       **    the error symbol.
   94199       **
   94200       **  * Set the error count to three.
   94201       **
   94202       **  * Begin accepting and shifting new tokens.  No new error
   94203       **    processing will occur until three tokens have been
   94204       **    shifted successfully.
   94205       **
   94206       */
   94207       if( yypParser->yyerrcnt<0 ){
   94208         yy_syntax_error(yypParser,yymajor,yyminorunion);
   94209       }
   94210       yymx = yypParser->yystack[yypParser->yyidx].major;
   94211       if( yymx==YYERRORSYMBOL || yyerrorhit ){
   94212 #ifndef NDEBUG
   94213         if( yyTraceFILE ){
   94214           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
   94215              yyTracePrompt,yyTokenName[yymajor]);
   94216         }
   94217 #endif
   94218         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
   94219         yymajor = YYNOCODE;
   94220       }else{
   94221          while(
   94222           yypParser->yyidx >= 0 &&
   94223           yymx != YYERRORSYMBOL &&
   94224           (yyact = yy_find_reduce_action(
   94225                         yypParser->yystack[yypParser->yyidx].stateno,
   94226                         YYERRORSYMBOL)) >= YYNSTATE
   94227         ){
   94228           yy_pop_parser_stack(yypParser);
   94229         }
   94230         if( yypParser->yyidx < 0 || yymajor==0 ){
   94231           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   94232           yy_parse_failed(yypParser);
   94233           yymajor = YYNOCODE;
   94234         }else if( yymx!=YYERRORSYMBOL ){
   94235           YYMINORTYPE u2;
   94236           u2.YYERRSYMDT = 0;
   94237           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
   94238         }
   94239       }
   94240       yypParser->yyerrcnt = 3;
   94241       yyerrorhit = 1;
   94242 #elif defined(YYNOERRORRECOVERY)
   94243       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
   94244       ** do any kind of error recovery.  Instead, simply invoke the syntax
   94245       ** error routine and continue going as if nothing had happened.
   94246       **
   94247       ** Applications can set this macro (for example inside %include) if
   94248       ** they intend to abandon the parse upon the first syntax error seen.
   94249       */
   94250       yy_syntax_error(yypParser,yymajor,yyminorunion);
   94251       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   94252       yymajor = YYNOCODE;
   94253 
   94254 #else  /* YYERRORSYMBOL is not defined */
   94255       /* This is what we do if the grammar does not define ERROR:
   94256       **
   94257       **  * Report an error message, and throw away the input token.
   94258       **
   94259       **  * If the input token is $, then fail the parse.
   94260       **
   94261       ** As before, subsequent error messages are suppressed until
   94262       ** three input tokens have been successfully shifted.
   94263       */
   94264       if( yypParser->yyerrcnt<=0 ){
   94265         yy_syntax_error(yypParser,yymajor,yyminorunion);
   94266       }
   94267       yypParser->yyerrcnt = 3;
   94268       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   94269       if( yyendofinput ){
   94270         yy_parse_failed(yypParser);
   94271       }
   94272       yymajor = YYNOCODE;
   94273 #endif
   94274     }
   94275   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
   94276   return;
   94277 }
   94278 
   94279 /************** End of parse.c ***********************************************/
   94280 /************** Begin file tokenize.c ****************************************/
   94281 /*
   94282 ** 2001 September 15
   94283 **
   94284 ** The author disclaims copyright to this source code.  In place of
   94285 ** a legal notice, here is a blessing:
   94286 **
   94287 **    May you do good and not evil.
   94288 **    May you find forgiveness for yourself and forgive others.
   94289 **    May you share freely, never taking more than you give.
   94290 **
   94291 *************************************************************************
   94292 ** An tokenizer for SQL
   94293 **
   94294 ** This file contains C code that splits an SQL input string up into
   94295 ** individual tokens and sends those tokens one-by-one over to the
   94296 ** parser for analysis.
   94297 */
   94298 
   94299 /*
   94300 ** The charMap() macro maps alphabetic characters into their
   94301 ** lower-case ASCII equivalent.  On ASCII machines, this is just
   94302 ** an upper-to-lower case map.  On EBCDIC machines we also need
   94303 ** to adjust the encoding.  Only alphabetic characters and underscores
   94304 ** need to be translated.
   94305 */
   94306 #ifdef SQLITE_ASCII
   94307 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
   94308 #endif
   94309 #ifdef SQLITE_EBCDIC
   94310 # define charMap(X) ebcdicToAscii[(unsigned char)X]
   94311 const unsigned char ebcdicToAscii[] = {
   94312 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
   94313    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
   94314    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
   94315    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
   94316    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
   94317    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
   94318    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
   94319    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
   94320    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
   94321    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
   94322    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
   94323    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
   94324    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
   94325    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
   94326    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
   94327    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
   94328    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
   94329 };
   94330 #endif
   94331 
   94332 /*
   94333 ** The sqlite3KeywordCode function looks up an identifier to determine if
   94334 ** it is a keyword.  If it is a keyword, the token code of that keyword is
   94335 ** returned.  If the input is not a keyword, TK_ID is returned.
   94336 **
   94337 ** The implementation of this routine was generated by a program,
   94338 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
   94339 ** The output of the mkkeywordhash.c program is written into a file
   94340 ** named keywordhash.h and then included into this source file by
   94341 ** the #include below.
   94342 */
   94343 /************** Include keywordhash.h in the middle of tokenize.c ************/
   94344 /************** Begin file keywordhash.h *************************************/
   94345 /***** This file contains automatically generated code ******
   94346 **
   94347 ** The code in this file has been automatically generated by
   94348 **
   94349 **   sqlite/tool/mkkeywordhash.c
   94350 **
   94351 ** The code in this file implements a function that determines whether
   94352 ** or not a given identifier is really an SQL keyword.  The same thing
   94353 ** might be implemented more directly using a hand-written hash table.
   94354 ** But by using this automatically generated code, the size of the code
   94355 ** is substantially reduced.  This is important for embedded applications
   94356 ** on platforms with limited memory.
   94357 */
   94358 /* Hash score: 175 */
   94359 static int keywordCode(const char *z, int n){
   94360   /* zText[] encodes 811 bytes of keywords in 541 bytes */
   94361   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
   94362   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
   94363   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
   94364   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
   94365   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
   94366   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
   94367   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
   94368   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
   94369   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
   94370   /*   INITIALLY                                                          */
   94371   static const char zText[540] = {
   94372     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
   94373     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
   94374     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
   94375     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
   94376     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
   94377     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
   94378     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
   94379     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
   94380     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
   94381     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
   94382     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
   94383     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
   94384     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
   94385     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
   94386     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
   94387     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
   94388     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
   94389     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
   94390     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
   94391     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
   94392     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
   94393     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
   94394     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
   94395     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
   94396     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
   94397     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
   94398     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
   94399     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
   94400     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
   94401     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
   94402   };
   94403   static const unsigned char aHash[127] = {
   94404       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
   94405       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
   94406      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
   94407        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
   94408        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
   94409       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
   94410       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
   94411       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
   94412       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
   94413       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
   94414   };
   94415   static const unsigned char aNext[121] = {
   94416        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
   94417        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
   94418        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
   94419        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
   94420        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
   94421       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
   94422       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
   94423        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
   94424      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
   94425       35,  64,   0,   0,
   94426   };
   94427   static const unsigned char aLen[121] = {
   94428        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
   94429        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
   94430       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
   94431        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
   94432        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
   94433        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
   94434        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
   94435        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
   94436        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
   94437        6,   4,   9,   3,
   94438   };
   94439   static const unsigned short int aOffset[121] = {
   94440        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
   94441       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
   94442       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
   94443      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
   94444      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
   94445      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
   94446      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
   94447      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
   94448      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
   94449      521, 527, 531, 536,
   94450   };
   94451   static const unsigned char aCode[121] = {
   94452     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
   94453     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
   94454     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
   94455     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
   94456     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
   94457     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
   94458     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
   94459     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
   94460     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
   94461     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
   94462     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
   94463     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
   94464     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
   94465     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
   94466     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
   94467     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
   94468     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
   94469     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
   94470     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
   94471     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
   94472     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
   94473     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
   94474     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
   94475     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
   94476     TK_ALL,
   94477   };
   94478   int h, i;
   94479   if( n<2 ) return TK_ID;
   94480   h = ((charMap(z[0])*4) ^
   94481       (charMap(z[n-1])*3) ^
   94482       n) % 127;
   94483   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
   94484     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
   94485       testcase( i==0 ); /* REINDEX */
   94486       testcase( i==1 ); /* INDEXED */
   94487       testcase( i==2 ); /* INDEX */
   94488       testcase( i==3 ); /* DESC */
   94489       testcase( i==4 ); /* ESCAPE */
   94490       testcase( i==5 ); /* EACH */
   94491       testcase( i==6 ); /* CHECK */
   94492       testcase( i==7 ); /* KEY */
   94493       testcase( i==8 ); /* BEFORE */
   94494       testcase( i==9 ); /* FOREIGN */
   94495       testcase( i==10 ); /* FOR */
   94496       testcase( i==11 ); /* IGNORE */
   94497       testcase( i==12 ); /* REGEXP */
   94498       testcase( i==13 ); /* EXPLAIN */
   94499       testcase( i==14 ); /* INSTEAD */
   94500       testcase( i==15 ); /* ADD */
   94501       testcase( i==16 ); /* DATABASE */
   94502       testcase( i==17 ); /* AS */
   94503       testcase( i==18 ); /* SELECT */
   94504       testcase( i==19 ); /* TABLE */
   94505       testcase( i==20 ); /* LEFT */
   94506       testcase( i==21 ); /* THEN */
   94507       testcase( i==22 ); /* END */
   94508       testcase( i==23 ); /* DEFERRABLE */
   94509       testcase( i==24 ); /* ELSE */
   94510       testcase( i==25 ); /* EXCEPT */
   94511       testcase( i==26 ); /* TRANSACTION */
   94512       testcase( i==27 ); /* ACTION */
   94513       testcase( i==28 ); /* ON */
   94514       testcase( i==29 ); /* NATURAL */
   94515       testcase( i==30 ); /* ALTER */
   94516       testcase( i==31 ); /* RAISE */
   94517       testcase( i==32 ); /* EXCLUSIVE */
   94518       testcase( i==33 ); /* EXISTS */
   94519       testcase( i==34 ); /* SAVEPOINT */
   94520       testcase( i==35 ); /* INTERSECT */
   94521       testcase( i==36 ); /* TRIGGER */
   94522       testcase( i==37 ); /* REFERENCES */
   94523       testcase( i==38 ); /* CONSTRAINT */
   94524       testcase( i==39 ); /* INTO */
   94525       testcase( i==40 ); /* OFFSET */
   94526       testcase( i==41 ); /* OF */
   94527       testcase( i==42 ); /* SET */
   94528       testcase( i==43 ); /* TEMPORARY */
   94529       testcase( i==44 ); /* TEMP */
   94530       testcase( i==45 ); /* OR */
   94531       testcase( i==46 ); /* UNIQUE */
   94532       testcase( i==47 ); /* QUERY */
   94533       testcase( i==48 ); /* ATTACH */
   94534       testcase( i==49 ); /* HAVING */
   94535       testcase( i==50 ); /* GROUP */
   94536       testcase( i==51 ); /* UPDATE */
   94537       testcase( i==52 ); /* BEGIN */
   94538       testcase( i==53 ); /* INNER */
   94539       testcase( i==54 ); /* RELEASE */
   94540       testcase( i==55 ); /* BETWEEN */
   94541       testcase( i==56 ); /* NOTNULL */
   94542       testcase( i==57 ); /* NOT */
   94543       testcase( i==58 ); /* NO */
   94544       testcase( i==59 ); /* NULL */
   94545       testcase( i==60 ); /* LIKE */
   94546       testcase( i==61 ); /* CASCADE */
   94547       testcase( i==62 ); /* ASC */
   94548       testcase( i==63 ); /* DELETE */
   94549       testcase( i==64 ); /* CASE */
   94550       testcase( i==65 ); /* COLLATE */
   94551       testcase( i==66 ); /* CREATE */
   94552       testcase( i==67 ); /* CURRENT_DATE */
   94553       testcase( i==68 ); /* DETACH */
   94554       testcase( i==69 ); /* IMMEDIATE */
   94555       testcase( i==70 ); /* JOIN */
   94556       testcase( i==71 ); /* INSERT */
   94557       testcase( i==72 ); /* MATCH */
   94558       testcase( i==73 ); /* PLAN */
   94559       testcase( i==74 ); /* ANALYZE */
   94560       testcase( i==75 ); /* PRAGMA */
   94561       testcase( i==76 ); /* ABORT */
   94562       testcase( i==77 ); /* VALUES */
   94563       testcase( i==78 ); /* VIRTUAL */
   94564       testcase( i==79 ); /* LIMIT */
   94565       testcase( i==80 ); /* WHEN */
   94566       testcase( i==81 ); /* WHERE */
   94567       testcase( i==82 ); /* RENAME */
   94568       testcase( i==83 ); /* AFTER */
   94569       testcase( i==84 ); /* REPLACE */
   94570       testcase( i==85 ); /* AND */
   94571       testcase( i==86 ); /* DEFAULT */
   94572       testcase( i==87 ); /* AUTOINCREMENT */
   94573       testcase( i==88 ); /* TO */
   94574       testcase( i==89 ); /* IN */
   94575       testcase( i==90 ); /* CAST */
   94576       testcase( i==91 ); /* COLUMN */
   94577       testcase( i==92 ); /* COMMIT */
   94578       testcase( i==93 ); /* CONFLICT */
   94579       testcase( i==94 ); /* CROSS */
   94580       testcase( i==95 ); /* CURRENT_TIMESTAMP */
   94581       testcase( i==96 ); /* CURRENT_TIME */
   94582       testcase( i==97 ); /* PRIMARY */
   94583       testcase( i==98 ); /* DEFERRED */
   94584       testcase( i==99 ); /* DISTINCT */
   94585       testcase( i==100 ); /* IS */
   94586       testcase( i==101 ); /* DROP */
   94587       testcase( i==102 ); /* FAIL */
   94588       testcase( i==103 ); /* FROM */
   94589       testcase( i==104 ); /* FULL */
   94590       testcase( i==105 ); /* GLOB */
   94591       testcase( i==106 ); /* BY */
   94592       testcase( i==107 ); /* IF */
   94593       testcase( i==108 ); /* ISNULL */
   94594       testcase( i==109 ); /* ORDER */
   94595       testcase( i==110 ); /* RESTRICT */
   94596       testcase( i==111 ); /* OUTER */
   94597       testcase( i==112 ); /* RIGHT */
   94598       testcase( i==113 ); /* ROLLBACK */
   94599       testcase( i==114 ); /* ROW */
   94600       testcase( i==115 ); /* UNION */
   94601       testcase( i==116 ); /* USING */
   94602       testcase( i==117 ); /* VACUUM */
   94603       testcase( i==118 ); /* VIEW */
   94604       testcase( i==119 ); /* INITIALLY */
   94605       testcase( i==120 ); /* ALL */
   94606       return aCode[i];
   94607     }
   94608   }
   94609   return TK_ID;
   94610 }
   94611 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
   94612   return keywordCode((char*)z, n);
   94613 }
   94614 #define SQLITE_N_KEYWORD 121
   94615 
   94616 /************** End of keywordhash.h *****************************************/
   94617 /************** Continuing where we left off in tokenize.c *******************/
   94618 
   94619 
   94620 /*
   94621 ** If X is a character that can be used in an identifier then
   94622 ** IdChar(X) will be true.  Otherwise it is false.
   94623 **
   94624 ** For ASCII, any character with the high-order bit set is
   94625 ** allowed in an identifier.  For 7-bit characters,
   94626 ** sqlite3IsIdChar[X] must be 1.
   94627 **
   94628 ** For EBCDIC, the rules are more complex but have the same
   94629 ** end result.
   94630 **
   94631 ** Ticket #1066.  the SQL standard does not allow '$' in the
   94632 ** middle of identfiers.  But many SQL implementations do.
   94633 ** SQLite will allow '$' in identifiers for compatibility.
   94634 ** But the feature is undocumented.
   94635 */
   94636 #ifdef SQLITE_ASCII
   94637 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
   94638 #endif
   94639 #ifdef SQLITE_EBCDIC
   94640 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
   94641 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
   94642     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
   94643     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
   94644     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
   94645     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
   94646     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
   94647     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
   94648     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
   94649     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
   94650     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
   94651     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
   94652     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
   94653     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
   94654 };
   94655 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
   94656 #endif
   94657 
   94658 
   94659 /*
   94660 ** Return the length of the token that begins at z[0].
   94661 ** Store the token type in *tokenType before returning.
   94662 */
   94663 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
   94664   int i, c;
   94665   switch( *z ){
   94666     case ' ': case '\t': case '\n': case '\f': case '\r': {
   94667       testcase( z[0]==' ' );
   94668       testcase( z[0]=='\t' );
   94669       testcase( z[0]=='\n' );
   94670       testcase( z[0]=='\f' );
   94671       testcase( z[0]=='\r' );
   94672       for(i=1; sqlite3Isspace(z[i]); i++){}
   94673       *tokenType = TK_SPACE;
   94674       return i;
   94675     }
   94676     case '-': {
   94677       if( z[1]=='-' ){
   94678         /* IMP: R-15891-05542 -- syntax diagram for comments */
   94679         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
   94680         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
   94681         return i;
   94682       }
   94683       *tokenType = TK_MINUS;
   94684       return 1;
   94685     }
   94686     case '(': {
   94687       *tokenType = TK_LP;
   94688       return 1;
   94689     }
   94690     case ')': {
   94691       *tokenType = TK_RP;
   94692       return 1;
   94693     }
   94694     case ';': {
   94695       *tokenType = TK_SEMI;
   94696       return 1;
   94697     }
   94698     case '+': {
   94699       *tokenType = TK_PLUS;
   94700       return 1;
   94701     }
   94702     case '*': {
   94703       *tokenType = TK_STAR;
   94704       return 1;
   94705     }
   94706     case '/': {
   94707       if( z[1]!='*' || z[2]==0 ){
   94708         *tokenType = TK_SLASH;
   94709         return 1;
   94710       }
   94711       /* IMP: R-15891-05542 -- syntax diagram for comments */
   94712       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
   94713       if( c ) i++;
   94714       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
   94715       return i;
   94716     }
   94717     case '%': {
   94718       *tokenType = TK_REM;
   94719       return 1;
   94720     }
   94721     case '=': {
   94722       *tokenType = TK_EQ;
   94723       return 1 + (z[1]=='=');
   94724     }
   94725     case '<': {
   94726       if( (c=z[1])=='=' ){
   94727         *tokenType = TK_LE;
   94728         return 2;
   94729       }else if( c=='>' ){
   94730         *tokenType = TK_NE;
   94731         return 2;
   94732       }else if( c=='<' ){
   94733         *tokenType = TK_LSHIFT;
   94734         return 2;
   94735       }else{
   94736         *tokenType = TK_LT;
   94737         return 1;
   94738       }
   94739     }
   94740     case '>': {
   94741       if( (c=z[1])=='=' ){
   94742         *tokenType = TK_GE;
   94743         return 2;
   94744       }else if( c=='>' ){
   94745         *tokenType = TK_RSHIFT;
   94746         return 2;
   94747       }else{
   94748         *tokenType = TK_GT;
   94749         return 1;
   94750       }
   94751     }
   94752     case '!': {
   94753       if( z[1]!='=' ){
   94754         *tokenType = TK_ILLEGAL;
   94755         return 2;
   94756       }else{
   94757         *tokenType = TK_NE;
   94758         return 2;
   94759       }
   94760     }
   94761     case '|': {
   94762       if( z[1]!='|' ){
   94763         *tokenType = TK_BITOR;
   94764         return 1;
   94765       }else{
   94766         *tokenType = TK_CONCAT;
   94767         return 2;
   94768       }
   94769     }
   94770     case ',': {
   94771       *tokenType = TK_COMMA;
   94772       return 1;
   94773     }
   94774     case '&': {
   94775       *tokenType = TK_BITAND;
   94776       return 1;
   94777     }
   94778     case '~': {
   94779       *tokenType = TK_BITNOT;
   94780       return 1;
   94781     }
   94782     case '`':
   94783     case '\'':
   94784     case '"': {
   94785       int delim = z[0];
   94786       testcase( delim=='`' );
   94787       testcase( delim=='\'' );
   94788       testcase( delim=='"' );
   94789       for(i=1; (c=z[i])!=0; i++){
   94790         if( c==delim ){
   94791           if( z[i+1]==delim ){
   94792             i++;
   94793           }else{
   94794             break;
   94795           }
   94796         }
   94797       }
   94798       if( c=='\'' ){
   94799         *tokenType = TK_STRING;
   94800         return i+1;
   94801       }else if( c!=0 ){
   94802         *tokenType = TK_ID;
   94803         return i+1;
   94804       }else{
   94805         *tokenType = TK_ILLEGAL;
   94806         return i;
   94807       }
   94808     }
   94809     case '.': {
   94810 #ifndef SQLITE_OMIT_FLOATING_POINT
   94811       if( !sqlite3Isdigit(z[1]) )
   94812 #endif
   94813       {
   94814         *tokenType = TK_DOT;
   94815         return 1;
   94816       }
   94817       /* If the next character is a digit, this is a floating point
   94818       ** number that begins with ".".  Fall thru into the next case */
   94819     }
   94820     case '0': case '1': case '2': case '3': case '4':
   94821     case '5': case '6': case '7': case '8': case '9': {
   94822       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
   94823       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
   94824       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
   94825       testcase( z[0]=='9' );
   94826       *tokenType = TK_INTEGER;
   94827       for(i=0; sqlite3Isdigit(z[i]); i++){}
   94828 #ifndef SQLITE_OMIT_FLOATING_POINT
   94829       if( z[i]=='.' ){
   94830         i++;
   94831         while( sqlite3Isdigit(z[i]) ){ i++; }
   94832         *tokenType = TK_FLOAT;
   94833       }
   94834       if( (z[i]=='e' || z[i]=='E') &&
   94835            ( sqlite3Isdigit(z[i+1])
   94836             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
   94837            )
   94838       ){
   94839         i += 2;
   94840         while( sqlite3Isdigit(z[i]) ){ i++; }
   94841         *tokenType = TK_FLOAT;
   94842       }
   94843 #endif
   94844       while( IdChar(z[i]) ){
   94845         *tokenType = TK_ILLEGAL;
   94846         i++;
   94847       }
   94848       return i;
   94849     }
   94850     case '[': {
   94851       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
   94852       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
   94853       return i;
   94854     }
   94855     case '?': {
   94856       *tokenType = TK_VARIABLE;
   94857       for(i=1; sqlite3Isdigit(z[i]); i++){}
   94858       return i;
   94859     }
   94860     case '#': {
   94861       for(i=1; sqlite3Isdigit(z[i]); i++){}
   94862       if( i>1 ){
   94863         /* Parameters of the form #NNN (where NNN is a number) are used
   94864         ** internally by sqlite3NestedParse.  */
   94865         *tokenType = TK_REGISTER;
   94866         return i;
   94867       }
   94868       /* Fall through into the next case if the '#' is not followed by
   94869       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
   94870     }
   94871 #ifndef SQLITE_OMIT_TCL_VARIABLE
   94872     case '$':
   94873 #endif
   94874     case '@':  /* For compatibility with MS SQL Server */
   94875     case ':': {
   94876       int n = 0;
   94877       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
   94878       *tokenType = TK_VARIABLE;
   94879       for(i=1; (c=z[i])!=0; i++){
   94880         if( IdChar(c) ){
   94881           n++;
   94882 #ifndef SQLITE_OMIT_TCL_VARIABLE
   94883         }else if( c=='(' && n>0 ){
   94884           do{
   94885             i++;
   94886           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
   94887           if( c==')' ){
   94888             i++;
   94889           }else{
   94890             *tokenType = TK_ILLEGAL;
   94891           }
   94892           break;
   94893         }else if( c==':' && z[i+1]==':' ){
   94894           i++;
   94895 #endif
   94896         }else{
   94897           break;
   94898         }
   94899       }
   94900       if( n==0 ) *tokenType = TK_ILLEGAL;
   94901       return i;
   94902     }
   94903 #ifndef SQLITE_OMIT_BLOB_LITERAL
   94904     case 'x': case 'X': {
   94905       testcase( z[0]=='x' ); testcase( z[0]=='X' );
   94906       if( z[1]=='\'' ){
   94907         *tokenType = TK_BLOB;
   94908         for(i=2; (c=z[i])!=0 && c!='\''; i++){
   94909           if( !sqlite3Isxdigit(c) ){
   94910             *tokenType = TK_ILLEGAL;
   94911           }
   94912         }
   94913         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
   94914         if( c ) i++;
   94915         return i;
   94916       }
   94917       /* Otherwise fall through to the next case */
   94918     }
   94919 #endif
   94920     default: {
   94921       if( !IdChar(*z) ){
   94922         break;
   94923       }
   94924       for(i=1; IdChar(z[i]); i++){}
   94925       *tokenType = keywordCode((char*)z, i);
   94926       return i;
   94927     }
   94928   }
   94929   *tokenType = TK_ILLEGAL;
   94930   return 1;
   94931 }
   94932 
   94933 /*
   94934 ** Run the parser on the given SQL string.  The parser structure is
   94935 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
   94936 ** then an and attempt is made to write an error message into
   94937 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
   94938 ** error message.
   94939 */
   94940 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
   94941   int nErr = 0;                   /* Number of errors encountered */
   94942   int i;                          /* Loop counter */
   94943   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
   94944   int tokenType;                  /* type of the next token */
   94945   int lastTokenParsed = -1;       /* type of the previous token */
   94946   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
   94947   sqlite3 *db = pParse->db;       /* The database connection */
   94948   int mxSqlLen;                   /* Max length of an SQL string */
   94949 
   94950 
   94951   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
   94952   if( db->activeVdbeCnt==0 ){
   94953     db->u1.isInterrupted = 0;
   94954   }
   94955   pParse->rc = SQLITE_OK;
   94956   pParse->zTail = zSql;
   94957   i = 0;
   94958   assert( pzErrMsg!=0 );
   94959   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
   94960   if( pEngine==0 ){
   94961     db->mallocFailed = 1;
   94962     return SQLITE_NOMEM;
   94963   }
   94964   assert( pParse->pNewTable==0 );
   94965   assert( pParse->pNewTrigger==0 );
   94966   assert( pParse->nVar==0 );
   94967   assert( pParse->nVarExpr==0 );
   94968   assert( pParse->nVarExprAlloc==0 );
   94969   assert( pParse->apVarExpr==0 );
   94970   enableLookaside = db->lookaside.bEnabled;
   94971   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
   94972   while( !db->mallocFailed && zSql[i]!=0 ){
   94973     assert( i>=0 );
   94974     pParse->sLastToken.z = &zSql[i];
   94975     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
   94976     i += pParse->sLastToken.n;
   94977     if( i>mxSqlLen ){
   94978       pParse->rc = SQLITE_TOOBIG;
   94979       break;
   94980     }
   94981     switch( tokenType ){
   94982       case TK_SPACE: {
   94983         if( db->u1.isInterrupted ){
   94984           sqlite3ErrorMsg(pParse, "interrupt");
   94985           pParse->rc = SQLITE_INTERRUPT;
   94986           goto abort_parse;
   94987         }
   94988         break;
   94989       }
   94990       case TK_ILLEGAL: {
   94991         sqlite3DbFree(db, *pzErrMsg);
   94992         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
   94993                         &pParse->sLastToken);
   94994         nErr++;
   94995         goto abort_parse;
   94996       }
   94997       case TK_SEMI: {
   94998         pParse->zTail = &zSql[i];
   94999         /* Fall thru into the default case */
   95000       }
   95001       default: {
   95002         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
   95003         lastTokenParsed = tokenType;
   95004         if( pParse->rc!=SQLITE_OK ){
   95005           goto abort_parse;
   95006         }
   95007         break;
   95008       }
   95009     }
   95010   }
   95011 abort_parse:
   95012   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
   95013     if( lastTokenParsed!=TK_SEMI ){
   95014       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
   95015       pParse->zTail = &zSql[i];
   95016     }
   95017     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
   95018   }
   95019 #ifdef YYTRACKMAXSTACKDEPTH
   95020   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
   95021       sqlite3ParserStackPeak(pEngine)
   95022   );
   95023 #endif /* YYDEBUG */
   95024   sqlite3ParserFree(pEngine, sqlite3_free);
   95025   db->lookaside.bEnabled = enableLookaside;
   95026   if( db->mallocFailed ){
   95027     pParse->rc = SQLITE_NOMEM;
   95028   }
   95029   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
   95030     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
   95031   }
   95032   assert( pzErrMsg!=0 );
   95033   if( pParse->zErrMsg ){
   95034     *pzErrMsg = pParse->zErrMsg;
   95035     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
   95036     pParse->zErrMsg = 0;
   95037     nErr++;
   95038   }
   95039   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
   95040     sqlite3VdbeDelete(pParse->pVdbe);
   95041     pParse->pVdbe = 0;
   95042   }
   95043 #ifndef SQLITE_OMIT_SHARED_CACHE
   95044   if( pParse->nested==0 ){
   95045     sqlite3DbFree(db, pParse->aTableLock);
   95046     pParse->aTableLock = 0;
   95047     pParse->nTableLock = 0;
   95048   }
   95049 #endif
   95050 #ifndef SQLITE_OMIT_VIRTUALTABLE
   95051   sqlite3DbFree(db, pParse->apVtabLock);
   95052 #endif
   95053 
   95054   if( !IN_DECLARE_VTAB ){
   95055     /* If the pParse->declareVtab flag is set, do not delete any table
   95056     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
   95057     ** will take responsibility for freeing the Table structure.
   95058     */
   95059     sqlite3DeleteTable(pParse->pNewTable);
   95060   }
   95061 
   95062   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
   95063   sqlite3DbFree(db, pParse->apVarExpr);
   95064   sqlite3DbFree(db, pParse->aAlias);
   95065   while( pParse->pAinc ){
   95066     AutoincInfo *p = pParse->pAinc;
   95067     pParse->pAinc = p->pNext;
   95068     sqlite3DbFree(db, p);
   95069   }
   95070   while( pParse->pZombieTab ){
   95071     Table *p = pParse->pZombieTab;
   95072     pParse->pZombieTab = p->pNextZombie;
   95073     sqlite3DeleteTable(p);
   95074   }
   95075   if( nErr>0 && pParse->rc==SQLITE_OK ){
   95076     pParse->rc = SQLITE_ERROR;
   95077   }
   95078   return nErr;
   95079 }
   95080 
   95081 /************** End of tokenize.c ********************************************/
   95082 /************** Begin file complete.c ****************************************/
   95083 /*
   95084 ** 2001 September 15
   95085 **
   95086 ** The author disclaims copyright to this source code.  In place of
   95087 ** a legal notice, here is a blessing:
   95088 **
   95089 **    May you do good and not evil.
   95090 **    May you find forgiveness for yourself and forgive others.
   95091 **    May you share freely, never taking more than you give.
   95092 **
   95093 *************************************************************************
   95094 ** An tokenizer for SQL
   95095 **
   95096 ** This file contains C code that implements the sqlite3_complete() API.
   95097 ** This code used to be part of the tokenizer.c source file.  But by
   95098 ** separating it out, the code will be automatically omitted from
   95099 ** static links that do not use it.
   95100 */
   95101 #ifndef SQLITE_OMIT_COMPLETE
   95102 
   95103 /*
   95104 ** This is defined in tokenize.c.  We just have to import the definition.
   95105 */
   95106 #ifndef SQLITE_AMALGAMATION
   95107 #ifdef SQLITE_ASCII
   95108 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
   95109 #endif
   95110 #ifdef SQLITE_EBCDIC
   95111 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
   95112 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
   95113 #endif
   95114 #endif /* SQLITE_AMALGAMATION */
   95115 
   95116 
   95117 /*
   95118 ** Token types used by the sqlite3_complete() routine.  See the header
   95119 ** comments on that procedure for additional information.
   95120 */
   95121 #define tkSEMI    0
   95122 #define tkWS      1
   95123 #define tkOTHER   2
   95124 #ifndef SQLITE_OMIT_TRIGGER
   95125 #define tkEXPLAIN 3
   95126 #define tkCREATE  4
   95127 #define tkTEMP    5
   95128 #define tkTRIGGER 6
   95129 #define tkEND     7
   95130 #endif
   95131 
   95132 /*
   95133 ** Return TRUE if the given SQL string ends in a semicolon.
   95134 **
   95135 ** Special handling is require for CREATE TRIGGER statements.
   95136 ** Whenever the CREATE TRIGGER keywords are seen, the statement
   95137 ** must end with ";END;".
   95138 **
   95139 ** This implementation uses a state machine with 8 states:
   95140 **
   95141 **   (0) INVALID   We have not yet seen a non-whitespace character.
   95142 **
   95143 **   (1) START     At the beginning or end of an SQL statement.  This routine
   95144 **                 returns 1 if it ends in the START state and 0 if it ends
   95145 **                 in any other state.
   95146 **
   95147 **   (2) NORMAL    We are in the middle of statement which ends with a single
   95148 **                 semicolon.
   95149 **
   95150 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
   95151 **                 a statement.
   95152 **
   95153 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
   95154 **                 statement, possibly preceeded by EXPLAIN and/or followed by
   95155 **                 TEMP or TEMPORARY
   95156 **
   95157 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
   95158 **                 ended by a semicolon, the keyword END, and another semicolon.
   95159 **
   95160 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
   95161 **                 the end of a trigger definition.
   95162 **
   95163 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
   95164 **                 of a trigger difinition.
   95165 **
   95166 ** Transitions between states above are determined by tokens extracted
   95167 ** from the input.  The following tokens are significant:
   95168 **
   95169 **   (0) tkSEMI      A semicolon.
   95170 **   (1) tkWS        Whitespace.
   95171 **   (2) tkOTHER     Any other SQL token.
   95172 **   (3) tkEXPLAIN   The "explain" keyword.
   95173 **   (4) tkCREATE    The "create" keyword.
   95174 **   (5) tkTEMP      The "temp" or "temporary" keyword.
   95175 **   (6) tkTRIGGER   The "trigger" keyword.
   95176 **   (7) tkEND       The "end" keyword.
   95177 **
   95178 ** Whitespace never causes a state transition and is always ignored.
   95179 ** This means that a SQL string of all whitespace is invalid.
   95180 **
   95181 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
   95182 ** to recognize the end of a trigger can be omitted.  All we have to do
   95183 ** is look for a semicolon that is not part of an string or comment.
   95184 */
   95185 SQLITE_API int sqlite3_complete(const char *zSql){
   95186   u8 state = 0;   /* Current state, using numbers defined in header comment */
   95187   u8 token;       /* Value of the next token */
   95188 
   95189 #ifndef SQLITE_OMIT_TRIGGER
   95190   /* A complex statement machine used to detect the end of a CREATE TRIGGER
   95191   ** statement.  This is the normal case.
   95192   */
   95193   static const u8 trans[8][8] = {
   95194                      /* Token:                                                */
   95195      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
   95196      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
   95197      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
   95198      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
   95199      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
   95200      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
   95201      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
   95202      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
   95203      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
   95204   };
   95205 #else
   95206   /* If triggers are not supported by this compile then the statement machine
   95207   ** used to detect the end of a statement is much simplier
   95208   */
   95209   static const u8 trans[3][3] = {
   95210                      /* Token:           */
   95211      /* State:       **  SEMI  WS  OTHER */
   95212      /* 0 INVALID: */ {    1,  0,     2, },
   95213      /* 1   START: */ {    1,  1,     2, },
   95214      /* 2  NORMAL: */ {    1,  2,     2, },
   95215   };
   95216 #endif /* SQLITE_OMIT_TRIGGER */
   95217 
   95218   while( *zSql ){
   95219     switch( *zSql ){
   95220       case ';': {  /* A semicolon */
   95221         token = tkSEMI;
   95222         break;
   95223       }
   95224       case ' ':
   95225       case '\r':
   95226       case '\t':
   95227       case '\n':
   95228       case '\f': {  /* White space is ignored */
   95229         token = tkWS;
   95230         break;
   95231       }
   95232       case '/': {   /* C-style comments */
   95233         if( zSql[1]!='*' ){
   95234           token = tkOTHER;
   95235           break;
   95236         }
   95237         zSql += 2;
   95238         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
   95239         if( zSql[0]==0 ) return 0;
   95240         zSql++;
   95241         token = tkWS;
   95242         break;
   95243       }
   95244       case '-': {   /* SQL-style comments from "--" to end of line */
   95245         if( zSql[1]!='-' ){
   95246           token = tkOTHER;
   95247           break;
   95248         }
   95249         while( *zSql && *zSql!='\n' ){ zSql++; }
   95250         if( *zSql==0 ) return state==1;
   95251         token = tkWS;
   95252         break;
   95253       }
   95254       case '[': {   /* Microsoft-style identifiers in [...] */
   95255         zSql++;
   95256         while( *zSql && *zSql!=']' ){ zSql++; }
   95257         if( *zSql==0 ) return 0;
   95258         token = tkOTHER;
   95259         break;
   95260       }
   95261       case '`':     /* Grave-accent quoted symbols used by MySQL */
   95262       case '"':     /* single- and double-quoted strings */
   95263       case '\'': {
   95264         int c = *zSql;
   95265         zSql++;
   95266         while( *zSql && *zSql!=c ){ zSql++; }
   95267         if( *zSql==0 ) return 0;
   95268         token = tkOTHER;
   95269         break;
   95270       }
   95271       default: {
   95272 #ifdef SQLITE_EBCDIC
   95273         unsigned char c;
   95274 #endif
   95275         if( IdChar((u8)*zSql) ){
   95276           /* Keywords and unquoted identifiers */
   95277           int nId;
   95278           for(nId=1; IdChar(zSql[nId]); nId++){}
   95279 #ifdef SQLITE_OMIT_TRIGGER
   95280           token = tkOTHER;
   95281 #else
   95282           switch( *zSql ){
   95283             case 'c': case 'C': {
   95284               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
   95285                 token = tkCREATE;
   95286               }else{
   95287                 token = tkOTHER;
   95288               }
   95289               break;
   95290             }
   95291             case 't': case 'T': {
   95292               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
   95293                 token = tkTRIGGER;
   95294               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
   95295                 token = tkTEMP;
   95296               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
   95297                 token = tkTEMP;
   95298               }else{
   95299                 token = tkOTHER;
   95300               }
   95301               break;
   95302             }
   95303             case 'e':  case 'E': {
   95304               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
   95305                 token = tkEND;
   95306               }else
   95307 #ifndef SQLITE_OMIT_EXPLAIN
   95308               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
   95309                 token = tkEXPLAIN;
   95310               }else
   95311 #endif
   95312               {
   95313                 token = tkOTHER;
   95314               }
   95315               break;
   95316             }
   95317             default: {
   95318               token = tkOTHER;
   95319               break;
   95320             }
   95321           }
   95322 #endif /* SQLITE_OMIT_TRIGGER */
   95323           zSql += nId-1;
   95324         }else{
   95325           /* Operators and special symbols */
   95326           token = tkOTHER;
   95327         }
   95328         break;
   95329       }
   95330     }
   95331     state = trans[state][token];
   95332     zSql++;
   95333   }
   95334   return state==1;
   95335 }
   95336 
   95337 #ifndef SQLITE_OMIT_UTF16
   95338 /*
   95339 ** This routine is the same as the sqlite3_complete() routine described
   95340 ** above, except that the parameter is required to be UTF-16 encoded, not
   95341 ** UTF-8.
   95342 */
   95343 SQLITE_API int sqlite3_complete16(const void *zSql){
   95344   sqlite3_value *pVal;
   95345   char const *zSql8;
   95346   int rc = SQLITE_NOMEM;
   95347 
   95348 #ifndef SQLITE_OMIT_AUTOINIT
   95349   rc = sqlite3_initialize();
   95350   if( rc ) return rc;
   95351 #endif
   95352   pVal = sqlite3ValueNew(0);
   95353   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   95354   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   95355   if( zSql8 ){
   95356     rc = sqlite3_complete(zSql8);
   95357   }else{
   95358     rc = SQLITE_NOMEM;
   95359   }
   95360   sqlite3ValueFree(pVal);
   95361   return sqlite3ApiExit(0, rc);
   95362 }
   95363 #endif /* SQLITE_OMIT_UTF16 */
   95364 #endif /* SQLITE_OMIT_COMPLETE */
   95365 
   95366 /************** End of complete.c ********************************************/
   95367 /************** Begin file main.c ********************************************/
   95368 /*
   95369 ** 2001 September 15
   95370 **
   95371 ** The author disclaims copyright to this source code.  In place of
   95372 ** a legal notice, here is a blessing:
   95373 **
   95374 **    May you do good and not evil.
   95375 **    May you find forgiveness for yourself and forgive others.
   95376 **    May you share freely, never taking more than you give.
   95377 **
   95378 *************************************************************************
   95379 ** Main file for the SQLite library.  The routines in this file
   95380 ** implement the programmer interface to the library.  Routines in
   95381 ** other files are for internal use by SQLite and should not be
   95382 ** accessed by users of the library.
   95383 */
   95384 
   95385 #ifdef SQLITE_ENABLE_FTS3
   95386 /************** Include fts3.h in the middle of main.c ***********************/
   95387 /************** Begin file fts3.h ********************************************/
   95388 /*
   95389 ** 2006 Oct 10
   95390 **
   95391 ** The author disclaims copyright to this source code.  In place of
   95392 ** a legal notice, here is a blessing:
   95393 **
   95394 **    May you do good and not evil.
   95395 **    May you find forgiveness for yourself and forgive others.
   95396 **    May you share freely, never taking more than you give.
   95397 **
   95398 ******************************************************************************
   95399 **
   95400 ** This header file is used by programs that want to link against the
   95401 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
   95402 */
   95403 
   95404 #if 0
   95405 extern "C" {
   95406 #endif  /* __cplusplus */
   95407 
   95408 // Begin Android Change
   95409 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db, const char* registerAs);
   95410 // End Android Change
   95411 
   95412 #if 0
   95413 }  /* extern "C" */
   95414 #endif  /* __cplusplus */
   95415 
   95416 /************** End of fts3.h ************************************************/
   95417 /************** Continuing where we left off in main.c ***********************/
   95418 #endif
   95419 #ifdef SQLITE_ENABLE_RTREE
   95420 /************** Include rtree.h in the middle of main.c **********************/
   95421 /************** Begin file rtree.h *******************************************/
   95422 /*
   95423 ** 2008 May 26
   95424 **
   95425 ** The author disclaims copyright to this source code.  In place of
   95426 ** a legal notice, here is a blessing:
   95427 **
   95428 **    May you do good and not evil.
   95429 **    May you find forgiveness for yourself and forgive others.
   95430 **    May you share freely, never taking more than you give.
   95431 **
   95432 ******************************************************************************
   95433 **
   95434 ** This header file is used by programs that want to link against the
   95435 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
   95436 */
   95437 
   95438 #if 0
   95439 extern "C" {
   95440 #endif  /* __cplusplus */
   95441 
   95442 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
   95443 
   95444 #if 0
   95445 }  /* extern "C" */
   95446 #endif  /* __cplusplus */
   95447 
   95448 /************** End of rtree.h ***********************************************/
   95449 /************** Continuing where we left off in main.c ***********************/
   95450 #endif
   95451 #ifdef SQLITE_ENABLE_ICU
   95452 /************** Include sqliteicu.h in the middle of main.c ******************/
   95453 /************** Begin file sqliteicu.h ***************************************/
   95454 /*
   95455 ** 2008 May 26
   95456 **
   95457 ** The author disclaims copyright to this source code.  In place of
   95458 ** a legal notice, here is a blessing:
   95459 **
   95460 **    May you do good and not evil.
   95461 **    May you find forgiveness for yourself and forgive others.
   95462 **    May you share freely, never taking more than you give.
   95463 **
   95464 ******************************************************************************
   95465 **
   95466 ** This header file is used by programs that want to link against the
   95467 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
   95468 */
   95469 
   95470 #if 0
   95471 extern "C" {
   95472 #endif  /* __cplusplus */
   95473 
   95474 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
   95475 
   95476 #if 0
   95477 }  /* extern "C" */
   95478 #endif  /* __cplusplus */
   95479 
   95480 
   95481 /************** End of sqliteicu.h *******************************************/
   95482 /************** Continuing where we left off in main.c ***********************/
   95483 #endif
   95484 
   95485 /*
   95486 ** The version of the library
   95487 */
   95488 #ifndef SQLITE_AMALGAMATION
   95489 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
   95490 #endif
   95491 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
   95492 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
   95493 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
   95494 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
   95495 
   95496 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
   95497 /*
   95498 ** If the following function pointer is not NULL and if
   95499 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
   95500 ** I/O active are written using this function.  These messages
   95501 ** are intended for debugging activity only.
   95502 */
   95503 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
   95504 #endif
   95505 
   95506 /*
   95507 ** If the following global variable points to a string which is the
   95508 ** name of a directory, then that directory will be used to store
   95509 ** temporary files.
   95510 **
   95511 ** See also the "PRAGMA temp_store_directory" SQL command.
   95512 */
   95513 SQLITE_API char *sqlite3_temp_directory = 0;
   95514 
   95515 /*
   95516 ** Initialize SQLite.
   95517 **
   95518 ** This routine must be called to initialize the memory allocation,
   95519 ** VFS, and mutex subsystems prior to doing any serious work with
   95520 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
   95521 ** this routine will be called automatically by key routines such as
   95522 ** sqlite3_open().
   95523 **
   95524 ** This routine is a no-op except on its very first call for the process,
   95525 ** or for the first call after a call to sqlite3_shutdown.
   95526 **
   95527 ** The first thread to call this routine runs the initialization to
   95528 ** completion.  If subsequent threads call this routine before the first
   95529 ** thread has finished the initialization process, then the subsequent
   95530 ** threads must block until the first thread finishes with the initialization.
   95531 **
   95532 ** The first thread might call this routine recursively.  Recursive
   95533 ** calls to this routine should not block, of course.  Otherwise the
   95534 ** initialization process would never complete.
   95535 **
   95536 ** Let X be the first thread to enter this routine.  Let Y be some other
   95537 ** thread.  Then while the initial invocation of this routine by X is
   95538 ** incomplete, it is required that:
   95539 **
   95540 **    *  Calls to this routine from Y must block until the outer-most
   95541 **       call by X completes.
   95542 **
   95543 **    *  Recursive calls to this routine from thread X return immediately
   95544 **       without blocking.
   95545 */
   95546 SQLITE_API int sqlite3_initialize(void){
   95547   sqlite3_mutex *pMaster;                      /* The main static mutex */
   95548   int rc;                                      /* Result code */
   95549 
   95550 #ifdef SQLITE_OMIT_WSD
   95551   rc = sqlite3_wsd_init(4096, 24);
   95552   if( rc!=SQLITE_OK ){
   95553     return rc;
   95554   }
   95555 #endif
   95556 
   95557   /* If SQLite is already completely initialized, then this call
   95558   ** to sqlite3_initialize() should be a no-op.  But the initialization
   95559   ** must be complete.  So isInit must not be set until the very end
   95560   ** of this routine.
   95561   */
   95562   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
   95563 
   95564   /* Make sure the mutex subsystem is initialized.  If unable to
   95565   ** initialize the mutex subsystem, return early with the error.
   95566   ** If the system is so sick that we are unable to allocate a mutex,
   95567   ** there is not much SQLite is going to be able to do.
   95568   **
   95569   ** The mutex subsystem must take care of serializing its own
   95570   ** initialization.
   95571   */
   95572   rc = sqlite3MutexInit();
   95573   if( rc ) return rc;
   95574 
   95575   /* Initialize the malloc() system and the recursive pInitMutex mutex.
   95576   ** This operation is protected by the STATIC_MASTER mutex.  Note that
   95577   ** MutexAlloc() is called for a static mutex prior to initializing the
   95578   ** malloc subsystem - this implies that the allocation of a static
   95579   ** mutex must not require support from the malloc subsystem.
   95580   */
   95581   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   95582   sqlite3_mutex_enter(pMaster);
   95583   sqlite3GlobalConfig.isMutexInit = 1;
   95584   if( !sqlite3GlobalConfig.isMallocInit ){
   95585     rc = sqlite3MallocInit();
   95586   }
   95587   if( rc==SQLITE_OK ){
   95588     sqlite3GlobalConfig.isMallocInit = 1;
   95589     if( !sqlite3GlobalConfig.pInitMutex ){
   95590       sqlite3GlobalConfig.pInitMutex =
   95591            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
   95592       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
   95593         rc = SQLITE_NOMEM;
   95594       }
   95595     }
   95596   }
   95597   if( rc==SQLITE_OK ){
   95598     sqlite3GlobalConfig.nRefInitMutex++;
   95599   }
   95600   sqlite3_mutex_leave(pMaster);
   95601 
   95602   /* If rc is not SQLITE_OK at this point, then either the malloc
   95603   ** subsystem could not be initialized or the system failed to allocate
   95604   ** the pInitMutex mutex. Return an error in either case.  */
   95605   if( rc!=SQLITE_OK ){
   95606     return rc;
   95607   }
   95608 
   95609   /* Do the rest of the initialization under the recursive mutex so
   95610   ** that we will be able to handle recursive calls into
   95611   ** sqlite3_initialize().  The recursive calls normally come through
   95612   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
   95613   ** recursive calls might also be possible.
   95614   */
   95615   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
   95616   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
   95617     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   95618     sqlite3GlobalConfig.inProgress = 1;
   95619     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
   95620     sqlite3RegisterGlobalFunctions();
   95621     if( sqlite3GlobalConfig.isPCacheInit==0 ){
   95622       rc = sqlite3PcacheInitialize();
   95623     }
   95624     if( rc==SQLITE_OK ){
   95625       sqlite3GlobalConfig.isPCacheInit = 1;
   95626       rc = sqlite3OsInit();
   95627     }
   95628     if( rc==SQLITE_OK ){
   95629       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
   95630           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
   95631       sqlite3GlobalConfig.isInit = 1;
   95632     }
   95633     sqlite3GlobalConfig.inProgress = 0;
   95634   }
   95635   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
   95636 
   95637   /* Go back under the static mutex and clean up the recursive
   95638   ** mutex to prevent a resource leak.
   95639   */
   95640   sqlite3_mutex_enter(pMaster);
   95641   sqlite3GlobalConfig.nRefInitMutex--;
   95642   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
   95643     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
   95644     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
   95645     sqlite3GlobalConfig.pInitMutex = 0;
   95646   }
   95647   sqlite3_mutex_leave(pMaster);
   95648 
   95649   /* The following is just a sanity check to make sure SQLite has
   95650   ** been compiled correctly.  It is important to run this code, but
   95651   ** we don't want to run it too often and soak up CPU cycles for no
   95652   ** reason.  So we run it once during initialization.
   95653   */
   95654 #ifndef NDEBUG
   95655 #ifndef SQLITE_OMIT_FLOATING_POINT
   95656   /* This section of code's only "output" is via assert() statements. */
   95657   if ( rc==SQLITE_OK ){
   95658     u64 x = (((u64)1)<<63)-1;
   95659     double y;
   95660     assert(sizeof(x)==8);
   95661     assert(sizeof(x)==sizeof(y));
   95662     memcpy(&y, &x, 8);
   95663     assert( sqlite3IsNaN(y) );
   95664   }
   95665 #endif
   95666 #endif
   95667 
   95668   return rc;
   95669 }
   95670 
   95671 /*
   95672 ** Undo the effects of sqlite3_initialize().  Must not be called while
   95673 ** there are outstanding database connections or memory allocations or
   95674 ** while any part of SQLite is otherwise in use in any thread.  This
   95675 ** routine is not threadsafe.  But it is safe to invoke this routine
   95676 ** on when SQLite is already shut down.  If SQLite is already shut down
   95677 ** when this routine is invoked, then this routine is a harmless no-op.
   95678 */
   95679 SQLITE_API int sqlite3_shutdown(void){
   95680   if( sqlite3GlobalConfig.isInit ){
   95681     sqlite3_os_end();
   95682     sqlite3_reset_auto_extension();
   95683     sqlite3GlobalConfig.isInit = 0;
   95684   }
   95685   if( sqlite3GlobalConfig.isPCacheInit ){
   95686     sqlite3PcacheShutdown();
   95687     sqlite3GlobalConfig.isPCacheInit = 0;
   95688   }
   95689   if( sqlite3GlobalConfig.isMallocInit ){
   95690     sqlite3MallocEnd();
   95691     sqlite3GlobalConfig.isMallocInit = 0;
   95692   }
   95693   if( sqlite3GlobalConfig.isMutexInit ){
   95694     sqlite3MutexEnd();
   95695     sqlite3GlobalConfig.isMutexInit = 0;
   95696   }
   95697 
   95698   return SQLITE_OK;
   95699 }
   95700 
   95701 /*
   95702 ** This API allows applications to modify the global configuration of
   95703 ** the SQLite library at run-time.
   95704 **
   95705 ** This routine should only be called when there are no outstanding
   95706 ** database connections or memory allocations.  This routine is not
   95707 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
   95708 ** behavior.
   95709 */
   95710 SQLITE_API int sqlite3_config(int op, ...){
   95711   va_list ap;
   95712   int rc = SQLITE_OK;
   95713 
   95714   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
   95715   ** the SQLite library is in use. */
   95716   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
   95717 
   95718   va_start(ap, op);
   95719   switch( op ){
   95720 
   95721     /* Mutex configuration options are only available in a threadsafe
   95722     ** compile.
   95723     */
   95724 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
   95725     case SQLITE_CONFIG_SINGLETHREAD: {
   95726       /* Disable all mutexing */
   95727       sqlite3GlobalConfig.bCoreMutex = 0;
   95728       sqlite3GlobalConfig.bFullMutex = 0;
   95729       break;
   95730     }
   95731     case SQLITE_CONFIG_MULTITHREAD: {
   95732       /* Disable mutexing of database connections */
   95733       /* Enable mutexing of core data structures */
   95734       sqlite3GlobalConfig.bCoreMutex = 1;
   95735       sqlite3GlobalConfig.bFullMutex = 0;
   95736       break;
   95737     }
   95738     case SQLITE_CONFIG_SERIALIZED: {
   95739       /* Enable all mutexing */
   95740       sqlite3GlobalConfig.bCoreMutex = 1;
   95741       sqlite3GlobalConfig.bFullMutex = 1;
   95742       break;
   95743     }
   95744     case SQLITE_CONFIG_MUTEX: {
   95745       /* Specify an alternative mutex implementation */
   95746       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
   95747       break;
   95748     }
   95749     case SQLITE_CONFIG_GETMUTEX: {
   95750       /* Retrieve the current mutex implementation */
   95751       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
   95752       break;
   95753     }
   95754 #endif
   95755 
   95756 
   95757     case SQLITE_CONFIG_MALLOC: {
   95758       /* Specify an alternative malloc implementation */
   95759       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
   95760       break;
   95761     }
   95762     case SQLITE_CONFIG_GETMALLOC: {
   95763       /* Retrieve the current malloc() implementation */
   95764       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
   95765       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
   95766       break;
   95767     }
   95768     case SQLITE_CONFIG_MEMSTATUS: {
   95769       /* Enable or disable the malloc status collection */
   95770       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
   95771       break;
   95772     }
   95773     case SQLITE_CONFIG_SCRATCH: {
   95774       /* Designate a buffer for scratch memory space */
   95775       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
   95776       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
   95777       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
   95778       break;
   95779     }
   95780     case SQLITE_CONFIG_PAGECACHE: {
   95781       /* Designate a buffer for page cache memory space */
   95782       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
   95783       sqlite3GlobalConfig.szPage = va_arg(ap, int);
   95784       sqlite3GlobalConfig.nPage = va_arg(ap, int);
   95785       break;
   95786     }
   95787 
   95788     case SQLITE_CONFIG_PCACHE: {
   95789       /* Specify an alternative page cache implementation */
   95790       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
   95791       break;
   95792     }
   95793 
   95794     case SQLITE_CONFIG_GETPCACHE: {
   95795       if( sqlite3GlobalConfig.pcache.xInit==0 ){
   95796         sqlite3PCacheSetDefault();
   95797       }
   95798       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
   95799       break;
   95800     }
   95801 
   95802 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
   95803     case SQLITE_CONFIG_HEAP: {
   95804       /* Designate a buffer for heap memory space */
   95805       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
   95806       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
   95807       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
   95808 
   95809       if( sqlite3GlobalConfig.pHeap==0 ){
   95810         /* If the heap pointer is NULL, then restore the malloc implementation
   95811         ** back to NULL pointers too.  This will cause the malloc to go
   95812         ** back to its default implementation when sqlite3_initialize() is
   95813         ** run.
   95814         */
   95815         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
   95816       }else{
   95817         /* The heap pointer is not NULL, then install one of the
   95818         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
   95819         ** ENABLE_MEMSYS5 is defined, return an error.
   95820         */
   95821 #ifdef SQLITE_ENABLE_MEMSYS3
   95822         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
   95823 #endif
   95824 #ifdef SQLITE_ENABLE_MEMSYS5
   95825         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
   95826 #endif
   95827       }
   95828       break;
   95829     }
   95830 #endif
   95831 
   95832     case SQLITE_CONFIG_LOOKASIDE: {
   95833       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
   95834       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
   95835       break;
   95836     }
   95837 
   95838     /* Record a pointer to the logger funcction and its first argument.
   95839     ** The default is NULL.  Logging is disabled if the function pointer is
   95840     ** NULL.
   95841     */
   95842     case SQLITE_CONFIG_LOG: {
   95843       sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
   95844       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
   95845       break;
   95846     }
   95847 
   95848     default: {
   95849       rc = SQLITE_ERROR;
   95850       break;
   95851     }
   95852   }
   95853   va_end(ap);
   95854   return rc;
   95855 }
   95856 
   95857 /*
   95858 ** Set up the lookaside buffers for a database connection.
   95859 ** Return SQLITE_OK on success.
   95860 ** If lookaside is already active, return SQLITE_BUSY.
   95861 **
   95862 ** The sz parameter is the number of bytes in each lookaside slot.
   95863 ** The cnt parameter is the number of slots.  If pStart is NULL the
   95864 ** space for the lookaside memory is obtained from sqlite3_malloc().
   95865 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
   95866 ** the lookaside memory.
   95867 */
   95868 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
   95869   void *pStart;
   95870   if( db->lookaside.nOut ){
   95871     return SQLITE_BUSY;
   95872   }
   95873   /* Free any existing lookaside buffer for this handle before
   95874   ** allocating a new one so we don't have to have space for
   95875   ** both at the same time.
   95876   */
   95877   if( db->lookaside.bMalloced ){
   95878     sqlite3_free(db->lookaside.pStart);
   95879   }
   95880   /* The size of a lookaside slot needs to be larger than a pointer
   95881   ** to be useful.
   95882   */
   95883   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
   95884   if( cnt<0 ) cnt = 0;
   95885   if( sz==0 || cnt==0 ){
   95886     sz = 0;
   95887     pStart = 0;
   95888   }else if( pBuf==0 ){
   95889     sz = ROUND8(sz);
   95890     sqlite3BeginBenignMalloc();
   95891     pStart = sqlite3Malloc( sz*cnt );
   95892     sqlite3EndBenignMalloc();
   95893   }else{
   95894     sz = ROUNDDOWN8(sz);
   95895     pStart = pBuf;
   95896   }
   95897   db->lookaside.pStart = pStart;
   95898   db->lookaside.pFree = 0;
   95899   db->lookaside.sz = (u16)sz;
   95900   if( pStart ){
   95901     int i;
   95902     LookasideSlot *p;
   95903     assert( sz > (int)sizeof(LookasideSlot*) );
   95904     p = (LookasideSlot*)pStart;
   95905     for(i=cnt-1; i>=0; i--){
   95906       p->pNext = db->lookaside.pFree;
   95907       db->lookaside.pFree = p;
   95908       p = (LookasideSlot*)&((u8*)p)[sz];
   95909     }
   95910     db->lookaside.pEnd = p;
   95911     db->lookaside.bEnabled = 1;
   95912     db->lookaside.bMalloced = pBuf==0 ?1:0;
   95913   }else{
   95914     db->lookaside.pEnd = 0;
   95915     db->lookaside.bEnabled = 0;
   95916     db->lookaside.bMalloced = 0;
   95917   }
   95918   return SQLITE_OK;
   95919 }
   95920 
   95921 /*
   95922 ** Return the mutex associated with a database connection.
   95923 */
   95924 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
   95925   return db->mutex;
   95926 }
   95927 
   95928 /*
   95929 ** Configuration settings for an individual database connection
   95930 */
   95931 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
   95932   va_list ap;
   95933   int rc;
   95934   va_start(ap, op);
   95935   switch( op ){
   95936     case SQLITE_DBCONFIG_LOOKASIDE: {
   95937       void *pBuf = va_arg(ap, void*);
   95938       int sz = va_arg(ap, int);
   95939       int cnt = va_arg(ap, int);
   95940       rc = setupLookaside(db, pBuf, sz, cnt);
   95941       break;
   95942     }
   95943     default: {
   95944       rc = SQLITE_ERROR;
   95945       break;
   95946     }
   95947   }
   95948   va_end(ap);
   95949   return rc;
   95950 }
   95951 
   95952 
   95953 /*
   95954 ** Return true if the buffer z[0..n-1] contains all spaces.
   95955 */
   95956 static int allSpaces(const char *z, int n){
   95957   while( n>0 && z[n-1]==' ' ){ n--; }
   95958   return n==0;
   95959 }
   95960 
   95961 /*
   95962 ** This is the default collating function named "BINARY" which is always
   95963 ** available.
   95964 **
   95965 ** If the padFlag argument is not NULL then space padding at the end
   95966 ** of strings is ignored.  This implements the RTRIM collation.
   95967 */
   95968 static int binCollFunc(
   95969   void *padFlag,
   95970   int nKey1, const void *pKey1,
   95971   int nKey2, const void *pKey2
   95972 ){
   95973   int rc, n;
   95974   n = nKey1<nKey2 ? nKey1 : nKey2;
   95975   rc = memcmp(pKey1, pKey2, n);
   95976   if( rc==0 ){
   95977     if( padFlag
   95978      && allSpaces(((char*)pKey1)+n, nKey1-n)
   95979      && allSpaces(((char*)pKey2)+n, nKey2-n)
   95980     ){
   95981       /* Leave rc unchanged at 0 */
   95982     }else{
   95983       rc = nKey1 - nKey2;
   95984     }
   95985   }
   95986   return rc;
   95987 }
   95988 
   95989 /*
   95990 ** Another built-in collating sequence: NOCASE.
   95991 **
   95992 ** This collating sequence is intended to be used for "case independant
   95993 ** comparison". SQLite's knowledge of upper and lower case equivalents
   95994 ** extends only to the 26 characters used in the English language.
   95995 **
   95996 ** At the moment there is only a UTF-8 implementation.
   95997 */
   95998 static int nocaseCollatingFunc(
   95999   void *NotUsed,
   96000   int nKey1, const void *pKey1,
   96001   int nKey2, const void *pKey2
   96002 ){
   96003   int r = sqlite3StrNICmp(
   96004       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
   96005   UNUSED_PARAMETER(NotUsed);
   96006   if( 0==r ){
   96007     r = nKey1-nKey2;
   96008   }
   96009   return r;
   96010 }
   96011 
   96012 /*
   96013 ** Return the ROWID of the most recent insert
   96014 */
   96015 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
   96016   return db->lastRowid;
   96017 }
   96018 
   96019 /*
   96020 ** Return the number of changes in the most recent call to sqlite3_exec().
   96021 */
   96022 SQLITE_API int sqlite3_changes(sqlite3 *db){
   96023   return db->nChange;
   96024 }
   96025 
   96026 /*
   96027 ** Return the number of changes since the database handle was opened.
   96028 */
   96029 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
   96030   return db->nTotalChange;
   96031 }
   96032 
   96033 /*
   96034 ** Close all open savepoints. This function only manipulates fields of the
   96035 ** database handle object, it does not close any savepoints that may be open
   96036 ** at the b-tree/pager level.
   96037 */
   96038 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
   96039   while( db->pSavepoint ){
   96040     Savepoint *pTmp = db->pSavepoint;
   96041     db->pSavepoint = pTmp->pNext;
   96042     sqlite3DbFree(db, pTmp);
   96043   }
   96044   db->nSavepoint = 0;
   96045   db->nStatement = 0;
   96046   db->isTransactionSavepoint = 0;
   96047 }
   96048 
   96049 /*
   96050 ** Close an existing SQLite database
   96051 */
   96052 SQLITE_API int sqlite3_close(sqlite3 *db){
   96053   HashElem *i;
   96054   int j;
   96055 
   96056   if( !db ){
   96057     return SQLITE_OK;
   96058   }
   96059   if( !sqlite3SafetyCheckSickOrOk(db) ){
   96060     return SQLITE_MISUSE_BKPT;
   96061   }
   96062   sqlite3_mutex_enter(db->mutex);
   96063 
   96064   sqlite3ResetInternalSchema(db, 0);
   96065 
   96066   /* If a transaction is open, the ResetInternalSchema() call above
   96067   ** will not have called the xDisconnect() method on any virtual
   96068   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
   96069   ** call will do so. We need to do this before the check for active
   96070   ** SQL statements below, as the v-table implementation may be storing
   96071   ** some prepared statements internally.
   96072   */
   96073   sqlite3VtabRollback(db);
   96074 
   96075   /* If there are any outstanding VMs, return SQLITE_BUSY. */
   96076   if( db->pVdbe ){
   96077     sqlite3Error(db, SQLITE_BUSY,
   96078         "unable to close due to unfinalised statements");
   96079     sqlite3_mutex_leave(db->mutex);
   96080     return SQLITE_BUSY;
   96081   }
   96082   assert( sqlite3SafetyCheckSickOrOk(db) );
   96083 
   96084   for(j=0; j<db->nDb; j++){
   96085     Btree *pBt = db->aDb[j].pBt;
   96086     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
   96087       sqlite3Error(db, SQLITE_BUSY,
   96088           "unable to close due to unfinished backup operation");
   96089       sqlite3_mutex_leave(db->mutex);
   96090       return SQLITE_BUSY;
   96091     }
   96092   }
   96093 
   96094   /* Free any outstanding Savepoint structures. */
   96095   sqlite3CloseSavepoints(db);
   96096 
   96097   for(j=0; j<db->nDb; j++){
   96098     struct Db *pDb = &db->aDb[j];
   96099     if( pDb->pBt ){
   96100       sqlite3BtreeClose(pDb->pBt);
   96101       pDb->pBt = 0;
   96102       if( j!=1 ){
   96103         pDb->pSchema = 0;
   96104       }
   96105     }
   96106   }
   96107   sqlite3ResetInternalSchema(db, 0);
   96108 
   96109   /* Tell the code in notify.c that the connection no longer holds any
   96110   ** locks and does not require any further unlock-notify callbacks.
   96111   */
   96112   sqlite3ConnectionClosed(db);
   96113 
   96114   assert( db->nDb<=2 );
   96115   assert( db->aDb==db->aDbStatic );
   96116   for(j=0; j<ArraySize(db->aFunc.a); j++){
   96117     FuncDef *pNext, *pHash, *p;
   96118     for(p=db->aFunc.a[j]; p; p=pHash){
   96119       pHash = p->pHash;
   96120       while( p ){
   96121         pNext = p->pNext;
   96122         sqlite3DbFree(db, p);
   96123         p = pNext;
   96124       }
   96125     }
   96126   }
   96127   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
   96128     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
   96129     /* Invoke any destructors registered for collation sequence user data. */
   96130     for(j=0; j<3; j++){
   96131       if( pColl[j].xDel ){
   96132         pColl[j].xDel(pColl[j].pUser);
   96133       }
   96134     }
   96135     sqlite3DbFree(db, pColl);
   96136   }
   96137   sqlite3HashClear(&db->aCollSeq);
   96138 #ifndef SQLITE_OMIT_VIRTUALTABLE
   96139   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
   96140     Module *pMod = (Module *)sqliteHashData(i);
   96141     if( pMod->xDestroy ){
   96142       pMod->xDestroy(pMod->pAux);
   96143     }
   96144     sqlite3DbFree(db, pMod);
   96145   }
   96146   sqlite3HashClear(&db->aModule);
   96147 #endif
   96148 
   96149   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
   96150   if( db->pErr ){
   96151     sqlite3ValueFree(db->pErr);
   96152   }
   96153   sqlite3CloseExtensions(db);
   96154 
   96155   db->magic = SQLITE_MAGIC_ERROR;
   96156 
   96157   /* The temp-database schema is allocated differently from the other schema
   96158   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
   96159   ** So it needs to be freed here. Todo: Why not roll the temp schema into
   96160   ** the same sqliteMalloc() as the one that allocates the database
   96161   ** structure?
   96162   */
   96163   sqlite3DbFree(db, db->aDb[1].pSchema);
   96164   sqlite3_mutex_leave(db->mutex);
   96165   db->magic = SQLITE_MAGIC_CLOSED;
   96166   sqlite3_mutex_free(db->mutex);
   96167   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
   96168   if( db->lookaside.bMalloced ){
   96169     sqlite3_free(db->lookaside.pStart);
   96170   }
   96171   sqlite3_free(db);
   96172   return SQLITE_OK;
   96173 }
   96174 
   96175 /*
   96176 ** Rollback all database files.
   96177 */
   96178 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
   96179   int i;
   96180   int inTrans = 0;
   96181   assert( sqlite3_mutex_held(db->mutex) );
   96182   sqlite3BeginBenignMalloc();
   96183   for(i=0; i<db->nDb; i++){
   96184     if( db->aDb[i].pBt ){
   96185       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
   96186         inTrans = 1;
   96187       }
   96188       sqlite3BtreeRollback(db->aDb[i].pBt);
   96189       db->aDb[i].inTrans = 0;
   96190     }
   96191   }
   96192   sqlite3VtabRollback(db);
   96193   sqlite3EndBenignMalloc();
   96194 
   96195   if( db->flags&SQLITE_InternChanges ){
   96196     sqlite3ExpirePreparedStatements(db);
   96197     sqlite3ResetInternalSchema(db, 0);
   96198   }
   96199 
   96200   /* Any deferred constraint violations have now been resolved. */
   96201   db->nDeferredCons = 0;
   96202 
   96203   /* If one has been configured, invoke the rollback-hook callback */
   96204   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
   96205     db->xRollbackCallback(db->pRollbackArg);
   96206   }
   96207 }
   96208 
   96209 /*
   96210 ** Return a static string that describes the kind of error specified in the
   96211 ** argument.
   96212 */
   96213 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
   96214   static const char* const aMsg[] = {
   96215     /* SQLITE_OK          */ "not an error",
   96216     /* SQLITE_ERROR       */ "SQL logic error or missing database",
   96217     /* SQLITE_INTERNAL    */ 0,
   96218     /* SQLITE_PERM        */ "access permission denied",
   96219     /* SQLITE_ABORT       */ "callback requested query abort",
   96220     /* SQLITE_BUSY        */ "database is locked",
   96221     /* SQLITE_LOCKED      */ "database table is locked",
   96222     /* SQLITE_NOMEM       */ "out of memory",
   96223     /* SQLITE_READONLY    */ "attempt to write a readonly database",
   96224     /* SQLITE_INTERRUPT   */ "interrupted",
   96225     /* SQLITE_IOERR       */ "disk I/O error",
   96226     /* SQLITE_CORRUPT     */ "database disk image is malformed",
   96227     /* SQLITE_NOTFOUND    */ 0,
   96228     /* SQLITE_FULL        */ "database or disk is full",
   96229     /* SQLITE_CANTOPEN    */ "unable to open database file",
   96230     /* SQLITE_PROTOCOL    */ 0,
   96231     /* SQLITE_EMPTY       */ "table contains no data",
   96232     /* SQLITE_SCHEMA      */ "database schema has changed",
   96233     /* SQLITE_TOOBIG      */ "string or blob too big",
   96234     /* SQLITE_CONSTRAINT  */ "constraint failed",
   96235     /* SQLITE_MISMATCH    */ "datatype mismatch",
   96236     /* SQLITE_MISUSE      */ "library routine called out of sequence",
   96237     /* SQLITE_NOLFS       */ "large file support is disabled",
   96238     /* SQLITE_AUTH        */ "authorization denied",
   96239     /* SQLITE_FORMAT      */ "auxiliary database format error",
   96240     /* SQLITE_RANGE       */ "bind or column index out of range",
   96241     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
   96242   };
   96243   rc &= 0xff;
   96244   if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
   96245     return aMsg[rc];
   96246   }else{
   96247     return "unknown error";
   96248   }
   96249 }
   96250 
   96251 /*
   96252 ** This routine implements a busy callback that sleeps and tries
   96253 ** again until a timeout value is reached.  The timeout value is
   96254 ** an integer number of milliseconds passed in as the first
   96255 ** argument.
   96256 */
   96257 static int sqliteDefaultBusyCallback(
   96258  void *ptr,               /* Database connection */
   96259  int count                /* Number of times table has been busy */
   96260 ){
   96261 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
   96262   static const u8 delays[] =
   96263      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
   96264   static const u8 totals[] =
   96265      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
   96266 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
   96267   sqlite3 *db = (sqlite3 *)ptr;
   96268   int timeout = db->busyTimeout;
   96269   int delay, prior;
   96270 
   96271   assert( count>=0 );
   96272   if( count < NDELAY ){
   96273     delay = delays[count];
   96274     prior = totals[count];
   96275   }else{
   96276     delay = delays[NDELAY-1];
   96277     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
   96278   }
   96279   if( prior + delay > timeout ){
   96280     delay = timeout - prior;
   96281     if( delay<=0 ) return 0;
   96282   }
   96283   sqlite3OsSleep(db->pVfs, delay*1000);
   96284   return 1;
   96285 #else
   96286   sqlite3 *db = (sqlite3 *)ptr;
   96287   int timeout = ((sqlite3 *)ptr)->busyTimeout;
   96288   if( (count+1)*1000 > timeout ){
   96289     return 0;
   96290   }
   96291   sqlite3OsSleep(db->pVfs, 1000000);
   96292   return 1;
   96293 #endif
   96294 }
   96295 
   96296 /*
   96297 ** Invoke the given busy handler.
   96298 **
   96299 ** This routine is called when an operation failed with a lock.
   96300 ** If this routine returns non-zero, the lock is retried.  If it
   96301 ** returns 0, the operation aborts with an SQLITE_BUSY error.
   96302 */
   96303 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
   96304   int rc;
   96305   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
   96306   rc = p->xFunc(p->pArg, p->nBusy);
   96307   if( rc==0 ){
   96308     p->nBusy = -1;
   96309   }else{
   96310     p->nBusy++;
   96311   }
   96312   return rc;
   96313 }
   96314 
   96315 /*
   96316 ** This routine sets the busy callback for an Sqlite database to the
   96317 ** given callback function with the given argument.
   96318 */
   96319 SQLITE_API int sqlite3_busy_handler(
   96320   sqlite3 *db,
   96321   int (*xBusy)(void*,int),
   96322   void *pArg
   96323 ){
   96324   sqlite3_mutex_enter(db->mutex);
   96325   db->busyHandler.xFunc = xBusy;
   96326   db->busyHandler.pArg = pArg;
   96327   db->busyHandler.nBusy = 0;
   96328   sqlite3_mutex_leave(db->mutex);
   96329   return SQLITE_OK;
   96330 }
   96331 
   96332 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   96333 /*
   96334 ** This routine sets the progress callback for an Sqlite database to the
   96335 ** given callback function with the given argument. The progress callback will
   96336 ** be invoked every nOps opcodes.
   96337 */
   96338 SQLITE_API void sqlite3_progress_handler(
   96339   sqlite3 *db,
   96340   int nOps,
   96341   int (*xProgress)(void*),
   96342   void *pArg
   96343 ){
   96344   sqlite3_mutex_enter(db->mutex);
   96345   if( nOps>0 ){
   96346     db->xProgress = xProgress;
   96347     db->nProgressOps = nOps;
   96348     db->pProgressArg = pArg;
   96349   }else{
   96350     db->xProgress = 0;
   96351     db->nProgressOps = 0;
   96352     db->pProgressArg = 0;
   96353   }
   96354   sqlite3_mutex_leave(db->mutex);
   96355 }
   96356 #endif
   96357 
   96358 
   96359 /*
   96360 ** This routine installs a default busy handler that waits for the
   96361 ** specified number of milliseconds before returning 0.
   96362 */
   96363 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
   96364   if( ms>0 ){
   96365     db->busyTimeout = ms;
   96366     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
   96367   }else{
   96368     sqlite3_busy_handler(db, 0, 0);
   96369   }
   96370   return SQLITE_OK;
   96371 }
   96372 
   96373 /*
   96374 ** Cause any pending operation to stop at its earliest opportunity.
   96375 */
   96376 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
   96377   db->u1.isInterrupted = 1;
   96378 }
   96379 
   96380 
   96381 /*
   96382 ** This function is exactly the same as sqlite3_create_function(), except
   96383 ** that it is designed to be called by internal code. The difference is
   96384 ** that if a malloc() fails in sqlite3_create_function(), an error code
   96385 ** is returned and the mallocFailed flag cleared.
   96386 */
   96387 SQLITE_PRIVATE int sqlite3CreateFunc(
   96388   sqlite3 *db,
   96389   const char *zFunctionName,
   96390   int nArg,
   96391   int enc,
   96392   void *pUserData,
   96393   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   96394   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   96395   void (*xFinal)(sqlite3_context*)
   96396 ){
   96397   FuncDef *p;
   96398   int nName;
   96399 
   96400   assert( sqlite3_mutex_held(db->mutex) );
   96401   if( zFunctionName==0 ||
   96402       (xFunc && (xFinal || xStep)) ||
   96403       (!xFunc && (xFinal && !xStep)) ||
   96404       (!xFunc && (!xFinal && xStep)) ||
   96405       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
   96406       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
   96407     return SQLITE_MISUSE_BKPT;
   96408   }
   96409 
   96410 #ifndef SQLITE_OMIT_UTF16
   96411   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   96412   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
   96413   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
   96414   **
   96415   ** If SQLITE_ANY is specified, add three versions of the function
   96416   ** to the hash table.
   96417   */
   96418   if( enc==SQLITE_UTF16 ){
   96419     enc = SQLITE_UTF16NATIVE;
   96420   }else if( enc==SQLITE_ANY ){
   96421     int rc;
   96422     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
   96423          pUserData, xFunc, xStep, xFinal);
   96424     if( rc==SQLITE_OK ){
   96425       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
   96426           pUserData, xFunc, xStep, xFinal);
   96427     }
   96428     if( rc!=SQLITE_OK ){
   96429       return rc;
   96430     }
   96431     enc = SQLITE_UTF16BE;
   96432   }
   96433 #else
   96434   enc = SQLITE_UTF8;
   96435 #endif
   96436 
   96437   /* Check if an existing function is being overridden or deleted. If so,
   96438   ** and there are active VMs, then return SQLITE_BUSY. If a function
   96439   ** is being overridden/deleted but there are no active VMs, allow the
   96440   ** operation to continue but invalidate all precompiled statements.
   96441   */
   96442   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
   96443   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
   96444     if( db->activeVdbeCnt ){
   96445       sqlite3Error(db, SQLITE_BUSY,
   96446         "unable to delete/modify user-function due to active statements");
   96447       assert( !db->mallocFailed );
   96448       return SQLITE_BUSY;
   96449     }else{
   96450       sqlite3ExpirePreparedStatements(db);
   96451     }
   96452   }
   96453 
   96454   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
   96455   assert(p || db->mallocFailed);
   96456   if( !p ){
   96457     return SQLITE_NOMEM;
   96458   }
   96459   p->flags = 0;
   96460   p->xFunc = xFunc;
   96461   p->xStep = xStep;
   96462   p->xFinalize = xFinal;
   96463   p->pUserData = pUserData;
   96464   p->nArg = (u16)nArg;
   96465   return SQLITE_OK;
   96466 }
   96467 
   96468 /*
   96469 ** Create new user functions.
   96470 */
   96471 SQLITE_API int sqlite3_create_function(
   96472   sqlite3 *db,
   96473   const char *zFunctionName,
   96474   int nArg,
   96475   int enc,
   96476   void *p,
   96477   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   96478   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   96479   void (*xFinal)(sqlite3_context*)
   96480 ){
   96481   int rc;
   96482   sqlite3_mutex_enter(db->mutex);
   96483   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
   96484   rc = sqlite3ApiExit(db, rc);
   96485   sqlite3_mutex_leave(db->mutex);
   96486   return rc;
   96487 }
   96488 
   96489 #ifndef SQLITE_OMIT_UTF16
   96490 SQLITE_API int sqlite3_create_function16(
   96491   sqlite3 *db,
   96492   const void *zFunctionName,
   96493   int nArg,
   96494   int eTextRep,
   96495   void *p,
   96496   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   96497   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   96498   void (*xFinal)(sqlite3_context*)
   96499 ){
   96500   int rc;
   96501   char *zFunc8;
   96502   sqlite3_mutex_enter(db->mutex);
   96503   assert( !db->mallocFailed );
   96504   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
   96505   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
   96506   sqlite3DbFree(db, zFunc8);
   96507   rc = sqlite3ApiExit(db, rc);
   96508   sqlite3_mutex_leave(db->mutex);
   96509   return rc;
   96510 }
   96511 #endif
   96512 
   96513 
   96514 /*
   96515 ** Declare that a function has been overloaded by a virtual table.
   96516 **
   96517 ** If the function already exists as a regular global function, then
   96518 ** this routine is a no-op.  If the function does not exist, then create
   96519 ** a new one that always throws a run-time error.
   96520 **
   96521 ** When virtual tables intend to provide an overloaded function, they
   96522 ** should call this routine to make sure the global function exists.
   96523 ** A global function must exist in order for name resolution to work
   96524 ** properly.
   96525 */
   96526 SQLITE_API int sqlite3_overload_function(
   96527   sqlite3 *db,
   96528   const char *zName,
   96529   int nArg
   96530 ){
   96531   int nName = sqlite3Strlen30(zName);
   96532   int rc;
   96533   sqlite3_mutex_enter(db->mutex);
   96534   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
   96535     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
   96536                       0, sqlite3InvalidFunction, 0, 0);
   96537   }
   96538   rc = sqlite3ApiExit(db, SQLITE_OK);
   96539   sqlite3_mutex_leave(db->mutex);
   96540   return rc;
   96541 }
   96542 
   96543 #ifndef SQLITE_OMIT_TRACE
   96544 /*
   96545 ** Register a trace function.  The pArg from the previously registered trace
   96546 ** is returned.
   96547 **
   96548 ** A NULL trace function means that no tracing is executes.  A non-NULL
   96549 ** trace is a pointer to a function that is invoked at the start of each
   96550 ** SQL statement.
   96551 */
   96552 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
   96553   void *pOld;
   96554   sqlite3_mutex_enter(db->mutex);
   96555   pOld = db->pTraceArg;
   96556   db->xTrace = xTrace;
   96557   db->pTraceArg = pArg;
   96558   sqlite3_mutex_leave(db->mutex);
   96559   return pOld;
   96560 }
   96561 /*
   96562 ** Register a profile function.  The pArg from the previously registered
   96563 ** profile function is returned.
   96564 **
   96565 ** A NULL profile function means that no profiling is executes.  A non-NULL
   96566 ** profile is a pointer to a function that is invoked at the conclusion of
   96567 ** each SQL statement that is run.
   96568 */
   96569 SQLITE_API void *sqlite3_profile(
   96570   sqlite3 *db,
   96571   void (*xProfile)(void*,const char*,sqlite_uint64),
   96572   void *pArg
   96573 ){
   96574   void *pOld;
   96575   sqlite3_mutex_enter(db->mutex);
   96576   pOld = db->pProfileArg;
   96577   db->xProfile = xProfile;
   96578   db->pProfileArg = pArg;
   96579   sqlite3_mutex_leave(db->mutex);
   96580   return pOld;
   96581 }
   96582 #endif /* SQLITE_OMIT_TRACE */
   96583 
   96584 /*** EXPERIMENTAL ***
   96585 **
   96586 ** Register a function to be invoked when a transaction comments.
   96587 ** If the invoked function returns non-zero, then the commit becomes a
   96588 ** rollback.
   96589 */
   96590 SQLITE_API void *sqlite3_commit_hook(
   96591   sqlite3 *db,              /* Attach the hook to this database */
   96592   int (*xCallback)(void*),  /* Function to invoke on each commit */
   96593   void *pArg                /* Argument to the function */
   96594 ){
   96595   void *pOld;
   96596   sqlite3_mutex_enter(db->mutex);
   96597   pOld = db->pCommitArg;
   96598   db->xCommitCallback = xCallback;
   96599   db->pCommitArg = pArg;
   96600   sqlite3_mutex_leave(db->mutex);
   96601   return pOld;
   96602 }
   96603 
   96604 /*
   96605 ** Register a callback to be invoked each time a row is updated,
   96606 ** inserted or deleted using this database connection.
   96607 */
   96608 SQLITE_API void *sqlite3_update_hook(
   96609   sqlite3 *db,              /* Attach the hook to this database */
   96610   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
   96611   void *pArg                /* Argument to the function */
   96612 ){
   96613   void *pRet;
   96614   sqlite3_mutex_enter(db->mutex);
   96615   pRet = db->pUpdateArg;
   96616   db->xUpdateCallback = xCallback;
   96617   db->pUpdateArg = pArg;
   96618   sqlite3_mutex_leave(db->mutex);
   96619   return pRet;
   96620 }
   96621 
   96622 /*
   96623 ** Register a callback to be invoked each time a transaction is rolled
   96624 ** back by this database connection.
   96625 */
   96626 SQLITE_API void *sqlite3_rollback_hook(
   96627   sqlite3 *db,              /* Attach the hook to this database */
   96628   void (*xCallback)(void*), /* Callback function */
   96629   void *pArg                /* Argument to the function */
   96630 ){
   96631   void *pRet;
   96632   sqlite3_mutex_enter(db->mutex);
   96633   pRet = db->pRollbackArg;
   96634   db->xRollbackCallback = xCallback;
   96635   db->pRollbackArg = pArg;
   96636   sqlite3_mutex_leave(db->mutex);
   96637   return pRet;
   96638 }
   96639 
   96640 /*
   96641 ** This function returns true if main-memory should be used instead of
   96642 ** a temporary file for transient pager files and statement journals.
   96643 ** The value returned depends on the value of db->temp_store (runtime
   96644 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
   96645 ** following table describes the relationship between these two values
   96646 ** and this functions return value.
   96647 **
   96648 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
   96649 **   -----------------     --------------     ------------------------------
   96650 **   0                     any                file      (return 0)
   96651 **   1                     1                  file      (return 0)
   96652 **   1                     2                  memory    (return 1)
   96653 **   1                     0                  file      (return 0)
   96654 **   2                     1                  file      (return 0)
   96655 **   2                     2                  memory    (return 1)
   96656 **   2                     0                  memory    (return 1)
   96657 **   3                     any                memory    (return 1)
   96658 */
   96659 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
   96660 #if SQLITE_TEMP_STORE==1
   96661   return ( db->temp_store==2 );
   96662 #endif
   96663 #if SQLITE_TEMP_STORE==2
   96664   return ( db->temp_store!=1 );
   96665 #endif
   96666 #if SQLITE_TEMP_STORE==3
   96667   return 1;
   96668 #endif
   96669 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
   96670   return 0;
   96671 #endif
   96672 }
   96673 
   96674 /*
   96675 ** This routine is called to create a connection to a database BTree
   96676 ** driver.  If zFilename is the name of a file, then that file is
   96677 ** opened and used.  If zFilename is the magic name ":memory:" then
   96678 ** the database is stored in memory (and is thus forgotten as soon as
   96679 ** the connection is closed.)  If zFilename is NULL then the database
   96680 ** is a "virtual" database for transient use only and is deleted as
   96681 ** soon as the connection is closed.
   96682 **
   96683 ** A virtual database can be either a disk file (that is automatically
   96684 ** deleted when the file is closed) or it an be held entirely in memory.
   96685 ** The sqlite3TempInMemory() function is used to determine which.
   96686 */
   96687 SQLITE_PRIVATE int sqlite3BtreeFactory(
   96688   sqlite3 *db,              /* Main database when opening aux otherwise 0 */
   96689   const char *zFilename,    /* Name of the file containing the BTree database */
   96690   int omitJournal,          /* if TRUE then do not journal this file */
   96691   int nCache,               /* How many pages in the page cache */
   96692   int vfsFlags,             /* Flags passed through to vfsOpen */
   96693   Btree **ppBtree           /* Pointer to new Btree object written here */
   96694 ){
   96695   int btFlags = 0;
   96696   int rc;
   96697 
   96698   assert( sqlite3_mutex_held(db->mutex) );
   96699   assert( ppBtree != 0);
   96700   if( omitJournal ){
   96701     btFlags |= BTREE_OMIT_JOURNAL;
   96702   }
   96703   if( db->flags & SQLITE_NoReadlock ){
   96704     btFlags |= BTREE_NO_READLOCK;
   96705   }
   96706 #ifndef SQLITE_OMIT_MEMORYDB
   96707   if( zFilename==0 && sqlite3TempInMemory(db) ){
   96708     zFilename = ":memory:";
   96709   }
   96710 #endif
   96711 
   96712   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
   96713     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
   96714   }
   96715   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
   96716 
   96717   /* If the B-Tree was successfully opened, set the pager-cache size to the
   96718   ** default value. Except, if the call to BtreeOpen() returned a handle
   96719   ** open on an existing shared pager-cache, do not change the pager-cache
   96720   ** size.
   96721   */
   96722   if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
   96723     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
   96724   }
   96725   return rc;
   96726 }
   96727 
   96728 /*
   96729 ** Return UTF-8 encoded English language explanation of the most recent
   96730 ** error.
   96731 */
   96732 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
   96733   const char *z;
   96734   if( !db ){
   96735     return sqlite3ErrStr(SQLITE_NOMEM);
   96736   }
   96737   if( !sqlite3SafetyCheckSickOrOk(db) ){
   96738     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
   96739   }
   96740   sqlite3_mutex_enter(db->mutex);
   96741   if( db->mallocFailed ){
   96742     z = sqlite3ErrStr(SQLITE_NOMEM);
   96743   }else{
   96744     z = (char*)sqlite3_value_text(db->pErr);
   96745     assert( !db->mallocFailed );
   96746     if( z==0 ){
   96747       z = sqlite3ErrStr(db->errCode);
   96748     }
   96749   }
   96750   sqlite3_mutex_leave(db->mutex);
   96751   return z;
   96752 }
   96753 
   96754 #ifndef SQLITE_OMIT_UTF16
   96755 /*
   96756 ** Return UTF-16 encoded English language explanation of the most recent
   96757 ** error.
   96758 */
   96759 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
   96760   static const u16 outOfMem[] = {
   96761     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
   96762   };
   96763   static const u16 misuse[] = {
   96764     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
   96765     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
   96766     'c', 'a', 'l', 'l', 'e', 'd', ' ',
   96767     'o', 'u', 't', ' ',
   96768     'o', 'f', ' ',
   96769     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
   96770   };
   96771 
   96772   const void *z;
   96773   if( !db ){
   96774     return (void *)outOfMem;
   96775   }
   96776   if( !sqlite3SafetyCheckSickOrOk(db) ){
   96777     return (void *)misuse;
   96778   }
   96779   sqlite3_mutex_enter(db->mutex);
   96780   if( db->mallocFailed ){
   96781     z = (void *)outOfMem;
   96782   }else{
   96783     z = sqlite3_value_text16(db->pErr);
   96784     if( z==0 ){
   96785       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
   96786            SQLITE_UTF8, SQLITE_STATIC);
   96787       z = sqlite3_value_text16(db->pErr);
   96788     }
   96789     /* A malloc() may have failed within the call to sqlite3_value_text16()
   96790     ** above. If this is the case, then the db->mallocFailed flag needs to
   96791     ** be cleared before returning. Do this directly, instead of via
   96792     ** sqlite3ApiExit(), to avoid setting the database handle error message.
   96793     */
   96794     db->mallocFailed = 0;
   96795   }
   96796   sqlite3_mutex_leave(db->mutex);
   96797   return z;
   96798 }
   96799 #endif /* SQLITE_OMIT_UTF16 */
   96800 
   96801 /*
   96802 ** Return the most recent error code generated by an SQLite routine. If NULL is
   96803 ** passed to this function, we assume a malloc() failed during sqlite3_open().
   96804 */
   96805 SQLITE_API int sqlite3_errcode(sqlite3 *db){
   96806   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
   96807     return SQLITE_MISUSE_BKPT;
   96808   }
   96809   if( !db || db->mallocFailed ){
   96810     return SQLITE_NOMEM;
   96811   }
   96812   return db->errCode & db->errMask;
   96813 }
   96814 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
   96815   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
   96816     return SQLITE_MISUSE_BKPT;
   96817   }
   96818   if( !db || db->mallocFailed ){
   96819     return SQLITE_NOMEM;
   96820   }
   96821   return db->errCode;
   96822 }
   96823 
   96824 /*
   96825 ** Create a new collating function for database "db".  The name is zName
   96826 ** and the encoding is enc.
   96827 */
   96828 static int createCollation(
   96829   sqlite3* db,
   96830   const char *zName,
   96831   u8 enc,
   96832   u8 collType,
   96833   void* pCtx,
   96834   int(*xCompare)(void*,int,const void*,int,const void*),
   96835   void(*xDel)(void*)
   96836 ){
   96837   CollSeq *pColl;
   96838   int enc2;
   96839   int nName = sqlite3Strlen30(zName);
   96840 
   96841   assert( sqlite3_mutex_held(db->mutex) );
   96842 
   96843   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   96844   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
   96845   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
   96846   */
   96847   enc2 = enc;
   96848   testcase( enc2==SQLITE_UTF16 );
   96849   testcase( enc2==SQLITE_UTF16_ALIGNED );
   96850   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
   96851     enc2 = SQLITE_UTF16NATIVE;
   96852   }
   96853   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
   96854     return SQLITE_MISUSE_BKPT;
   96855   }
   96856 
   96857   /* Check if this call is removing or replacing an existing collation
   96858   ** sequence. If so, and there are active VMs, return busy. If there
   96859   ** are no active VMs, invalidate any pre-compiled statements.
   96860   */
   96861   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
   96862   if( pColl && pColl->xCmp ){
   96863     if( db->activeVdbeCnt ){
   96864       sqlite3Error(db, SQLITE_BUSY,
   96865         "unable to delete/modify collation sequence due to active statements");
   96866       return SQLITE_BUSY;
   96867     }
   96868     sqlite3ExpirePreparedStatements(db);
   96869 
   96870     /* If collation sequence pColl was created directly by a call to
   96871     ** sqlite3_create_collation, and not generated by synthCollSeq(),
   96872     ** then any copies made by synthCollSeq() need to be invalidated.
   96873     ** Also, collation destructor - CollSeq.xDel() - function may need
   96874     ** to be called.
   96875     */
   96876     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
   96877       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
   96878       int j;
   96879       for(j=0; j<3; j++){
   96880         CollSeq *p = &aColl[j];
   96881         if( p->enc==pColl->enc ){
   96882           if( p->xDel ){
   96883             p->xDel(p->pUser);
   96884           }
   96885           p->xCmp = 0;
   96886         }
   96887       }
   96888     }
   96889   }
   96890 
   96891   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
   96892   if( pColl ){
   96893     pColl->xCmp = xCompare;
   96894     pColl->pUser = pCtx;
   96895     pColl->xDel = xDel;
   96896     pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
   96897     pColl->type = collType;
   96898   }
   96899   sqlite3Error(db, SQLITE_OK, 0);
   96900   return SQLITE_OK;
   96901 }
   96902 
   96903 
   96904 /*
   96905 ** This array defines hard upper bounds on limit values.  The
   96906 ** initializer must be kept in sync with the SQLITE_LIMIT_*
   96907 ** #defines in sqlite3.h.
   96908 */
   96909 static const int aHardLimit[] = {
   96910   SQLITE_MAX_LENGTH,
   96911   SQLITE_MAX_SQL_LENGTH,
   96912   SQLITE_MAX_COLUMN,
   96913   SQLITE_MAX_EXPR_DEPTH,
   96914   SQLITE_MAX_COMPOUND_SELECT,
   96915   SQLITE_MAX_VDBE_OP,
   96916   SQLITE_MAX_FUNCTION_ARG,
   96917   SQLITE_MAX_ATTACHED,
   96918   SQLITE_MAX_LIKE_PATTERN_LENGTH,
   96919   SQLITE_MAX_VARIABLE_NUMBER,
   96920   SQLITE_MAX_TRIGGER_DEPTH,
   96921 };
   96922 
   96923 /*
   96924 ** Make sure the hard limits are set to reasonable values
   96925 */
   96926 #if SQLITE_MAX_LENGTH<100
   96927 # error SQLITE_MAX_LENGTH must be at least 100
   96928 #endif
   96929 #if SQLITE_MAX_SQL_LENGTH<100
   96930 # error SQLITE_MAX_SQL_LENGTH must be at least 100
   96931 #endif
   96932 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
   96933 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
   96934 #endif
   96935 #if SQLITE_MAX_COMPOUND_SELECT<2
   96936 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
   96937 #endif
   96938 #if SQLITE_MAX_VDBE_OP<40
   96939 # error SQLITE_MAX_VDBE_OP must be at least 40
   96940 #endif
   96941 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
   96942 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
   96943 #endif
   96944 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
   96945 # error SQLITE_MAX_ATTACHED must be between 0 and 30
   96946 #endif
   96947 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
   96948 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
   96949 #endif
   96950 #if SQLITE_MAX_COLUMN>32767
   96951 # error SQLITE_MAX_COLUMN must not exceed 32767
   96952 #endif
   96953 #if SQLITE_MAX_TRIGGER_DEPTH<1
   96954 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
   96955 #endif
   96956 
   96957 
   96958 /*
   96959 ** Change the value of a limit.  Report the old value.
   96960 ** If an invalid limit index is supplied, report -1.
   96961 ** Make no changes but still report the old value if the
   96962 ** new limit is negative.
   96963 **
   96964 ** A new lower limit does not shrink existing constructs.
   96965 ** It merely prevents new constructs that exceed the limit
   96966 ** from forming.
   96967 */
   96968 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
   96969   int oldLimit;
   96970   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
   96971     return -1;
   96972   }
   96973   oldLimit = db->aLimit[limitId];
   96974   if( newLimit>=0 ){
   96975     if( newLimit>aHardLimit[limitId] ){
   96976       newLimit = aHardLimit[limitId];
   96977     }
   96978     db->aLimit[limitId] = newLimit;
   96979   }
   96980   return oldLimit;
   96981 }
   96982 
   96983 /*
   96984 ** This routine does the work of opening a database on behalf of
   96985 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
   96986 ** is UTF-8 encoded.
   96987 */
   96988 static int openDatabase(
   96989   const char *zFilename, /* Database filename UTF-8 encoded */
   96990   sqlite3 **ppDb,        /* OUT: Returned database handle */
   96991   unsigned flags,        /* Operational flags */
   96992   const char *zVfs       /* Name of the VFS to use */
   96993 ){
   96994   sqlite3 *db;
   96995   int rc;
   96996   int isThreadsafe;
   96997 
   96998   *ppDb = 0;
   96999 #ifndef SQLITE_OMIT_AUTOINIT
   97000   rc = sqlite3_initialize();
   97001   if( rc ) return rc;
   97002 #endif
   97003 
   97004   if( sqlite3GlobalConfig.bCoreMutex==0 ){
   97005     isThreadsafe = 0;
   97006   }else if( flags & SQLITE_OPEN_NOMUTEX ){
   97007     isThreadsafe = 0;
   97008   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
   97009     isThreadsafe = 1;
   97010   }else{
   97011     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
   97012   }
   97013   if( flags & SQLITE_OPEN_PRIVATECACHE ){
   97014     flags &= ~SQLITE_OPEN_SHAREDCACHE;
   97015   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
   97016     flags |= SQLITE_OPEN_SHAREDCACHE;
   97017   }
   97018 
   97019   /* Remove harmful bits from the flags parameter
   97020   **
   97021   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
   97022   ** dealt with in the previous code block.  Besides these, the only
   97023   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
   97024   ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE.  Silently mask
   97025   ** off all other flags.
   97026   */
   97027   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
   97028                SQLITE_OPEN_EXCLUSIVE |
   97029                SQLITE_OPEN_MAIN_DB |
   97030                SQLITE_OPEN_TEMP_DB |
   97031                SQLITE_OPEN_TRANSIENT_DB |
   97032                SQLITE_OPEN_MAIN_JOURNAL |
   97033                SQLITE_OPEN_TEMP_JOURNAL |
   97034                SQLITE_OPEN_SUBJOURNAL |
   97035                SQLITE_OPEN_MASTER_JOURNAL |
   97036                SQLITE_OPEN_NOMUTEX |
   97037                SQLITE_OPEN_FULLMUTEX
   97038              );
   97039 
   97040   /* Allocate the sqlite data structure */
   97041   db = sqlite3MallocZero( sizeof(sqlite3) );
   97042   if( db==0 ) goto opendb_out;
   97043   if( isThreadsafe ){
   97044     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
   97045     if( db->mutex==0 ){
   97046       sqlite3_free(db);
   97047       db = 0;
   97048       goto opendb_out;
   97049     }
   97050   }
   97051   sqlite3_mutex_enter(db->mutex);
   97052   db->errMask = 0xff;
   97053   db->nDb = 2;
   97054   db->magic = SQLITE_MAGIC_BUSY;
   97055   db->aDb = db->aDbStatic;
   97056 
   97057   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
   97058   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
   97059   db->autoCommit = 1;
   97060   db->nextAutovac = -1;
   97061   db->nextPagesize = 0;
   97062   db->flags |= SQLITE_ShortColNames
   97063 #if SQLITE_DEFAULT_FILE_FORMAT<4
   97064                  | SQLITE_LegacyFileFmt
   97065 #endif
   97066 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
   97067                  | SQLITE_LoadExtension
   97068 #endif
   97069 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
   97070                  | SQLITE_RecTriggers
   97071 #endif
   97072       ;
   97073   sqlite3HashInit(&db->aCollSeq);
   97074 #ifndef SQLITE_OMIT_VIRTUALTABLE
   97075   sqlite3HashInit(&db->aModule);
   97076 #endif
   97077 
   97078   db->pVfs = sqlite3_vfs_find(zVfs);
   97079   if( !db->pVfs ){
   97080     rc = SQLITE_ERROR;
   97081     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
   97082     goto opendb_out;
   97083   }
   97084 
   97085   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
   97086   ** and UTF-16, so add a version for each to avoid any unnecessary
   97087   ** conversions. The only error that can occur here is a malloc() failure.
   97088   */
   97089   createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
   97090                   binCollFunc, 0);
   97091   createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
   97092                   binCollFunc, 0);
   97093   createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
   97094                   binCollFunc, 0);
   97095   createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
   97096                   binCollFunc, 0);
   97097   if( db->mallocFailed ){
   97098     goto opendb_out;
   97099   }
   97100   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
   97101   assert( db->pDfltColl!=0 );
   97102 
   97103   /* Also add a UTF-8 case-insensitive collation sequence. */
   97104   createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
   97105                   nocaseCollatingFunc, 0);
   97106 
   97107   /* Open the backend database driver */
   97108   db->openFlags = flags;
   97109   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
   97110                            flags | SQLITE_OPEN_MAIN_DB,
   97111                            &db->aDb[0].pBt);
   97112   if( rc!=SQLITE_OK ){
   97113     if( rc==SQLITE_IOERR_NOMEM ){
   97114       rc = SQLITE_NOMEM;
   97115     }
   97116     sqlite3Error(db, rc, 0);
   97117     goto opendb_out;
   97118   }
   97119   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
   97120   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
   97121 
   97122 
   97123   /* The default safety_level for the main database is 'full'; for the temp
   97124   ** database it is 'NONE'. This matches the pager layer defaults.
   97125   */
   97126   db->aDb[0].zName = "main";
   97127   db->aDb[0].safety_level = 3;
   97128   db->aDb[1].zName = "temp";
   97129   db->aDb[1].safety_level = 1;
   97130 
   97131   db->magic = SQLITE_MAGIC_OPEN;
   97132   if( db->mallocFailed ){
   97133     goto opendb_out;
   97134   }
   97135 
   97136   /* Register all built-in functions, but do not attempt to read the
   97137   ** database schema yet. This is delayed until the first time the database
   97138   ** is accessed.
   97139   */
   97140   sqlite3Error(db, SQLITE_OK, 0);
   97141   sqlite3RegisterBuiltinFunctions(db);
   97142 
   97143   /* Load automatic extensions - extensions that have been registered
   97144   ** using the sqlite3_automatic_extension() API.
   97145   */
   97146   sqlite3AutoLoadExtensions(db);
   97147   rc = sqlite3_errcode(db);
   97148   if( rc!=SQLITE_OK ){
   97149     goto opendb_out;
   97150   }
   97151 
   97152 #ifdef SQLITE_ENABLE_FTS1
   97153 // Begin Android change
   97154 #error "Do not enable FTS1 on Android as FTS3_BACKWARDS has been in use"
   97155 // End Android add
   97156   if( !db->mallocFailed ){
   97157     extern int sqlite3Fts1Init(sqlite3*);
   97158     rc = sqlite3Fts1Init(db);
   97159   }
   97160 #endif
   97161 
   97162 #ifdef SQLITE_ENABLE_FTS2
   97163 // Begin Android change
   97164 #error "Do not enable FTS2 on Android as FTS3_BACKWARDS has been in use"
   97165 // End Android add
   97166   if( !db->mallocFailed && rc==SQLITE_OK ){
   97167     extern int sqlite3Fts2Init(sqlite3*);
   97168     rc = sqlite3Fts2Init(db);
   97169   }
   97170 #endif
   97171 
   97172 #ifdef SQLITE_ENABLE_FTS3
   97173   // Begin Android change
   97174   #ifdef SQLITE_ENABLE_FTS3_BACKWARDS
   97175     /* Also register as fts1 and fts2, for backwards compatability on
   97176     ** systems known to have never seen a pre-fts3 database.
   97177     */
   97178     if( !db->mallocFailed && rc==SQLITE_OK ){
   97179       rc = sqlite3Fts3Init(db, "fts1");
   97180     }
   97181 
   97182     if( !db->mallocFailed && rc==SQLITE_OK ){
   97183       rc = sqlite3Fts3Init(db, "fts2");
   97184     }
   97185   #endif
   97186 
   97187     if( !db->mallocFailed && rc==SQLITE_OK ){
   97188       rc = sqlite3Fts3Init(db, "fts3");
   97189     }
   97190   // End Android change
   97191 #endif
   97192 
   97193 #ifdef SQLITE_ENABLE_ICU
   97194   if( !db->mallocFailed && rc==SQLITE_OK ){
   97195     rc = sqlite3IcuInit(db);
   97196   }
   97197 #endif
   97198 
   97199 #ifdef SQLITE_ENABLE_RTREE
   97200   if( !db->mallocFailed && rc==SQLITE_OK){
   97201     rc = sqlite3RtreeInit(db);
   97202   }
   97203 #endif
   97204 
   97205   sqlite3Error(db, rc, 0);
   97206 
   97207   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
   97208   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
   97209   ** mode.  Doing nothing at all also makes NORMAL the default.
   97210   */
   97211 #ifdef SQLITE_DEFAULT_LOCKING_MODE
   97212   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
   97213   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
   97214                           SQLITE_DEFAULT_LOCKING_MODE);
   97215 #endif
   97216 
   97217   /* Enable the lookaside-malloc subsystem */
   97218   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
   97219                         sqlite3GlobalConfig.nLookaside);
   97220 
   97221 opendb_out:
   97222   if( db ){
   97223     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
   97224     sqlite3_mutex_leave(db->mutex);
   97225   }
   97226   rc = sqlite3_errcode(db);
   97227   if( rc==SQLITE_NOMEM ){
   97228     sqlite3_close(db);
   97229     db = 0;
   97230   }else if( rc!=SQLITE_OK ){
   97231     db->magic = SQLITE_MAGIC_SICK;
   97232   }
   97233   *ppDb = db;
   97234   return sqlite3ApiExit(0, rc);
   97235 }
   97236 
   97237 /*
   97238 ** Open a new database handle.
   97239 */
   97240 SQLITE_API int sqlite3_open(
   97241   const char *zFilename,
   97242   sqlite3 **ppDb
   97243 ){
   97244   return openDatabase(zFilename, ppDb,
   97245                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
   97246 }
   97247 SQLITE_API int sqlite3_open_v2(
   97248   const char *filename,   /* Database filename (UTF-8) */
   97249   sqlite3 **ppDb,         /* OUT: SQLite db handle */
   97250   int flags,              /* Flags */
   97251   const char *zVfs        /* Name of VFS module to use */
   97252 ){
   97253   return openDatabase(filename, ppDb, flags, zVfs);
   97254 }
   97255 
   97256 #ifndef SQLITE_OMIT_UTF16
   97257 /*
   97258 ** Open a new database handle.
   97259 */
   97260 SQLITE_API int sqlite3_open16(
   97261   const void *zFilename,
   97262   sqlite3 **ppDb
   97263 ){
   97264   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
   97265   sqlite3_value *pVal;
   97266   int rc;
   97267 
   97268   assert( zFilename );
   97269   assert( ppDb );
   97270   *ppDb = 0;
   97271 #ifndef SQLITE_OMIT_AUTOINIT
   97272   rc = sqlite3_initialize();
   97273   if( rc ) return rc;
   97274 #endif
   97275   pVal = sqlite3ValueNew(0);
   97276   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   97277   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   97278   if( zFilename8 ){
   97279     rc = openDatabase(zFilename8, ppDb,
   97280                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
   97281     assert( *ppDb || rc==SQLITE_NOMEM );
   97282     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
   97283       ENC(*ppDb) = SQLITE_UTF16NATIVE;
   97284     }
   97285   }else{
   97286     rc = SQLITE_NOMEM;
   97287   }
   97288   sqlite3ValueFree(pVal);
   97289 
   97290   return sqlite3ApiExit(0, rc);
   97291 }
   97292 #endif /* SQLITE_OMIT_UTF16 */
   97293 
   97294 /*
   97295 ** Register a new collation sequence with the database handle db.
   97296 */
   97297 SQLITE_API int sqlite3_create_collation(
   97298   sqlite3* db,
   97299   const char *zName,
   97300   int enc,
   97301   void* pCtx,
   97302   int(*xCompare)(void*,int,const void*,int,const void*)
   97303 ){
   97304   int rc;
   97305   sqlite3_mutex_enter(db->mutex);
   97306   assert( !db->mallocFailed );
   97307   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
   97308   rc = sqlite3ApiExit(db, rc);
   97309   sqlite3_mutex_leave(db->mutex);
   97310   return rc;
   97311 }
   97312 
   97313 /*
   97314 ** Register a new collation sequence with the database handle db.
   97315 */
   97316 SQLITE_API int sqlite3_create_collation_v2(
   97317   sqlite3* db,
   97318   const char *zName,
   97319   int enc,
   97320   void* pCtx,
   97321   int(*xCompare)(void*,int,const void*,int,const void*),
   97322   void(*xDel)(void*)
   97323 ){
   97324   int rc;
   97325   sqlite3_mutex_enter(db->mutex);
   97326   assert( !db->mallocFailed );
   97327   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
   97328   rc = sqlite3ApiExit(db, rc);
   97329   sqlite3_mutex_leave(db->mutex);
   97330   return rc;
   97331 }
   97332 
   97333 #ifndef SQLITE_OMIT_UTF16
   97334 /*
   97335 ** Register a new collation sequence with the database handle db.
   97336 */
   97337 SQLITE_API int sqlite3_create_collation16(
   97338   sqlite3* db,
   97339   const void *zName,
   97340   int enc,
   97341   void* pCtx,
   97342   int(*xCompare)(void*,int,const void*,int,const void*)
   97343 ){
   97344   int rc = SQLITE_OK;
   97345   char *zName8;
   97346   sqlite3_mutex_enter(db->mutex);
   97347   assert( !db->mallocFailed );
   97348   zName8 = sqlite3Utf16to8(db, zName, -1);
   97349   if( zName8 ){
   97350     rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
   97351     sqlite3DbFree(db, zName8);
   97352   }
   97353   rc = sqlite3ApiExit(db, rc);
   97354   sqlite3_mutex_leave(db->mutex);
   97355   return rc;
   97356 }
   97357 #endif /* SQLITE_OMIT_UTF16 */
   97358 
   97359 /*
   97360 ** Register a collation sequence factory callback with the database handle
   97361 ** db. Replace any previously installed collation sequence factory.
   97362 */
   97363 SQLITE_API int sqlite3_collation_needed(
   97364   sqlite3 *db,
   97365   void *pCollNeededArg,
   97366   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
   97367 ){
   97368   sqlite3_mutex_enter(db->mutex);
   97369   db->xCollNeeded = xCollNeeded;
   97370   db->xCollNeeded16 = 0;
   97371   db->pCollNeededArg = pCollNeededArg;
   97372   sqlite3_mutex_leave(db->mutex);
   97373   return SQLITE_OK;
   97374 }
   97375 
   97376 #ifndef SQLITE_OMIT_UTF16
   97377 /*
   97378 ** Register a collation sequence factory callback with the database handle
   97379 ** db. Replace any previously installed collation sequence factory.
   97380 */
   97381 SQLITE_API int sqlite3_collation_needed16(
   97382   sqlite3 *db,
   97383   void *pCollNeededArg,
   97384   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
   97385 ){
   97386   sqlite3_mutex_enter(db->mutex);
   97387   db->xCollNeeded = 0;
   97388   db->xCollNeeded16 = xCollNeeded16;
   97389   db->pCollNeededArg = pCollNeededArg;
   97390   sqlite3_mutex_leave(db->mutex);
   97391   return SQLITE_OK;
   97392 }
   97393 #endif /* SQLITE_OMIT_UTF16 */
   97394 
   97395 #ifndef SQLITE_OMIT_GLOBALRECOVER
   97396 #ifndef SQLITE_OMIT_DEPRECATED
   97397 /*
   97398 ** This function is now an anachronism. It used to be used to recover from a
   97399 ** malloc() failure, but SQLite now does this automatically.
   97400 */
   97401 SQLITE_API int sqlite3_global_recover(void){
   97402   return SQLITE_OK;
   97403 }
   97404 #endif
   97405 #endif
   97406 
   97407 /*
   97408 ** Test to see whether or not the database connection is in autocommit
   97409 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
   97410 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
   97411 ** by the next COMMIT or ROLLBACK.
   97412 **
   97413 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
   97414 */
   97415 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
   97416   return db->autoCommit;
   97417 }
   97418 
   97419 /*
   97420 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
   97421 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
   97422 ** constants.  They server two purposes:
   97423 **
   97424 **   1.  Serve as a convenient place to set a breakpoint in a debugger
   97425 **       to detect when version error conditions occurs.
   97426 **
   97427 **   2.  Invoke sqlite3_log() to provide the source code location where
   97428 **       a low-level error is first detected.
   97429 */
   97430 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
   97431   testcase( sqlite3GlobalConfig.xLog!=0 );
   97432   sqlite3_log(SQLITE_CORRUPT,
   97433               "database corruption found by source line %d", lineno);
   97434   return SQLITE_CORRUPT;
   97435 }
   97436 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
   97437   testcase( sqlite3GlobalConfig.xLog!=0 );
   97438   sqlite3_log(SQLITE_MISUSE, "misuse detected by source line %d", lineno);
   97439   return SQLITE_MISUSE;
   97440 }
   97441 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
   97442   testcase( sqlite3GlobalConfig.xLog!=0 );
   97443   sqlite3_log(SQLITE_CANTOPEN, "cannot open file at source line %d", lineno);
   97444   return SQLITE_CANTOPEN;
   97445 }
   97446 
   97447 
   97448 #ifndef SQLITE_OMIT_DEPRECATED
   97449 /*
   97450 ** This is a convenience routine that makes sure that all thread-specific
   97451 ** data for this thread has been deallocated.
   97452 **
   97453 ** SQLite no longer uses thread-specific data so this routine is now a
   97454 ** no-op.  It is retained for historical compatibility.
   97455 */
   97456 SQLITE_API void sqlite3_thread_cleanup(void){
   97457 }
   97458 #endif
   97459 
   97460 /*
   97461 ** Return meta information about a specific column of a database table.
   97462 ** See comment in sqlite3.h (sqlite.h.in) for details.
   97463 */
   97464 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   97465 SQLITE_API int sqlite3_table_column_metadata(
   97466   sqlite3 *db,                /* Connection handle */
   97467   const char *zDbName,        /* Database name or NULL */
   97468   const char *zTableName,     /* Table name */
   97469   const char *zColumnName,    /* Column name */
   97470   char const **pzDataType,    /* OUTPUT: Declared data type */
   97471   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
   97472   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
   97473   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
   97474   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
   97475 ){
   97476   int rc;
   97477   char *zErrMsg = 0;
   97478   Table *pTab = 0;
   97479   Column *pCol = 0;
   97480   int iCol;
   97481 
   97482   char const *zDataType = 0;
   97483   char const *zCollSeq = 0;
   97484   int notnull = 0;
   97485   int primarykey = 0;
   97486   int autoinc = 0;
   97487 
   97488   /* Ensure the database schema has been loaded */
   97489   sqlite3_mutex_enter(db->mutex);
   97490   sqlite3BtreeEnterAll(db);
   97491   rc = sqlite3Init(db, &zErrMsg);
   97492   if( SQLITE_OK!=rc ){
   97493     goto error_out;
   97494   }
   97495 
   97496   /* Locate the table in question */
   97497   pTab = sqlite3FindTable(db, zTableName, zDbName);
   97498   if( !pTab || pTab->pSelect ){
   97499     pTab = 0;
   97500     goto error_out;
   97501   }
   97502 
   97503   /* Find the column for which info is requested */
   97504   if( sqlite3IsRowid(zColumnName) ){
   97505     iCol = pTab->iPKey;
   97506     if( iCol>=0 ){
   97507       pCol = &pTab->aCol[iCol];
   97508     }
   97509   }else{
   97510     for(iCol=0; iCol<pTab->nCol; iCol++){
   97511       pCol = &pTab->aCol[iCol];
   97512       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
   97513         break;
   97514       }
   97515     }
   97516     if( iCol==pTab->nCol ){
   97517       pTab = 0;
   97518       goto error_out;
   97519     }
   97520   }
   97521 
   97522   /* The following block stores the meta information that will be returned
   97523   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
   97524   ** and autoinc. At this point there are two possibilities:
   97525   **
   97526   **     1. The specified column name was rowid", "oid" or "_rowid_"
   97527   **        and there is no explicitly declared IPK column.
   97528   **
   97529   **     2. The table is not a view and the column name identified an
   97530   **        explicitly declared column. Copy meta information from *pCol.
   97531   */
   97532   if( pCol ){
   97533     zDataType = pCol->zType;
   97534     zCollSeq = pCol->zColl;
   97535     notnull = pCol->notNull!=0;
   97536     primarykey  = pCol->isPrimKey!=0;
   97537     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
   97538   }else{
   97539     zDataType = "INTEGER";
   97540     primarykey = 1;
   97541   }
   97542   if( !zCollSeq ){
   97543     zCollSeq = "BINARY";
   97544   }
   97545 
   97546 error_out:
   97547   sqlite3BtreeLeaveAll(db);
   97548 
   97549   /* Whether the function call succeeded or failed, set the output parameters
   97550   ** to whatever their local counterparts contain. If an error did occur,
   97551   ** this has the effect of zeroing all output parameters.
   97552   */
   97553   if( pzDataType ) *pzDataType = zDataType;
   97554   if( pzCollSeq ) *pzCollSeq = zCollSeq;
   97555   if( pNotNull ) *pNotNull = notnull;
   97556   if( pPrimaryKey ) *pPrimaryKey = primarykey;
   97557   if( pAutoinc ) *pAutoinc = autoinc;
   97558 
   97559   if( SQLITE_OK==rc && !pTab ){
   97560     sqlite3DbFree(db, zErrMsg);
   97561     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
   97562         zColumnName);
   97563     rc = SQLITE_ERROR;
   97564   }
   97565   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
   97566   sqlite3DbFree(db, zErrMsg);
   97567   rc = sqlite3ApiExit(db, rc);
   97568   sqlite3_mutex_leave(db->mutex);
   97569   return rc;
   97570 }
   97571 #endif
   97572 
   97573 /*
   97574 ** Sleep for a little while.  Return the amount of time slept.
   97575 */
   97576 SQLITE_API int sqlite3_sleep(int ms){
   97577   sqlite3_vfs *pVfs;
   97578   int rc;
   97579   pVfs = sqlite3_vfs_find(0);
   97580   if( pVfs==0 ) return 0;
   97581 
   97582   /* This function works in milliseconds, but the underlying OsSleep()
   97583   ** API uses microseconds. Hence the 1000's.
   97584   */
   97585   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
   97586   return rc;
   97587 }
   97588 
   97589 /*
   97590 ** Enable or disable the extended result codes.
   97591 */
   97592 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
   97593   sqlite3_mutex_enter(db->mutex);
   97594   db->errMask = onoff ? 0xffffffff : 0xff;
   97595   sqlite3_mutex_leave(db->mutex);
   97596   return SQLITE_OK;
   97597 }
   97598 
   97599 /*
   97600 ** Invoke the xFileControl method on a particular database.
   97601 */
   97602 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
   97603   int rc = SQLITE_ERROR;
   97604   int iDb;
   97605   sqlite3_mutex_enter(db->mutex);
   97606   if( zDbName==0 ){
   97607     iDb = 0;
   97608   }else{
   97609     for(iDb=0; iDb<db->nDb; iDb++){
   97610       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
   97611     }
   97612   }
   97613   if( iDb<db->nDb ){
   97614     Btree *pBtree = db->aDb[iDb].pBt;
   97615     if( pBtree ){
   97616       Pager *pPager;
   97617       sqlite3_file *fd;
   97618       sqlite3BtreeEnter(pBtree);
   97619       pPager = sqlite3BtreePager(pBtree);
   97620       assert( pPager!=0 );
   97621       fd = sqlite3PagerFile(pPager);
   97622       assert( fd!=0 );
   97623       if( fd->pMethods ){
   97624         rc = sqlite3OsFileControl(fd, op, pArg);
   97625       }
   97626       sqlite3BtreeLeave(pBtree);
   97627     }
   97628   }
   97629   sqlite3_mutex_leave(db->mutex);
   97630   return rc;
   97631 }
   97632 
   97633 /*
   97634 ** Interface to the testing logic.
   97635 */
   97636 SQLITE_API int sqlite3_test_control(int op, ...){
   97637   int rc = 0;
   97638 #ifndef SQLITE_OMIT_BUILTIN_TEST
   97639   va_list ap;
   97640   va_start(ap, op);
   97641   switch( op ){
   97642 
   97643     /*
   97644     ** Save the current state of the PRNG.
   97645     */
   97646     case SQLITE_TESTCTRL_PRNG_SAVE: {
   97647       sqlite3PrngSaveState();
   97648       break;
   97649     }
   97650 
   97651     /*
   97652     ** Restore the state of the PRNG to the last state saved using
   97653     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
   97654     ** this verb acts like PRNG_RESET.
   97655     */
   97656     case SQLITE_TESTCTRL_PRNG_RESTORE: {
   97657       sqlite3PrngRestoreState();
   97658       break;
   97659     }
   97660 
   97661     /*
   97662     ** Reset the PRNG back to its uninitialized state.  The next call
   97663     ** to sqlite3_randomness() will reseed the PRNG using a single call
   97664     ** to the xRandomness method of the default VFS.
   97665     */
   97666     case SQLITE_TESTCTRL_PRNG_RESET: {
   97667       sqlite3PrngResetState();
   97668       break;
   97669     }
   97670 
   97671     /*
   97672     **  sqlite3_test_control(BITVEC_TEST, size, program)
   97673     **
   97674     ** Run a test against a Bitvec object of size.  The program argument
   97675     ** is an array of integers that defines the test.  Return -1 on a
   97676     ** memory allocation error, 0 on success, or non-zero for an error.
   97677     ** See the sqlite3BitvecBuiltinTest() for additional information.
   97678     */
   97679     case SQLITE_TESTCTRL_BITVEC_TEST: {
   97680       int sz = va_arg(ap, int);
   97681       int *aProg = va_arg(ap, int*);
   97682       rc = sqlite3BitvecBuiltinTest(sz, aProg);
   97683       break;
   97684     }
   97685 
   97686     /*
   97687     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
   97688     **
   97689     ** Register hooks to call to indicate which malloc() failures
   97690     ** are benign.
   97691     */
   97692     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
   97693       typedef void (*void_function)(void);
   97694       void_function xBenignBegin;
   97695       void_function xBenignEnd;
   97696       xBenignBegin = va_arg(ap, void_function);
   97697       xBenignEnd = va_arg(ap, void_function);
   97698       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
   97699       break;
   97700     }
   97701 
   97702     /*
   97703     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
   97704     **
   97705     ** Set the PENDING byte to the value in the argument, if X>0.
   97706     ** Make no changes if X==0.  Return the value of the pending byte
   97707     ** as it existing before this routine was called.
   97708     **
   97709     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
   97710     ** an incompatible database file format.  Changing the PENDING byte
   97711     ** while any database connection is open results in undefined and
   97712     ** dileterious behavior.
   97713     */
   97714     case SQLITE_TESTCTRL_PENDING_BYTE: {
   97715       unsigned int newVal = va_arg(ap, unsigned int);
   97716       rc = sqlite3PendingByte;
   97717       if( newVal ) sqlite3PendingByte = newVal;
   97718       break;
   97719     }
   97720 
   97721     /*
   97722     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
   97723     **
   97724     ** This action provides a run-time test to see whether or not
   97725     ** assert() was enabled at compile-time.  If X is true and assert()
   97726     ** is enabled, then the return value is true.  If X is true and
   97727     ** assert() is disabled, then the return value is zero.  If X is
   97728     ** false and assert() is enabled, then the assertion fires and the
   97729     ** process aborts.  If X is false and assert() is disabled, then the
   97730     ** return value is zero.
   97731     */
   97732     case SQLITE_TESTCTRL_ASSERT: {
   97733       volatile int x = 0;
   97734       assert( (x = va_arg(ap,int))!=0 );
   97735       rc = x;
   97736       break;
   97737     }
   97738 
   97739 
   97740     /*
   97741     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
   97742     **
   97743     ** This action provides a run-time test to see how the ALWAYS and
   97744     ** NEVER macros were defined at compile-time.
   97745     **
   97746     ** The return value is ALWAYS(X).
   97747     **
   97748     ** The recommended test is X==2.  If the return value is 2, that means
   97749     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
   97750     ** default setting.  If the return value is 1, then ALWAYS() is either
   97751     ** hard-coded to true or else it asserts if its argument is false.
   97752     ** The first behavior (hard-coded to true) is the case if
   97753     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
   97754     ** behavior (assert if the argument to ALWAYS() is false) is the case if
   97755     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
   97756     **
   97757     ** The run-time test procedure might look something like this:
   97758     **
   97759     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
   97760     **      // ALWAYS() and NEVER() are no-op pass-through macros
   97761     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
   97762     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
   97763     **    }else{
   97764     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
   97765     **    }
   97766     */
   97767     case SQLITE_TESTCTRL_ALWAYS: {
   97768       int x = va_arg(ap,int);
   97769       rc = ALWAYS(x);
   97770       break;
   97771     }
   97772 
   97773     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
   97774     **
   97775     ** Set the nReserve size to N for the main database on the database
   97776     ** connection db.
   97777     */
   97778     case SQLITE_TESTCTRL_RESERVE: {
   97779       sqlite3 *db = va_arg(ap, sqlite3*);
   97780       int x = va_arg(ap,int);
   97781       sqlite3_mutex_enter(db->mutex);
   97782       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
   97783       sqlite3_mutex_leave(db->mutex);
   97784       break;
   97785     }
   97786 
   97787     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
   97788     **
   97789     ** Enable or disable various optimizations for testing purposes.  The
   97790     ** argument N is a bitmask of optimizations to be disabled.  For normal
   97791     ** operation N should be 0.  The idea is that a test program (like the
   97792     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
   97793     ** with various optimizations disabled to verify that the same answer
   97794     ** is obtained in every case.
   97795     */
   97796     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
   97797       sqlite3 *db = va_arg(ap, sqlite3*);
   97798       int x = va_arg(ap,int);
   97799       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
   97800       break;
   97801     }
   97802 
   97803 #ifdef SQLITE_N_KEYWORD
   97804     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
   97805     **
   97806     ** If zWord is a keyword recognized by the parser, then return the
   97807     ** number of keywords.  Or if zWord is not a keyword, return 0.
   97808     **
   97809     ** This test feature is only available in the amalgamation since
   97810     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
   97811     ** is built using separate source files.
   97812     */
   97813     case SQLITE_TESTCTRL_ISKEYWORD: {
   97814       const char *zWord = va_arg(ap, const char*);
   97815       int n = sqlite3Strlen30(zWord);
   97816       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
   97817       break;
   97818     }
   97819 #endif
   97820 
   97821   }
   97822   va_end(ap);
   97823 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   97824   return rc;
   97825 }
   97826 
   97827 /************** End of main.c ************************************************/
   97828 /************** Begin file notify.c ******************************************/
   97829 /*
   97830 ** 2009 March 3
   97831 **
   97832 ** The author disclaims copyright to this source code.  In place of
   97833 ** a legal notice, here is a blessing:
   97834 **
   97835 **    May you do good and not evil.
   97836 **    May you find forgiveness for yourself and forgive others.
   97837 **    May you share freely, never taking more than you give.
   97838 **
   97839 *************************************************************************
   97840 **
   97841 ** This file contains the implementation of the sqlite3_unlock_notify()
   97842 ** API method and its associated functionality.
   97843 */
   97844 
   97845 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
   97846 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   97847 
   97848 /*
   97849 ** Public interfaces:
   97850 **
   97851 **   sqlite3ConnectionBlocked()
   97852 **   sqlite3ConnectionUnlocked()
   97853 **   sqlite3ConnectionClosed()
   97854 **   sqlite3_unlock_notify()
   97855 */
   97856 
   97857 #define assertMutexHeld() \
   97858   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
   97859 
   97860 /*
   97861 ** Head of a linked list of all sqlite3 objects created by this process
   97862 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
   97863 ** is not NULL. This variable may only accessed while the STATIC_MASTER
   97864 ** mutex is held.
   97865 */
   97866 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
   97867 
   97868 #ifndef NDEBUG
   97869 /*
   97870 ** This function is a complex assert() that verifies the following
   97871 ** properties of the blocked connections list:
   97872 **
   97873 **   1) Each entry in the list has a non-NULL value for either
   97874 **      pUnlockConnection or pBlockingConnection, or both.
   97875 **
   97876 **   2) All entries in the list that share a common value for
   97877 **      xUnlockNotify are grouped together.
   97878 **
   97879 **   3) If the argument db is not NULL, then none of the entries in the
   97880 **      blocked connections list have pUnlockConnection or pBlockingConnection
   97881 **      set to db. This is used when closing connection db.
   97882 */
   97883 static void checkListProperties(sqlite3 *db){
   97884   sqlite3 *p;
   97885   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
   97886     int seen = 0;
   97887     sqlite3 *p2;
   97888 
   97889     /* Verify property (1) */
   97890     assert( p->pUnlockConnection || p->pBlockingConnection );
   97891 
   97892     /* Verify property (2) */
   97893     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
   97894       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
   97895       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
   97896       assert( db==0 || p->pUnlockConnection!=db );
   97897       assert( db==0 || p->pBlockingConnection!=db );
   97898     }
   97899   }
   97900 }
   97901 #else
   97902 # define checkListProperties(x)
   97903 #endif
   97904 
   97905 /*
   97906 ** Remove connection db from the blocked connections list. If connection
   97907 ** db is not currently a part of the list, this function is a no-op.
   97908 */
   97909 static void removeFromBlockedList(sqlite3 *db){
   97910   sqlite3 **pp;
   97911   assertMutexHeld();
   97912   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
   97913     if( *pp==db ){
   97914       *pp = (*pp)->pNextBlocked;
   97915       break;
   97916     }
   97917   }
   97918 }
   97919 
   97920 /*
   97921 ** Add connection db to the blocked connections list. It is assumed
   97922 ** that it is not already a part of the list.
   97923 */
   97924 static void addToBlockedList(sqlite3 *db){
   97925   sqlite3 **pp;
   97926   assertMutexHeld();
   97927   for(
   97928     pp=&sqlite3BlockedList;
   97929     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
   97930     pp=&(*pp)->pNextBlocked
   97931   );
   97932   db->pNextBlocked = *pp;
   97933   *pp = db;
   97934 }
   97935 
   97936 /*
   97937 ** Obtain the STATIC_MASTER mutex.
   97938 */
   97939 static void enterMutex(void){
   97940   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   97941   checkListProperties(0);
   97942 }
   97943 
   97944 /*
   97945 ** Release the STATIC_MASTER mutex.
   97946 */
   97947 static void leaveMutex(void){
   97948   assertMutexHeld();
   97949   checkListProperties(0);
   97950   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   97951 }
   97952 
   97953 /*
   97954 ** Register an unlock-notify callback.
   97955 **
   97956 ** This is called after connection "db" has attempted some operation
   97957 ** but has received an SQLITE_LOCKED error because another connection
   97958 ** (call it pOther) in the same process was busy using the same shared
   97959 ** cache.  pOther is found by looking at db->pBlockingConnection.
   97960 **
   97961 ** If there is no blocking connection, the callback is invoked immediately,
   97962 ** before this routine returns.
   97963 **
   97964 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
   97965 ** a deadlock.
   97966 **
   97967 ** Otherwise, make arrangements to invoke xNotify when pOther drops
   97968 ** its locks.
   97969 **
   97970 ** Each call to this routine overrides any prior callbacks registered
   97971 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
   97972 ** cancelled.
   97973 */
   97974 SQLITE_API int sqlite3_unlock_notify(
   97975   sqlite3 *db,
   97976   void (*xNotify)(void **, int),
   97977   void *pArg
   97978 ){
   97979   int rc = SQLITE_OK;
   97980 
   97981   sqlite3_mutex_enter(db->mutex);
   97982   enterMutex();
   97983 
   97984   if( xNotify==0 ){
   97985     removeFromBlockedList(db);
   97986     db->pUnlockConnection = 0;
   97987     db->xUnlockNotify = 0;
   97988     db->pUnlockArg = 0;
   97989   }else if( 0==db->pBlockingConnection ){
   97990     /* The blocking transaction has been concluded. Or there never was a
   97991     ** blocking transaction. In either case, invoke the notify callback
   97992     ** immediately.
   97993     */
   97994     xNotify(&pArg, 1);
   97995   }else{
   97996     sqlite3 *p;
   97997 
   97998     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
   97999     if( p ){
   98000       rc = SQLITE_LOCKED;              /* Deadlock detected. */
   98001     }else{
   98002       db->pUnlockConnection = db->pBlockingConnection;
   98003       db->xUnlockNotify = xNotify;
   98004       db->pUnlockArg = pArg;
   98005       removeFromBlockedList(db);
   98006       addToBlockedList(db);
   98007     }
   98008   }
   98009 
   98010   leaveMutex();
   98011   assert( !db->mallocFailed );
   98012   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
   98013   sqlite3_mutex_leave(db->mutex);
   98014   return rc;
   98015 }
   98016 
   98017 /*
   98018 ** This function is called while stepping or preparing a statement
   98019 ** associated with connection db. The operation will return SQLITE_LOCKED
   98020 ** to the user because it requires a lock that will not be available
   98021 ** until connection pBlocker concludes its current transaction.
   98022 */
   98023 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
   98024   enterMutex();
   98025   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
   98026     addToBlockedList(db);
   98027   }
   98028   db->pBlockingConnection = pBlocker;
   98029   leaveMutex();
   98030 }
   98031 
   98032 /*
   98033 ** This function is called when
   98034 ** the transaction opened by database db has just finished. Locks held
   98035 ** by database connection db have been released.
   98036 **
   98037 ** This function loops through each entry in the blocked connections
   98038 ** list and does the following:
   98039 **
   98040 **   1) If the sqlite3.pBlockingConnection member of a list entry is
   98041 **      set to db, then set pBlockingConnection=0.
   98042 **
   98043 **   2) If the sqlite3.pUnlockConnection member of a list entry is
   98044 **      set to db, then invoke the configured unlock-notify callback and
   98045 **      set pUnlockConnection=0.
   98046 **
   98047 **   3) If the two steps above mean that pBlockingConnection==0 and
   98048 **      pUnlockConnection==0, remove the entry from the blocked connections
   98049 **      list.
   98050 */
   98051 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
   98052   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
   98053   int nArg = 0;                            /* Number of entries in aArg[] */
   98054   sqlite3 **pp;                            /* Iterator variable */
   98055   void **aArg;               /* Arguments to the unlock callback */
   98056   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
   98057   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
   98058 
   98059   aArg = aStatic;
   98060   enterMutex();         /* Enter STATIC_MASTER mutex */
   98061 
   98062   /* This loop runs once for each entry in the blocked-connections list. */
   98063   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
   98064     sqlite3 *p = *pp;
   98065 
   98066     /* Step 1. */
   98067     if( p->pBlockingConnection==db ){
   98068       p->pBlockingConnection = 0;
   98069     }
   98070 
   98071     /* Step 2. */
   98072     if( p->pUnlockConnection==db ){
   98073       assert( p->xUnlockNotify );
   98074       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
   98075         xUnlockNotify(aArg, nArg);
   98076         nArg = 0;
   98077       }
   98078 
   98079       sqlite3BeginBenignMalloc();
   98080       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
   98081       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
   98082       if( (!aDyn && nArg==(int)ArraySize(aStatic))
   98083        || (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*)))
   98084       ){
   98085         /* The aArg[] array needs to grow. */
   98086         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
   98087         if( pNew ){
   98088           memcpy(pNew, aArg, nArg*sizeof(void *));
   98089           sqlite3_free(aDyn);
   98090           aDyn = aArg = pNew;
   98091         }else{
   98092           /* This occurs when the array of context pointers that need to
   98093           ** be passed to the unlock-notify callback is larger than the
   98094           ** aStatic[] array allocated on the stack and the attempt to
   98095           ** allocate a larger array from the heap has failed.
   98096           **
   98097           ** This is a difficult situation to handle. Returning an error
   98098           ** code to the caller is insufficient, as even if an error code
   98099           ** is returned the transaction on connection db will still be
   98100           ** closed and the unlock-notify callbacks on blocked connections
   98101           ** will go unissued. This might cause the application to wait
   98102           ** indefinitely for an unlock-notify callback that will never
   98103           ** arrive.
   98104           **
   98105           ** Instead, invoke the unlock-notify callback with the context
   98106           ** array already accumulated. We can then clear the array and
   98107           ** begin accumulating any further context pointers without
   98108           ** requiring any dynamic allocation. This is sub-optimal because
   98109           ** it means that instead of one callback with a large array of
   98110           ** context pointers the application will receive two or more
   98111           ** callbacks with smaller arrays of context pointers, which will
   98112           ** reduce the applications ability to prioritize multiple
   98113           ** connections. But it is the best that can be done under the
   98114           ** circumstances.
   98115           */
   98116           xUnlockNotify(aArg, nArg);
   98117           nArg = 0;
   98118         }
   98119       }
   98120       sqlite3EndBenignMalloc();
   98121 
   98122       aArg[nArg++] = p->pUnlockArg;
   98123       xUnlockNotify = p->xUnlockNotify;
   98124       p->pUnlockConnection = 0;
   98125       p->xUnlockNotify = 0;
   98126       p->pUnlockArg = 0;
   98127     }
   98128 
   98129     /* Step 3. */
   98130     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
   98131       /* Remove connection p from the blocked connections list. */
   98132       *pp = p->pNextBlocked;
   98133       p->pNextBlocked = 0;
   98134     }else{
   98135       pp = &p->pNextBlocked;
   98136     }
   98137   }
   98138 
   98139   if( nArg!=0 ){
   98140     xUnlockNotify(aArg, nArg);
   98141   }
   98142   sqlite3_free(aDyn);
   98143   leaveMutex();         /* Leave STATIC_MASTER mutex */
   98144 }
   98145 
   98146 /*
   98147 ** This is called when the database connection passed as an argument is
   98148 ** being closed. The connection is removed from the blocked list.
   98149 */
   98150 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
   98151   sqlite3ConnectionUnlocked(db);
   98152   enterMutex();
   98153   removeFromBlockedList(db);
   98154   checkListProperties(db);
   98155   leaveMutex();
   98156 }
   98157 #endif
   98158 
   98159 /************** End of notify.c **********************************************/
   98160 /************** Begin file fts3.c ********************************************/
   98161 /*
   98162 ** 2006 Oct 10
   98163 **
   98164 ** The author disclaims copyright to this source code.  In place of
   98165 ** a legal notice, here is a blessing:
   98166 **
   98167 **    May you do good and not evil.
   98168 **    May you find forgiveness for yourself and forgive others.
   98169 **    May you share freely, never taking more than you give.
   98170 **
   98171 ******************************************************************************
   98172 **
   98173 ** This is an SQLite module implementing full-text search.
   98174 */
   98175 
   98176 /*
   98177 ** The code in this file is only compiled if:
   98178 **
   98179 **     * The FTS3 module is being built as an extension
   98180 **       (in which case SQLITE_CORE is not defined), or
   98181 **
   98182 **     * The FTS3 module is being built into the core of
   98183 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   98184 */
   98185 
   98186 /* TODO(shess) Consider exporting this comment to an HTML file or the
   98187 ** wiki.
   98188 */
   98189 /* The full-text index is stored in a series of b+tree (-like)
   98190 ** structures called segments which map terms to doclists.  The
   98191 ** structures are like b+trees in layout, but are constructed from the
   98192 ** bottom up in optimal fashion and are not updatable.  Since trees
   98193 ** are built from the bottom up, things will be described from the
   98194 ** bottom up.
   98195 **
   98196 **
   98197 **** Varints ****
   98198 ** The basic unit of encoding is a variable-length integer called a
   98199 ** varint.  We encode variable-length integers in little-endian order
   98200 ** using seven bits * per byte as follows:
   98201 **
   98202 ** KEY:
   98203 **         A = 0xxxxxxx    7 bits of data and one flag bit
   98204 **         B = 1xxxxxxx    7 bits of data and one flag bit
   98205 **
   98206 **  7 bits - A
   98207 ** 14 bits - BA
   98208 ** 21 bits - BBA
   98209 ** and so on.
   98210 **
   98211 ** This is identical to how sqlite encodes varints (see util.c).
   98212 **
   98213 **
   98214 **** Document lists ****
   98215 ** A doclist (document list) holds a docid-sorted list of hits for a
   98216 ** given term.  Doclists hold docids, and can optionally associate
   98217 ** token positions and offsets with docids.
   98218 **
   98219 ** A DL_POSITIONS_OFFSETS doclist is stored like this:
   98220 **
   98221 ** array {
   98222 **   varint docid;
   98223 **   array {                (position list for column 0)
   98224 **     varint position;     (delta from previous position plus POS_BASE)
   98225 **     varint startOffset;  (delta from previous startOffset)
   98226 **     varint endOffset;    (delta from startOffset)
   98227 **   }
   98228 **   array {
   98229 **     varint POS_COLUMN;   (marks start of position list for new column)
   98230 **     varint column;       (index of new column)
   98231 **     array {
   98232 **       varint position;   (delta from previous position plus POS_BASE)
   98233 **       varint startOffset;(delta from previous startOffset)
   98234 **       varint endOffset;  (delta from startOffset)
   98235 **     }
   98236 **   }
   98237 **   varint POS_END;        (marks end of positions for this document.
   98238 ** }
   98239 **
   98240 ** Here, array { X } means zero or more occurrences of X, adjacent in
   98241 ** memory.  A "position" is an index of a token in the token stream
   98242 ** generated by the tokenizer, while an "offset" is a byte offset,
   98243 ** both based at 0.  Note that POS_END and POS_COLUMN occur in the
   98244 ** same logical place as the position element, and act as sentinals
   98245 ** ending a position list array.
   98246 **
   98247 ** A DL_POSITIONS doclist omits the startOffset and endOffset
   98248 ** information.  A DL_DOCIDS doclist omits both the position and
   98249 ** offset information, becoming an array of varint-encoded docids.
   98250 **
   98251 ** On-disk data is stored as type DL_DEFAULT, so we don't serialize
   98252 ** the type.  Due to how deletion is implemented in the segmentation
   98253 ** system, on-disk doclists MUST store at least positions.
   98254 **
   98255 **
   98256 **** Segment leaf nodes ****
   98257 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
   98258 ** nodes are written using LeafWriter, and read using LeafReader (to
   98259 ** iterate through a single leaf node's data) and LeavesReader (to
   98260 ** iterate through a segment's entire leaf layer).  Leaf nodes have
   98261 ** the format:
   98262 **
   98263 ** varint iHeight;             (height from leaf level, always 0)
   98264 ** varint nTerm;               (length of first term)
   98265 ** char pTerm[nTerm];          (content of first term)
   98266 ** varint nDoclist;            (length of term's associated doclist)
   98267 ** char pDoclist[nDoclist];    (content of doclist)
   98268 ** array {
   98269 **                             (further terms are delta-encoded)
   98270 **   varint nPrefix;           (length of prefix shared with previous term)
   98271 **   varint nSuffix;           (length of unshared suffix)
   98272 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
   98273 **   varint nDoclist;          (length of term's associated doclist)
   98274 **   char pDoclist[nDoclist];  (content of doclist)
   98275 ** }
   98276 **
   98277 ** Here, array { X } means zero or more occurrences of X, adjacent in
   98278 ** memory.
   98279 **
   98280 ** Leaf nodes are broken into blocks which are stored contiguously in
   98281 ** the %_segments table in sorted order.  This means that when the end
   98282 ** of a node is reached, the next term is in the node with the next
   98283 ** greater node id.
   98284 **
   98285 ** New data is spilled to a new leaf node when the current node
   98286 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
   98287 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
   98288 ** node (a leaf node with a single term and doclist).  The goal of
   98289 ** these settings is to pack together groups of small doclists while
   98290 ** making it efficient to directly access large doclists.  The
   98291 ** assumption is that large doclists represent terms which are more
   98292 ** likely to be query targets.
   98293 **
   98294 ** TODO(shess) It may be useful for blocking decisions to be more
   98295 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
   98296 ** node rather than splitting into 2k and .5k nodes.  My intuition is
   98297 ** that this might extend through 2x or 4x the pagesize.
   98298 **
   98299 **
   98300 **** Segment interior nodes ****
   98301 ** Segment interior nodes store blockids for subtree nodes and terms
   98302 ** to describe what data is stored by the each subtree.  Interior
   98303 ** nodes are written using InteriorWriter, and read using
   98304 ** InteriorReader.  InteriorWriters are created as needed when
   98305 ** SegmentWriter creates new leaf nodes, or when an interior node
   98306 ** itself grows too big and must be split.  The format of interior
   98307 ** nodes:
   98308 **
   98309 ** varint iHeight;           (height from leaf level, always >0)
   98310 ** varint iBlockid;          (block id of node's leftmost subtree)
   98311 ** optional {
   98312 **   varint nTerm;           (length of first term)
   98313 **   char pTerm[nTerm];      (content of first term)
   98314 **   array {
   98315 **                                (further terms are delta-encoded)
   98316 **     varint nPrefix;            (length of shared prefix with previous term)
   98317 **     varint nSuffix;            (length of unshared suffix)
   98318 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
   98319 **   }
   98320 ** }
   98321 **
   98322 ** Here, optional { X } means an optional element, while array { X }
   98323 ** means zero or more occurrences of X, adjacent in memory.
   98324 **
   98325 ** An interior node encodes n terms separating n+1 subtrees.  The
   98326 ** subtree blocks are contiguous, so only the first subtree's blockid
   98327 ** is encoded.  The subtree at iBlockid will contain all terms less
   98328 ** than the first term encoded (or all terms if no term is encoded).
   98329 ** Otherwise, for terms greater than or equal to pTerm[i] but less
   98330 ** than pTerm[i+1], the subtree for that term will be rooted at
   98331 ** iBlockid+i.  Interior nodes only store enough term data to
   98332 ** distinguish adjacent children (if the rightmost term of the left
   98333 ** child is "something", and the leftmost term of the right child is
   98334 ** "wicked", only "w" is stored).
   98335 **
   98336 ** New data is spilled to a new interior node at the same height when
   98337 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
   98338 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
   98339 ** interior nodes and making the tree too skinny.  The interior nodes
   98340 ** at a given height are naturally tracked by interior nodes at
   98341 ** height+1, and so on.
   98342 **
   98343 **
   98344 **** Segment directory ****
   98345 ** The segment directory in table %_segdir stores meta-information for
   98346 ** merging and deleting segments, and also the root node of the
   98347 ** segment's tree.
   98348 **
   98349 ** The root node is the top node of the segment's tree after encoding
   98350 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
   98351 ** This could be either a leaf node or an interior node.  If the top
   98352 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
   98353 ** and a new root interior node is generated (which should always fit
   98354 ** within ROOT_MAX because it only needs space for 2 varints, the
   98355 ** height and the blockid of the previous root).
   98356 **
   98357 ** The meta-information in the segment directory is:
   98358 **   level               - segment level (see below)
   98359 **   idx                 - index within level
   98360 **                       - (level,idx uniquely identify a segment)
   98361 **   start_block         - first leaf node
   98362 **   leaves_end_block    - last leaf node
   98363 **   end_block           - last block (including interior nodes)
   98364 **   root                - contents of root node
   98365 **
   98366 ** If the root node is a leaf node, then start_block,
   98367 ** leaves_end_block, and end_block are all 0.
   98368 **
   98369 **
   98370 **** Segment merging ****
   98371 ** To amortize update costs, segments are grouped into levels and
   98372 ** merged in batches.  Each increase in level represents exponentially
   98373 ** more documents.
   98374 **
   98375 ** New documents (actually, document updates) are tokenized and
   98376 ** written individually (using LeafWriter) to a level 0 segment, with
   98377 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
   98378 ** level 0 segments are merged into a single level 1 segment.  Level 1
   98379 ** is populated like level 0, and eventually MERGE_COUNT level 1
   98380 ** segments are merged to a single level 2 segment (representing
   98381 ** MERGE_COUNT^2 updates), and so on.
   98382 **
   98383 ** A segment merge traverses all segments at a given level in
   98384 ** parallel, performing a straightforward sorted merge.  Since segment
   98385 ** leaf nodes are written in to the %_segments table in order, this
   98386 ** merge traverses the underlying sqlite disk structures efficiently.
   98387 ** After the merge, all segment blocks from the merged level are
   98388 ** deleted.
   98389 **
   98390 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
   98391 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
   98392 ** very similar performance numbers to 16 on insertion, though they're
   98393 ** a tiny bit slower (perhaps due to more overhead in merge-time
   98394 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
   98395 ** 16, 2 about 66% slower than 16.
   98396 **
   98397 ** At query time, high MERGE_COUNT increases the number of segments
   98398 ** which need to be scanned and merged.  For instance, with 100k docs
   98399 ** inserted:
   98400 **
   98401 **    MERGE_COUNT   segments
   98402 **       16           25
   98403 **        8           12
   98404 **        4           10
   98405 **        2            6
   98406 **
   98407 ** This appears to have only a moderate impact on queries for very
   98408 ** frequent terms (which are somewhat dominated by segment merge
   98409 ** costs), and infrequent and non-existent terms still seem to be fast
   98410 ** even with many segments.
   98411 **
   98412 ** TODO(shess) That said, it would be nice to have a better query-side
   98413 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
   98414 ** optimizations to things like doclist merging will swing the sweet
   98415 ** spot around.
   98416 **
   98417 **
   98418 **
   98419 **** Handling of deletions and updates ****
   98420 ** Since we're using a segmented structure, with no docid-oriented
   98421 ** index into the term index, we clearly cannot simply update the term
   98422 ** index when a document is deleted or updated.  For deletions, we
   98423 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
   98424 ** we simply write the new doclist.  Segment merges overwrite older
   98425 ** data for a particular docid with newer data, so deletes or updates
   98426 ** will eventually overtake the earlier data and knock it out.  The
   98427 ** query logic likewise merges doclists so that newer data knocks out
   98428 ** older data.
   98429 **
   98430 ** TODO(shess) Provide a VACUUM type operation to clear out all
   98431 ** deletions and duplications.  This would basically be a forced merge
   98432 ** into a single segment.
   98433 */
   98434 
   98435 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   98436 
   98437 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
   98438 # define SQLITE_CORE 1
   98439 #endif
   98440 
   98441 /************** Include fts3Int.h in the middle of fts3.c ********************/
   98442 /************** Begin file fts3Int.h *****************************************/
   98443 /*
   98444 ** 2009 Nov 12
   98445 **
   98446 ** The author disclaims copyright to this source code.  In place of
   98447 ** a legal notice, here is a blessing:
   98448 **
   98449 **    May you do good and not evil.
   98450 **    May you find forgiveness for yourself and forgive others.
   98451 **    May you share freely, never taking more than you give.
   98452 **
   98453 ******************************************************************************
   98454 **
   98455 */
   98456 
   98457 #ifndef _FTSINT_H
   98458 #define _FTSINT_H
   98459 
   98460 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   98461 # define NDEBUG 1
   98462 #endif
   98463 
   98464 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
   98465 /************** Begin file fts3_tokenizer.h **********************************/
   98466 /*
   98467 ** 2006 July 10
   98468 **
   98469 ** The author disclaims copyright to this source code.
   98470 **
   98471 *************************************************************************
   98472 ** Defines the interface to tokenizers used by fulltext-search.  There
   98473 ** are three basic components:
   98474 **
   98475 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
   98476 ** interface functions.  This is essentially the class structure for
   98477 ** tokenizers.
   98478 **
   98479 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
   98480 ** including customization information defined at creation time.
   98481 **
   98482 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
   98483 ** tokens from a particular input.
   98484 */
   98485 #ifndef _FTS3_TOKENIZER_H_
   98486 #define _FTS3_TOKENIZER_H_
   98487 
   98488 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
   98489 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
   98490 ** we will need a way to register the API consistently.
   98491 */
   98492 
   98493 /*
   98494 ** Structures used by the tokenizer interface. When a new tokenizer
   98495 ** implementation is registered, the caller provides a pointer to
   98496 ** an sqlite3_tokenizer_module containing pointers to the callback
   98497 ** functions that make up an implementation.
   98498 **
   98499 ** When an fts3 table is created, it passes any arguments passed to
   98500 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
   98501 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
   98502 ** implementation. The xCreate() function in turn returns an
   98503 ** sqlite3_tokenizer structure representing the specific tokenizer to
   98504 ** be used for the fts3 table (customized by the tokenizer clause arguments).
   98505 **
   98506 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
   98507 ** method is called. It returns an sqlite3_tokenizer_cursor object
   98508 ** that may be used to tokenize a specific input buffer based on
   98509 ** the tokenization rules supplied by a specific sqlite3_tokenizer
   98510 ** object.
   98511 */
   98512 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
   98513 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
   98514 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
   98515 
   98516 struct sqlite3_tokenizer_module {
   98517 
   98518   /*
   98519   ** Structure version. Should always be set to 0.
   98520   */
   98521   int iVersion;
   98522 
   98523   /*
   98524   ** Create a new tokenizer. The values in the argv[] array are the
   98525   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
   98526   ** TABLE statement that created the fts3 table. For example, if
   98527   ** the following SQL is executed:
   98528   **
   98529   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
   98530   **
   98531   ** then argc is set to 2, and the argv[] array contains pointers
   98532   ** to the strings "arg1" and "arg2".
   98533   **
   98534   ** This method should return either SQLITE_OK (0), or an SQLite error
   98535   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
   98536   ** to point at the newly created tokenizer structure. The generic
   98537   ** sqlite3_tokenizer.pModule variable should not be initialised by
   98538   ** this callback. The caller will do so.
   98539   */
   98540   int (*xCreate)(
   98541     int argc,                           /* Size of argv array */
   98542     const char *const*argv,             /* Tokenizer argument strings */
   98543     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
   98544   );
   98545 
   98546   /*
   98547   ** Destroy an existing tokenizer. The fts3 module calls this method
   98548   ** exactly once for each successful call to xCreate().
   98549   */
   98550   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
   98551 
   98552   /*
   98553   ** Create a tokenizer cursor to tokenize an input buffer. The caller
   98554   ** is responsible for ensuring that the input buffer remains valid
   98555   ** until the cursor is closed (using the xClose() method).
   98556   */
   98557   int (*xOpen)(
   98558     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
   98559     const char *pInput, int nBytes,      /* Input buffer */
   98560     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
   98561   );
   98562 
   98563   /*
   98564   ** Destroy an existing tokenizer cursor. The fts3 module calls this
   98565   ** method exactly once for each successful call to xOpen().
   98566   */
   98567   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
   98568 
   98569   /*
   98570   ** Retrieve the next token from the tokenizer cursor pCursor. This
   98571   ** method should either return SQLITE_OK and set the values of the
   98572   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
   98573   ** the end of the buffer has been reached, or an SQLite error code.
   98574   **
   98575   ** *ppToken should be set to point at a buffer containing the
   98576   ** normalized version of the token (i.e. after any case-folding and/or
   98577   ** stemming has been performed). *pnBytes should be set to the length
   98578   ** of this buffer in bytes. The input text that generated the token is
   98579   ** identified by the byte offsets returned in *piStartOffset and
   98580   ** *piEndOffset. *piStartOffset should be set to the index of the first
   98581   ** byte of the token in the input buffer. *piEndOffset should be set
   98582   ** to the index of the first byte just past the end of the token in
   98583   ** the input buffer.
   98584   **
   98585   ** The buffer *ppToken is set to point at is managed by the tokenizer
   98586   ** implementation. It is only required to be valid until the next call
   98587   ** to xNext() or xClose().
   98588   */
   98589   /* TODO(shess) current implementation requires pInput to be
   98590   ** nul-terminated.  This should either be fixed, or pInput/nBytes
   98591   ** should be converted to zInput.
   98592   */
   98593   int (*xNext)(
   98594     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
   98595     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
   98596     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
   98597     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
   98598     int *piPosition      /* OUT: Number of tokens returned before this one */
   98599   );
   98600 };
   98601 
   98602 struct sqlite3_tokenizer {
   98603   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
   98604   /* Tokenizer implementations will typically add additional fields */
   98605 };
   98606 
   98607 struct sqlite3_tokenizer_cursor {
   98608   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
   98609   /* Tokenizer implementations will typically add additional fields */
   98610 };
   98611 
   98612 int fts3_global_term_cnt(int iTerm, int iCol);
   98613 int fts3_term_cnt(int iTerm, int iCol);
   98614 
   98615 
   98616 #endif /* _FTS3_TOKENIZER_H_ */
   98617 
   98618 /************** End of fts3_tokenizer.h **************************************/
   98619 /************** Continuing where we left off in fts3Int.h ********************/
   98620 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
   98621 /************** Begin file fts3_hash.h ***************************************/
   98622 /*
   98623 ** 2001 September 22
   98624 **
   98625 ** The author disclaims copyright to this source code.  In place of
   98626 ** a legal notice, here is a blessing:
   98627 **
   98628 **    May you do good and not evil.
   98629 **    May you find forgiveness for yourself and forgive others.
   98630 **    May you share freely, never taking more than you give.
   98631 **
   98632 *************************************************************************
   98633 ** This is the header file for the generic hash-table implemenation
   98634 ** used in SQLite.  We've modified it slightly to serve as a standalone
   98635 ** hash table implementation for the full-text indexing module.
   98636 **
   98637 */
   98638 #ifndef _FTS3_HASH_H_
   98639 #define _FTS3_HASH_H_
   98640 
   98641 /* Forward declarations of structures. */
   98642 typedef struct Fts3Hash Fts3Hash;
   98643 typedef struct Fts3HashElem Fts3HashElem;
   98644 
   98645 /* A complete hash table is an instance of the following structure.
   98646 ** The internals of this structure are intended to be opaque -- client
   98647 ** code should not attempt to access or modify the fields of this structure
   98648 ** directly.  Change this structure only by using the routines below.
   98649 ** However, many of the "procedures" and "functions" for modifying and
   98650 ** accessing this structure are really macros, so we can't really make
   98651 ** this structure opaque.
   98652 */
   98653 struct Fts3Hash {
   98654   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
   98655   char copyKey;           /* True if copy of key made on insert */
   98656   int count;              /* Number of entries in this table */
   98657   Fts3HashElem *first;    /* The first element of the array */
   98658   int htsize;             /* Number of buckets in the hash table */
   98659   struct _fts3ht {        /* the hash table */
   98660     int count;               /* Number of entries with this hash */
   98661     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
   98662   } *ht;
   98663 };
   98664 
   98665 /* Each element in the hash table is an instance of the following
   98666 ** structure.  All elements are stored on a single doubly-linked list.
   98667 **
   98668 ** Again, this structure is intended to be opaque, but it can't really
   98669 ** be opaque because it is used by macros.
   98670 */
   98671 struct Fts3HashElem {
   98672   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
   98673   void *data;                /* Data associated with this element */
   98674   void *pKey; int nKey;      /* Key associated with this element */
   98675 };
   98676 
   98677 /*
   98678 ** There are 2 different modes of operation for a hash table:
   98679 **
   98680 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
   98681 **                           (including the null-terminator, if any).  Case
   98682 **                           is respected in comparisons.
   98683 **
   98684 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
   98685 **                           memcmp() is used to compare keys.
   98686 **
   98687 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
   98688 */
   98689 #define FTS3_HASH_STRING    1
   98690 #define FTS3_HASH_BINARY    2
   98691 
   98692 /*
   98693 ** Access routines.  To delete, insert a NULL pointer.
   98694 */
   98695 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
   98696 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
   98697 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
   98698 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
   98699 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
   98700 
   98701 /*
   98702 ** Shorthand for the functions above
   98703 */
   98704 #define fts3HashInit     sqlite3Fts3HashInit
   98705 #define fts3HashInsert   sqlite3Fts3HashInsert
   98706 #define fts3HashFind     sqlite3Fts3HashFind
   98707 #define fts3HashClear    sqlite3Fts3HashClear
   98708 #define fts3HashFindElem sqlite3Fts3HashFindElem
   98709 
   98710 /*
   98711 ** Macros for looping over all elements of a hash table.  The idiom is
   98712 ** like this:
   98713 **
   98714 **   Fts3Hash h;
   98715 **   Fts3HashElem *p;
   98716 **   ...
   98717 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
   98718 **     SomeStructure *pData = fts3HashData(p);
   98719 **     // do something with pData
   98720 **   }
   98721 */
   98722 #define fts3HashFirst(H)  ((H)->first)
   98723 #define fts3HashNext(E)   ((E)->next)
   98724 #define fts3HashData(E)   ((E)->data)
   98725 #define fts3HashKey(E)    ((E)->pKey)
   98726 #define fts3HashKeysize(E) ((E)->nKey)
   98727 
   98728 /*
   98729 ** Number of entries in a hash table
   98730 */
   98731 #define fts3HashCount(H)  ((H)->count)
   98732 
   98733 #endif /* _FTS3_HASH_H_ */
   98734 
   98735 /************** End of fts3_hash.h *******************************************/
   98736 /************** Continuing where we left off in fts3Int.h ********************/
   98737 
   98738 /*
   98739 ** This constant controls how often segments are merged. Once there are
   98740 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
   98741 ** segment of level N+1.
   98742 */
   98743 #define FTS3_MERGE_COUNT 16
   98744 
   98745 /*
   98746 ** This is the maximum amount of data (in bytes) to store in the
   98747 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
   98748 ** populated as documents are inserted/updated/deleted in a transaction
   98749 ** and used to create a new segment when the transaction is committed.
   98750 ** However if this limit is reached midway through a transaction, a new
   98751 ** segment is created and the hash table cleared immediately.
   98752 */
   98753 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
   98754 
   98755 /*
   98756 ** Macro to return the number of elements in an array. SQLite has a
   98757 ** similar macro called ArraySize(). Use a different name to avoid
   98758 ** a collision when building an amalgamation with built-in FTS3.
   98759 */
   98760 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
   98761 
   98762 /*
   98763 ** Maximum length of a varint encoded integer. The varint format is different
   98764 ** from that used by SQLite, so the maximum length is 10, not 9.
   98765 */
   98766 #define FTS3_VARINT_MAX 10
   98767 
   98768 /*
   98769 ** This section provides definitions to allow the
   98770 ** FTS3 extension to be compiled outside of the
   98771 ** amalgamation.
   98772 */
   98773 #ifndef SQLITE_AMALGAMATION
   98774 /*
   98775 ** Macros indicating that conditional expressions are always true or
   98776 ** false.
   98777 */
   98778 # define ALWAYS(x) (x)
   98779 # define NEVER(X)  (x)
   98780 /*
   98781 ** Internal types used by SQLite.
   98782 */
   98783 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
   98784 typedef short int i16;            /* 2-byte (or larger) signed integer */
   98785 typedef unsigned int u32;         /* 4-byte unsigned integer */
   98786 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
   98787 /*
   98788 ** Macro used to suppress compiler warnings for unused parameters.
   98789 */
   98790 #define UNUSED_PARAMETER(x) (void)(x)
   98791 #endif
   98792 
   98793 typedef struct Fts3Table Fts3Table;
   98794 typedef struct Fts3Cursor Fts3Cursor;
   98795 typedef struct Fts3Expr Fts3Expr;
   98796 typedef struct Fts3Phrase Fts3Phrase;
   98797 typedef struct Fts3SegReader Fts3SegReader;
   98798 typedef struct Fts3SegFilter Fts3SegFilter;
   98799 
   98800 /*
   98801 ** A connection to a fulltext index is an instance of the following
   98802 ** structure. The xCreate and xConnect methods create an instance
   98803 ** of this structure and xDestroy and xDisconnect free that instance.
   98804 ** All other methods receive a pointer to the structure as one of their
   98805 ** arguments.
   98806 */
   98807 struct Fts3Table {
   98808   sqlite3_vtab base;              /* Base class used by SQLite core */
   98809   sqlite3 *db;                    /* The database connection */
   98810   const char *zDb;                /* logical database name */
   98811   const char *zName;              /* virtual table name */
   98812   int nColumn;                    /* number of named columns in virtual table */
   98813   char **azColumn;                /* column names.  malloced */
   98814   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
   98815 
   98816   /* Precompiled statements used by the implementation. Each of these
   98817   ** statements is run and reset within a single virtual table API call.
   98818   */
   98819   sqlite3_stmt *aStmt[18];
   98820 
   98821   /* Pointer to string containing the SQL:
   98822   **
   98823   ** "SELECT block FROM %_segments WHERE blockid BETWEEN ? AND ?
   98824   **    ORDER BY blockid"
   98825   */
   98826   char *zSelectLeaves;
   98827   int nLeavesStmt;                /* Valid statements in aLeavesStmt */
   98828   int nLeavesTotal;               /* Total number of prepared leaves stmts */
   98829   int nLeavesAlloc;               /* Allocated size of aLeavesStmt */
   98830   sqlite3_stmt **aLeavesStmt;     /* Array of prepared zSelectLeaves stmts */
   98831 
   98832   int nNodeSize;                  /* Soft limit for node size */
   98833 
   98834   /* The following hash table is used to buffer pending index updates during
   98835   ** transactions. Variable nPendingData estimates the memory size of the
   98836   ** pending data, including hash table overhead, but not malloc overhead.
   98837   ** When nPendingData exceeds nMaxPendingData, the buffer is flushed
   98838   ** automatically. Variable iPrevDocid is the docid of the most recently
   98839   ** inserted record.
   98840   */
   98841   int nMaxPendingData;
   98842   int nPendingData;
   98843   sqlite_int64 iPrevDocid;
   98844   Fts3Hash pendingTerms;
   98845 };
   98846 
   98847 /*
   98848 ** When the core wants to read from the virtual table, it creates a
   98849 ** virtual table cursor (an instance of the following structure) using
   98850 ** the xOpen method. Cursors are destroyed using the xClose method.
   98851 */
   98852 struct Fts3Cursor {
   98853   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
   98854   i16 eSearch;                    /* Search strategy (see below) */
   98855   u8 isEof;                       /* True if at End Of Results */
   98856   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
   98857   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
   98858   Fts3Expr *pExpr;                /* Parsed MATCH query string */
   98859   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
   98860   char *pNextId;                  /* Pointer into the body of aDoclist */
   98861   char *aDoclist;                 /* List of docids for full-text queries */
   98862   int nDoclist;                   /* Size of buffer at aDoclist */
   98863   int isMatchinfoOk;              /* True when aMatchinfo[] matches iPrevId */
   98864   u32 *aMatchinfo;
   98865 };
   98866 
   98867 /*
   98868 ** The Fts3Cursor.eSearch member is always set to one of the following.
   98869 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
   98870 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
   98871 ** of the column to be searched.  For example, in
   98872 **
   98873 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
   98874 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
   98875 **
   98876 ** Because the LHS of the MATCH operator is 2nd column "b",
   98877 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
   98878 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
   98879 ** indicating that all columns should be searched,
   98880 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
   98881 */
   98882 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
   98883 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
   98884 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
   98885 
   98886 /*
   98887 ** A "phrase" is a sequence of one or more tokens that must match in
   98888 ** sequence.  A single token is the base case and the most common case.
   98889 ** For a sequence of tokens contained in "...", nToken will be the number
   98890 ** of tokens in the string.
   98891 */
   98892 struct Fts3Phrase {
   98893   int nToken;                /* Number of tokens in the phrase */
   98894   int iColumn;               /* Index of column this phrase must match */
   98895   int isNot;                 /* Phrase prefixed by unary not (-) operator */
   98896   struct PhraseToken {
   98897     char *z;                 /* Text of the token */
   98898     int n;                   /* Number of bytes in buffer pointed to by z */
   98899     int isPrefix;            /* True if token ends in with a "*" character */
   98900   } aToken[1];               /* One entry for each token in the phrase */
   98901 };
   98902 
   98903 /*
   98904 ** A tree of these objects forms the RHS of a MATCH operator.
   98905 **
   98906 ** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
   98907 ** is true, then aDoclist points to a malloced buffer, size nDoclist bytes,
   98908 ** containing the results of the NEAR or phrase query in FTS3 doclist
   98909 ** format. As usual, the initial "Length" field found in doclists stored
   98910 ** on disk is omitted from this buffer.
   98911 **
   98912 ** Variable pCurrent always points to the start of a docid field within
   98913 ** aDoclist. Since the doclist is usually scanned in docid order, this can
   98914 ** be used to accelerate seeking to the required docid within the doclist.
   98915 */
   98916 struct Fts3Expr {
   98917   int eType;                 /* One of the FTSQUERY_XXX values defined below */
   98918   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
   98919   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
   98920   Fts3Expr *pLeft;           /* Left operand */
   98921   Fts3Expr *pRight;          /* Right operand */
   98922   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
   98923 
   98924   int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
   98925   char *aDoclist;            /* Buffer containing doclist */
   98926   int nDoclist;              /* Size of aDoclist in bytes */
   98927 
   98928   sqlite3_int64 iCurrent;
   98929   char *pCurrent;
   98930 };
   98931 
   98932 /*
   98933 ** Candidate values for Fts3Query.eType. Note that the order of the first
   98934 ** four values is in order of precedence when parsing expressions. For
   98935 ** example, the following:
   98936 **
   98937 **   "a OR b AND c NOT d NEAR e"
   98938 **
   98939 ** is equivalent to:
   98940 **
   98941 **   "a OR (b AND (c NOT (d NEAR e)))"
   98942 */
   98943 #define FTSQUERY_NEAR   1
   98944 #define FTSQUERY_NOT    2
   98945 #define FTSQUERY_AND    3
   98946 #define FTSQUERY_OR     4
   98947 #define FTSQUERY_PHRASE 5
   98948 
   98949 
   98950 /* fts3_init.c */
   98951 SQLITE_PRIVATE int sqlite3Fts3DeleteVtab(int, sqlite3_vtab *);
   98952 SQLITE_PRIVATE int sqlite3Fts3InitVtab(int, sqlite3*, void*, int, const char*const*,
   98953                         sqlite3_vtab **, char **);
   98954 
   98955 /* fts3_write.c */
   98956 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
   98957 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
   98958 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
   98959 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
   98960 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(Fts3Table *,int, sqlite3_int64,
   98961   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
   98962 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
   98963 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *, Fts3SegReader *);
   98964 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
   98965   Fts3Table *, Fts3SegReader **, int, Fts3SegFilter *,
   98966   int (*)(Fts3Table *, void *, char *, int, char *, int),  void *
   98967 );
   98968 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char const**, int*);
   98969 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
   98970 
   98971 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
   98972 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
   98973 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
   98974 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
   98975 #define FTS3_SEGMENT_PREFIX        0x00000008
   98976 
   98977 /* Type passed as 4th argument to SegmentReaderIterate() */
   98978 struct Fts3SegFilter {
   98979   const char *zTerm;
   98980   int nTerm;
   98981   int iCol;
   98982   int flags;
   98983 };
   98984 
   98985 /* fts3.c */
   98986 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
   98987 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
   98988 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
   98989 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
   98990 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
   98991 
   98992 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
   98993 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *, Fts3Expr *);
   98994 
   98995 /* fts3_tokenizer.c */
   98996 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
   98997 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
   98998 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash,
   98999   const char *, sqlite3_tokenizer **, const char **, char **
   99000 );
   99001 
   99002 /* fts3_snippet.c */
   99003 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
   99004 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context*, Fts3Cursor*,
   99005   const char *, const char *, const char *
   99006 );
   99007 SQLITE_PRIVATE void sqlite3Fts3Snippet2(sqlite3_context *, Fts3Cursor *, const char *,
   99008   const char *, const char *, int, int
   99009 );
   99010 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *);
   99011 
   99012 /* fts3_expr.c */
   99013 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *,
   99014   char **, int, int, const char *, int, Fts3Expr **
   99015 );
   99016 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
   99017 #ifdef SQLITE_TEST
   99018 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
   99019 #endif
   99020 
   99021 #endif /* _FTSINT_H */
   99022 
   99023 /************** End of fts3Int.h *********************************************/
   99024 /************** Continuing where we left off in fts3.c ***********************/
   99025 
   99026 
   99027 #ifndef SQLITE_CORE
   99028   SQLITE_EXTENSION_INIT1
   99029 #endif
   99030 
   99031 /*
   99032 ** Write a 64-bit variable-length integer to memory starting at p[0].
   99033 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
   99034 ** The number of bytes written is returned.
   99035 */
   99036 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
   99037   unsigned char *q = (unsigned char *) p;
   99038   sqlite_uint64 vu = v;
   99039   do{
   99040     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
   99041     vu >>= 7;
   99042   }while( vu!=0 );
   99043   q[-1] &= 0x7f;  /* turn off high bit in final byte */
   99044   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
   99045   return (int) (q - (unsigned char *)p);
   99046 }
   99047 
   99048 /*
   99049 ** Read a 64-bit variable-length integer from memory starting at p[0].
   99050 ** Return the number of bytes read, or 0 on error.
   99051 ** The value is stored in *v.
   99052 */
   99053 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
   99054   const unsigned char *q = (const unsigned char *) p;
   99055   sqlite_uint64 x = 0, y = 1;
   99056   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
   99057     x += y * (*q++ & 0x7f);
   99058     y <<= 7;
   99059   }
   99060   x += y * (*q++);
   99061   *v = (sqlite_int64) x;
   99062   return (int) (q - (unsigned char *)p);
   99063 }
   99064 
   99065 /*
   99066 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
   99067 ** 32-bit integer before it is returned.
   99068 */
   99069 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
   99070  sqlite_int64 i;
   99071  int ret = sqlite3Fts3GetVarint(p, &i);
   99072  *pi = (int) i;
   99073  return ret;
   99074 }
   99075 
   99076 /*
   99077 ** Return the number of bytes required to store the value passed as the
   99078 ** first argument in varint form.
   99079 */
   99080 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
   99081   int i = 0;
   99082   do{
   99083     i++;
   99084     v >>= 7;
   99085   }while( v!=0 );
   99086   return i;
   99087 }
   99088 
   99089 /*
   99090 ** Convert an SQL-style quoted string into a normal string by removing
   99091 ** the quote characters.  The conversion is done in-place.  If the
   99092 ** input does not begin with a quote character, then this routine
   99093 ** is a no-op.
   99094 **
   99095 ** Examples:
   99096 **
   99097 **     "abc"   becomes   abc
   99098 **     'xyz'   becomes   xyz
   99099 **     [pqr]   becomes   pqr
   99100 **     `mno`   becomes   mno
   99101 **
   99102 */
   99103 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
   99104   char quote;                     /* Quote character (if any ) */
   99105 
   99106   quote = z[0];
   99107   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
   99108     int iIn = 1;                  /* Index of next byte to read from input */
   99109     int iOut = 0;                 /* Index of next byte to write to output */
   99110 
   99111     /* If the first byte was a '[', then the close-quote character is a ']' */
   99112     if( quote=='[' ) quote = ']';
   99113 
   99114     while( ALWAYS(z[iIn]) ){
   99115       if( z[iIn]==quote ){
   99116         if( z[iIn+1]!=quote ) break;
   99117         z[iOut++] = quote;
   99118         iIn += 2;
   99119       }else{
   99120         z[iOut++] = z[iIn++];
   99121       }
   99122     }
   99123     z[iOut] = '\0';
   99124   }
   99125 }
   99126 
   99127 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
   99128   sqlite3_int64 iVal;
   99129   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
   99130   *pVal += iVal;
   99131 }
   99132 
   99133 static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
   99134   if( *pp>=pEnd ){
   99135     *pp = 0;
   99136   }else{
   99137     fts3GetDeltaVarint(pp, pVal);
   99138   }
   99139 }
   99140 
   99141 /*
   99142 ** The xDisconnect() virtual table method.
   99143 */
   99144 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
   99145   Fts3Table *p = (Fts3Table *)pVtab;
   99146   int i;
   99147 
   99148   assert( p->nPendingData==0 );
   99149 
   99150   /* Free any prepared statements held */
   99151   for(i=0; i<SizeofArray(p->aStmt); i++){
   99152     sqlite3_finalize(p->aStmt[i]);
   99153   }
   99154   for(i=0; i<p->nLeavesStmt; i++){
   99155     sqlite3_finalize(p->aLeavesStmt[i]);
   99156   }
   99157   sqlite3_free(p->zSelectLeaves);
   99158   sqlite3_free(p->aLeavesStmt);
   99159 
   99160   /* Invoke the tokenizer destructor to free the tokenizer. */
   99161   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
   99162 
   99163   sqlite3_free(p);
   99164   return SQLITE_OK;
   99165 }
   99166 
   99167 /*
   99168 ** The xDestroy() virtual table method.
   99169 */
   99170 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
   99171   int rc;                         /* Return code */
   99172   Fts3Table *p = (Fts3Table *)pVtab;
   99173 
   99174   /* Create a script to drop the underlying three storage tables. */
   99175   char *zSql = sqlite3_mprintf(
   99176       "DROP TABLE IF EXISTS %Q.'%q_content';"
   99177       "DROP TABLE IF EXISTS %Q.'%q_segments';"
   99178       "DROP TABLE IF EXISTS %Q.'%q_segdir';",
   99179       p->zDb, p->zName, p->zDb, p->zName, p->zDb, p->zName
   99180   );
   99181 
   99182   /* If malloc has failed, set rc to SQLITE_NOMEM. Otherwise, try to
   99183   ** execute the SQL script created above.
   99184   */
   99185   if( zSql ){
   99186     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
   99187     sqlite3_free(zSql);
   99188   }else{
   99189     rc = SQLITE_NOMEM;
   99190   }
   99191 
   99192   /* If everything has worked, invoke fts3DisconnectMethod() to free the
   99193   ** memory associated with the Fts3Table structure and return SQLITE_OK.
   99194   ** Otherwise, return an SQLite error code.
   99195   */
   99196   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
   99197 }
   99198 
   99199 
   99200 /*
   99201 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
   99202 ** passed as the first argument. This is done as part of the xConnect()
   99203 ** and xCreate() methods.
   99204 */
   99205 static int fts3DeclareVtab(Fts3Table *p){
   99206   int i;                          /* Iterator variable */
   99207   int rc;                         /* Return code */
   99208   char *zSql;                     /* SQL statement passed to declare_vtab() */
   99209   char *zCols;                    /* List of user defined columns */
   99210 
   99211   /* Create a list of user columns for the virtual table */
   99212   zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
   99213   for(i=1; zCols && i<p->nColumn; i++){
   99214     zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
   99215   }
   99216 
   99217   /* Create the whole "CREATE TABLE" statement to pass to SQLite */
   99218   zSql = sqlite3_mprintf(
   99219       "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
   99220   );
   99221 
   99222   if( !zCols || !zSql ){
   99223     rc = SQLITE_NOMEM;
   99224   }else{
   99225     rc = sqlite3_declare_vtab(p->db, zSql);
   99226   }
   99227 
   99228   sqlite3_free(zSql);
   99229   sqlite3_free(zCols);
   99230   return rc;
   99231 }
   99232 
   99233 /*
   99234 ** Create the backing store tables (%_content, %_segments and %_segdir)
   99235 ** required by the FTS3 table passed as the only argument. This is done
   99236 ** as part of the vtab xCreate() method.
   99237 */
   99238 static int fts3CreateTables(Fts3Table *p){
   99239   int rc;                         /* Return code */
   99240   int i;                          /* Iterator variable */
   99241   char *zContentCols;             /* Columns of %_content table */
   99242   char *zSql;                     /* SQL script to create required tables */
   99243 
   99244   /* Create a list of user columns for the content table */
   99245   zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
   99246   for(i=0; zContentCols && i<p->nColumn; i++){
   99247     char *z = p->azColumn[i];
   99248     zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
   99249   }
   99250 
   99251   /* Create the whole SQL script */
   99252   zSql = sqlite3_mprintf(
   99253       "CREATE TABLE %Q.'%q_content'(%s);"
   99254       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);"
   99255       "CREATE TABLE %Q.'%q_segdir'("
   99256         "level INTEGER,"
   99257         "idx INTEGER,"
   99258         "start_block INTEGER,"
   99259         "leaves_end_block INTEGER,"
   99260         "end_block INTEGER,"
   99261         "root BLOB,"
   99262         "PRIMARY KEY(level, idx)"
   99263       ");",
   99264       p->zDb, p->zName, zContentCols, p->zDb, p->zName, p->zDb, p->zName
   99265   );
   99266 
   99267   /* Unless a malloc() failure has occurred, execute the SQL script to
   99268   ** create the tables used to store data for this FTS3 virtual table.
   99269   */
   99270   if( zContentCols==0 || zSql==0 ){
   99271     rc = SQLITE_NOMEM;
   99272   }else{
   99273     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
   99274   }
   99275 
   99276   sqlite3_free(zSql);
   99277   sqlite3_free(zContentCols);
   99278   return rc;
   99279 }
   99280 
   99281 /*
   99282 ** This function is the implementation of both the xConnect and xCreate
   99283 ** methods of the FTS3 virtual table.
   99284 **
   99285 ** The argv[] array contains the following:
   99286 **
   99287 **   argv[0]   -> module name
   99288 **   argv[1]   -> database name
   99289 **   argv[2]   -> table name
   99290 **   argv[...] -> "column name" and other module argument fields.
   99291 */
   99292 static int fts3InitVtab(
   99293   int isCreate,                   /* True for xCreate, false for xConnect */
   99294   sqlite3 *db,                    /* The SQLite database connection */
   99295   void *pAux,                     /* Hash table containing tokenizers */
   99296   int argc,                       /* Number of elements in argv array */
   99297   const char * const *argv,       /* xCreate/xConnect argument array */
   99298   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
   99299   char **pzErr                    /* Write any error message here */
   99300 ){
   99301   Fts3Hash *pHash = (Fts3Hash *)pAux;
   99302   Fts3Table *p;                   /* Pointer to allocated vtab */
   99303   int rc;                         /* Return code */
   99304   int i;                          /* Iterator variable */
   99305   int nByte;                      /* Size of allocation used for *p */
   99306   int iCol;
   99307   int nString = 0;
   99308   int nCol = 0;
   99309   char *zCsr;
   99310   int nDb;
   99311   int nName;
   99312 
   99313   const char *zTokenizer = 0;               /* Name of tokenizer to use */
   99314   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
   99315 
   99316   nDb = (int)strlen(argv[1]) + 1;
   99317   nName = (int)strlen(argv[2]) + 1;
   99318   for(i=3; i<argc; i++){
   99319     char const *z = argv[i];
   99320     rc = sqlite3Fts3InitTokenizer(pHash, z, &pTokenizer, &zTokenizer, pzErr);
   99321     if( rc!=SQLITE_OK ){
   99322       return rc;
   99323     }
   99324     if( z!=zTokenizer ){
   99325       nString += (int)(strlen(z) + 1);
   99326     }
   99327   }
   99328   nCol = argc - 3 - (zTokenizer!=0);
   99329   if( zTokenizer==0 ){
   99330     rc = sqlite3Fts3InitTokenizer(pHash, 0, &pTokenizer, 0, pzErr);
   99331     if( rc!=SQLITE_OK ){
   99332       return rc;
   99333     }
   99334     assert( pTokenizer );
   99335   }
   99336 
   99337   if( nCol==0 ){
   99338     nCol = 1;
   99339   }
   99340 
   99341   /* Allocate and populate the Fts3Table structure. */
   99342   nByte = sizeof(Fts3Table) +              /* Fts3Table */
   99343           nCol * sizeof(char *) +              /* azColumn */
   99344           nName +                              /* zName */
   99345           nDb +                                /* zDb */
   99346           nString;                             /* Space for azColumn strings */
   99347   p = (Fts3Table*)sqlite3_malloc(nByte);
   99348   if( p==0 ){
   99349     rc = SQLITE_NOMEM;
   99350     goto fts3_init_out;
   99351   }
   99352   memset(p, 0, nByte);
   99353 
   99354   p->db = db;
   99355   p->nColumn = nCol;
   99356   p->nPendingData = 0;
   99357   p->azColumn = (char **)&p[1];
   99358   p->pTokenizer = pTokenizer;
   99359   p->nNodeSize = 1000;
   99360   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
   99361   zCsr = (char *)&p->azColumn[nCol];
   99362 
   99363   fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
   99364 
   99365   /* Fill in the zName and zDb fields of the vtab structure. */
   99366   p->zName = zCsr;
   99367   memcpy(zCsr, argv[2], nName);
   99368   zCsr += nName;
   99369   p->zDb = zCsr;
   99370   memcpy(zCsr, argv[1], nDb);
   99371   zCsr += nDb;
   99372 
   99373   /* Fill in the azColumn array */
   99374   iCol = 0;
   99375   for(i=3; i<argc; i++){
   99376     if( argv[i]!=zTokenizer ){
   99377       char *z;
   99378       int n;
   99379       z = (char *)sqlite3Fts3NextToken(argv[i], &n);
   99380       memcpy(zCsr, z, n);
   99381       zCsr[n] = '\0';
   99382       sqlite3Fts3Dequote(zCsr);
   99383       p->azColumn[iCol++] = zCsr;
   99384       zCsr += n+1;
   99385       assert( zCsr <= &((char *)p)[nByte] );
   99386     }
   99387   }
   99388   if( iCol==0 ){
   99389     assert( nCol==1 );
   99390     p->azColumn[0] = "content";
   99391   }
   99392 
   99393   /* If this is an xCreate call, create the underlying tables in the
   99394   ** database. TODO: For xConnect(), it could verify that said tables exist.
   99395   */
   99396   if( isCreate ){
   99397     rc = fts3CreateTables(p);
   99398     if( rc!=SQLITE_OK ) goto fts3_init_out;
   99399   }
   99400 
   99401   rc = fts3DeclareVtab(p);
   99402   if( rc!=SQLITE_OK ) goto fts3_init_out;
   99403 
   99404   *ppVTab = &p->base;
   99405 
   99406 fts3_init_out:
   99407   assert( p || (pTokenizer && rc!=SQLITE_OK) );
   99408   if( rc!=SQLITE_OK ){
   99409     if( p ){
   99410       fts3DisconnectMethod((sqlite3_vtab *)p);
   99411     }else{
   99412       pTokenizer->pModule->xDestroy(pTokenizer);
   99413     }
   99414   }
   99415   return rc;
   99416 }
   99417 
   99418 /*
   99419 ** The xConnect() and xCreate() methods for the virtual table. All the
   99420 ** work is done in function fts3InitVtab().
   99421 */
   99422 static int fts3ConnectMethod(
   99423   sqlite3 *db,                    /* Database connection */
   99424   void *pAux,                     /* Pointer to tokenizer hash table */
   99425   int argc,                       /* Number of elements in argv array */
   99426   const char * const *argv,       /* xCreate/xConnect argument array */
   99427   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   99428   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   99429 ){
   99430   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
   99431 }
   99432 static int fts3CreateMethod(
   99433   sqlite3 *db,                    /* Database connection */
   99434   void *pAux,                     /* Pointer to tokenizer hash table */
   99435   int argc,                       /* Number of elements in argv array */
   99436   const char * const *argv,       /* xCreate/xConnect argument array */
   99437   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   99438   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   99439 ){
   99440   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
   99441 }
   99442 
   99443 /*
   99444 ** Implementation of the xBestIndex method for FTS3 tables. There
   99445 ** are three possible strategies, in order of preference:
   99446 **
   99447 **   1. Direct lookup by rowid or docid.
   99448 **   2. Full-text search using a MATCH operator on a non-docid column.
   99449 **   3. Linear scan of %_content table.
   99450 */
   99451 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
   99452   Fts3Table *p = (Fts3Table *)pVTab;
   99453   int i;                          /* Iterator variable */
   99454   int iCons = -1;                 /* Index of constraint to use */
   99455 
   99456   /* By default use a full table scan. This is an expensive option,
   99457   ** so search through the constraints to see if a more efficient
   99458   ** strategy is possible.
   99459   */
   99460   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
   99461   pInfo->estimatedCost = 500000;
   99462   for(i=0; i<pInfo->nConstraint; i++){
   99463     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
   99464     if( pCons->usable==0 ) continue;
   99465 
   99466     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
   99467     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
   99468      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
   99469     ){
   99470       pInfo->idxNum = FTS3_DOCID_SEARCH;
   99471       pInfo->estimatedCost = 1.0;
   99472       iCons = i;
   99473     }
   99474 
   99475     /* A MATCH constraint. Use a full-text search.
   99476     **
   99477     ** If there is more than one MATCH constraint available, use the first
   99478     ** one encountered. If there is both a MATCH constraint and a direct
   99479     ** rowid/docid lookup, prefer the MATCH strategy. This is done even
   99480     ** though the rowid/docid lookup is faster than a MATCH query, selecting
   99481     ** it would lead to an "unable to use function MATCH in the requested
   99482     ** context" error.
   99483     */
   99484     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
   99485      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
   99486     ){
   99487       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
   99488       pInfo->estimatedCost = 2.0;
   99489       iCons = i;
   99490       break;
   99491     }
   99492   }
   99493 
   99494   if( iCons>=0 ){
   99495     pInfo->aConstraintUsage[iCons].argvIndex = 1;
   99496     pInfo->aConstraintUsage[iCons].omit = 1;
   99497   }
   99498   return SQLITE_OK;
   99499 }
   99500 
   99501 /*
   99502 ** Implementation of xOpen method.
   99503 */
   99504 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   99505   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
   99506 
   99507   UNUSED_PARAMETER(pVTab);
   99508 
   99509   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
   99510   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
   99511   ** if the allocation fails, return SQLITE_NOMEM.
   99512   */
   99513   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
   99514   if( !pCsr ){
   99515     return SQLITE_NOMEM;
   99516   }
   99517   memset(pCsr, 0, sizeof(Fts3Cursor));
   99518   return SQLITE_OK;
   99519 }
   99520 
   99521 /****************************************************************/
   99522 /****************************************************************/
   99523 /****************************************************************/
   99524 /****************************************************************/
   99525 
   99526 
   99527 /*
   99528 ** Close the cursor.  For additional information see the documentation
   99529 ** on the xClose method of the virtual table interface.
   99530 */
   99531 static int fulltextClose(sqlite3_vtab_cursor *pCursor){
   99532   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   99533   sqlite3_finalize(pCsr->pStmt);
   99534   sqlite3Fts3ExprFree(pCsr->pExpr);
   99535   sqlite3_free(pCsr->aDoclist);
   99536   sqlite3_free(pCsr->aMatchinfo);
   99537   sqlite3_free(pCsr);
   99538   return SQLITE_OK;
   99539 }
   99540 
   99541 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
   99542   if( pCsr->isRequireSeek ){
   99543     pCsr->isRequireSeek = 0;
   99544     sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
   99545     if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
   99546       return SQLITE_OK;
   99547     }else{
   99548       int rc = sqlite3_reset(pCsr->pStmt);
   99549       if( rc==SQLITE_OK ){
   99550         /* If no row was found and no error has occured, then the %_content
   99551         ** table is missing a row that is present in the full-text index.
   99552         ** The data structures are corrupt.
   99553         */
   99554         rc = SQLITE_CORRUPT;
   99555       }
   99556       pCsr->isEof = 1;
   99557       if( pContext ){
   99558         sqlite3_result_error_code(pContext, rc);
   99559       }
   99560       return rc;
   99561     }
   99562   }else{
   99563     return SQLITE_OK;
   99564   }
   99565 }
   99566 
   99567 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
   99568   int rc = SQLITE_OK;             /* Return code */
   99569   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   99570 
   99571   if( pCsr->aDoclist==0 ){
   99572     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
   99573       pCsr->isEof = 1;
   99574       rc = sqlite3_reset(pCsr->pStmt);
   99575     }
   99576   }else if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
   99577     pCsr->isEof = 1;
   99578   }else{
   99579     sqlite3_reset(pCsr->pStmt);
   99580     fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
   99581     pCsr->isRequireSeek = 1;
   99582     pCsr->isMatchinfoOk = 1;
   99583   }
   99584   return rc;
   99585 }
   99586 
   99587 
   99588 /*
   99589 ** The buffer pointed to by argument zNode (size nNode bytes) contains the
   99590 ** root node of a b-tree segment. The segment is guaranteed to be at least
   99591 ** one level high (i.e. the root node is not also a leaf). If successful,
   99592 ** this function locates the leaf node of the segment that may contain the
   99593 ** term specified by arguments zTerm and nTerm and writes its block number
   99594 ** to *piLeaf.
   99595 **
   99596 ** It is possible that the returned leaf node does not contain the specified
   99597 ** term. However, if the segment does contain said term, it is stored on
   99598 ** the identified leaf node. Because this function only inspects interior
   99599 ** segment nodes (and never loads leaf nodes into memory), it is not possible
   99600 ** to be sure.
   99601 **
   99602 ** If an error occurs, an error code other than SQLITE_OK is returned.
   99603 */
   99604 static int fts3SelectLeaf(
   99605   Fts3Table *p,                   /* Virtual table handle */
   99606   const char *zTerm,              /* Term to select leaves for */
   99607   int nTerm,                      /* Size of term zTerm in bytes */
   99608   const char *zNode,              /* Buffer containing segment interior node */
   99609   int nNode,                      /* Size of buffer at zNode */
   99610   sqlite3_int64 *piLeaf           /* Selected leaf node */
   99611 ){
   99612   int rc = SQLITE_OK;             /* Return code */
   99613   const char *zCsr = zNode;       /* Cursor to iterate through node */
   99614   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
   99615   char *zBuffer = 0;              /* Buffer to load terms into */
   99616   int nAlloc = 0;                 /* Size of allocated buffer */
   99617 
   99618   while( 1 ){
   99619     int isFirstTerm = 1;          /* True when processing first term on page */
   99620     int iHeight;                  /* Height of this node in tree */
   99621     sqlite3_int64 iChild;         /* Block id of child node to descend to */
   99622     int nBlock;                   /* Size of child node in bytes */
   99623 
   99624     zCsr += sqlite3Fts3GetVarint32(zCsr, &iHeight);
   99625     zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
   99626 
   99627     while( zCsr<zEnd ){
   99628       int cmp;                    /* memcmp() result */
   99629       int nSuffix;                /* Size of term suffix */
   99630       int nPrefix = 0;            /* Size of term prefix */
   99631       int nBuffer;                /* Total term size */
   99632 
   99633       /* Load the next term on the node into zBuffer */
   99634       if( !isFirstTerm ){
   99635         zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
   99636       }
   99637       isFirstTerm = 0;
   99638       zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
   99639       if( nPrefix+nSuffix>nAlloc ){
   99640         char *zNew;
   99641         nAlloc = (nPrefix+nSuffix) * 2;
   99642         zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
   99643         if( !zNew ){
   99644           sqlite3_free(zBuffer);
   99645           return SQLITE_NOMEM;
   99646         }
   99647         zBuffer = zNew;
   99648       }
   99649       memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
   99650       nBuffer = nPrefix + nSuffix;
   99651       zCsr += nSuffix;
   99652 
   99653       /* Compare the term we are searching for with the term just loaded from
   99654       ** the interior node. If the specified term is greater than or equal
   99655       ** to the term from the interior node, then all terms on the sub-tree
   99656       ** headed by node iChild are smaller than zTerm. No need to search
   99657       ** iChild.
   99658       **
   99659       ** If the interior node term is larger than the specified term, then
   99660       ** the tree headed by iChild may contain the specified term.
   99661       */
   99662       cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
   99663       if( cmp<0 || (cmp==0 && nBuffer>nTerm) ) break;
   99664       iChild++;
   99665     };
   99666 
   99667     /* If (iHeight==1), the children of this interior node are leaves. The
   99668     ** specified term may be present on leaf node iChild.
   99669     */
   99670     if( iHeight==1 ){
   99671       *piLeaf = iChild;
   99672       break;
   99673     }
   99674 
   99675     /* Descend to interior node iChild. */
   99676     rc = sqlite3Fts3ReadBlock(p, iChild, &zCsr, &nBlock);
   99677     if( rc!=SQLITE_OK ) break;
   99678     zEnd = &zCsr[nBlock];
   99679   }
   99680   sqlite3_free(zBuffer);
   99681   return rc;
   99682 }
   99683 
   99684 /*
   99685 ** This function is used to create delta-encoded serialized lists of FTS3
   99686 ** varints. Each call to this function appends a single varint to a list.
   99687 */
   99688 static void fts3PutDeltaVarint(
   99689   char **pp,                      /* IN/OUT: Output pointer */
   99690   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
   99691   sqlite3_int64 iVal              /* Write this value to the list */
   99692 ){
   99693   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
   99694   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
   99695   *piPrev = iVal;
   99696 }
   99697 
   99698 /*
   99699 ** When this function is called, *ppPoslist is assumed to point to the
   99700 ** start of a position-list.
   99701 */
   99702 static void fts3PoslistCopy(char **pp, char **ppPoslist){
   99703   char *pEnd = *ppPoslist;
   99704   char c = 0;
   99705 
   99706   /* The end of a position list is marked by a zero encoded as an FTS3
   99707   ** varint. A single 0x00 byte. Except, if the 0x00 byte is preceded by
   99708   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
   99709   ** of some other, multi-byte, value.
   99710   **
   99711   ** The following block moves pEnd to point to the first byte that is not
   99712   ** immediately preceded by a byte with the 0x80 bit set. Then increments
   99713   ** pEnd once more so that it points to the byte immediately following the
   99714   ** last byte in the position-list.
   99715   */
   99716   while( *pEnd | c ) c = *pEnd++ & 0x80;
   99717   pEnd++;
   99718 
   99719   if( pp ){
   99720     int n = (int)(pEnd - *ppPoslist);
   99721     char *p = *pp;
   99722     memcpy(p, *ppPoslist, n);
   99723     p += n;
   99724     *pp = p;
   99725   }
   99726   *ppPoslist = pEnd;
   99727 }
   99728 
   99729 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
   99730   char *pEnd = *ppPoslist;
   99731   char c = 0;
   99732 
   99733   /* A column-list is terminated by either a 0x01 or 0x00. */
   99734   while( 0xFE & (*pEnd | c) ) c = *pEnd++ & 0x80;
   99735   if( pp ){
   99736     int n = (int)(pEnd - *ppPoslist);
   99737     char *p = *pp;
   99738     memcpy(p, *ppPoslist, n);
   99739     p += n;
   99740     *pp = p;
   99741   }
   99742   *ppPoslist = pEnd;
   99743 }
   99744 
   99745 /*
   99746 ** Value used to signify the end of an offset-list. This is safe because
   99747 ** it is not possible to have a document with 2^31 terms.
   99748 */
   99749 #define OFFSET_LIST_END 0x7fffffff
   99750 
   99751 /*
   99752 ** This function is used to help parse offset-lists. When this function is
   99753 ** called, *pp may point to the start of the next varint in the offset-list
   99754 ** being parsed, or it may point to 1 byte past the end of the offset-list
   99755 ** (in which case **pp will be 0x00 or 0x01).
   99756 **
   99757 ** If *pp points past the end of the current offset list, set *pi to
   99758 ** OFFSET_LIST_END and return. Otherwise, read the next varint from *pp,
   99759 ** increment the current value of *pi by the value read, and set *pp to
   99760 ** point to the next value before returning.
   99761 */
   99762 static void fts3ReadNextPos(
   99763   char **pp,                      /* IN/OUT: Pointer into offset-list buffer */
   99764   sqlite3_int64 *pi               /* IN/OUT: Value read from offset-list */
   99765 ){
   99766   if( **pp&0xFE ){
   99767     fts3GetDeltaVarint(pp, pi);
   99768     *pi -= 2;
   99769   }else{
   99770     *pi = OFFSET_LIST_END;
   99771   }
   99772 }
   99773 
   99774 /*
   99775 ** If parameter iCol is not 0, write an 0x01 byte followed by the value of
   99776 ** iCol encoded as a varint to *pp.
   99777 **
   99778 ** Set *pp to point to the byte just after the last byte written before
   99779 ** returning (do not modify it if iCol==0). Return the total number of bytes
   99780 ** written (0 if iCol==0).
   99781 */
   99782 static int fts3PutColNumber(char **pp, int iCol){
   99783   int n = 0;                      /* Number of bytes written */
   99784   if( iCol ){
   99785     char *p = *pp;                /* Output pointer */
   99786     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
   99787     *p = 0x01;
   99788     *pp = &p[n];
   99789   }
   99790   return n;
   99791 }
   99792 
   99793 /*
   99794 **
   99795 */
   99796 static void fts3PoslistMerge(
   99797   char **pp,                      /* Output buffer */
   99798   char **pp1,                     /* Left input list */
   99799   char **pp2                      /* Right input list */
   99800 ){
   99801   char *p = *pp;
   99802   char *p1 = *pp1;
   99803   char *p2 = *pp2;
   99804 
   99805   while( *p1 || *p2 ){
   99806     int iCol1;
   99807     int iCol2;
   99808 
   99809     if( *p1==0x01 ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
   99810     else if( *p1==0x00 ) iCol1 = OFFSET_LIST_END;
   99811     else iCol1 = 0;
   99812 
   99813     if( *p2==0x01 ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
   99814     else if( *p2==0x00 ) iCol2 = OFFSET_LIST_END;
   99815     else iCol2 = 0;
   99816 
   99817     if( iCol1==iCol2 ){
   99818       sqlite3_int64 i1 = 0;
   99819       sqlite3_int64 i2 = 0;
   99820       sqlite3_int64 iPrev = 0;
   99821       int n = fts3PutColNumber(&p, iCol1);
   99822       p1 += n;
   99823       p2 += n;
   99824 
   99825       /* At this point, both p1 and p2 point to the start of offset-lists.
   99826       ** An offset-list is a list of non-negative delta-encoded varints, each
   99827       ** incremented by 2 before being stored. Each list is terminated by a 0
   99828       ** or 1 value (0x00 or 0x01). The following block merges the two lists
   99829       ** and writes the results to buffer p. p is left pointing to the byte
   99830       ** after the list written. No terminator (0x00 or 0x01) is written to
   99831       ** the output.
   99832       */
   99833       fts3GetDeltaVarint(&p1, &i1);
   99834       fts3GetDeltaVarint(&p2, &i2);
   99835       do {
   99836         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
   99837         iPrev -= 2;
   99838         if( i1==i2 ){
   99839           fts3ReadNextPos(&p1, &i1);
   99840           fts3ReadNextPos(&p2, &i2);
   99841         }else if( i1<i2 ){
   99842           fts3ReadNextPos(&p1, &i1);
   99843         }else{
   99844           fts3ReadNextPos(&p2, &i2);
   99845         }
   99846       }while( i1!=OFFSET_LIST_END || i2!=OFFSET_LIST_END );
   99847     }else if( iCol1<iCol2 ){
   99848       p1 += fts3PutColNumber(&p, iCol1);
   99849       fts3ColumnlistCopy(&p, &p1);
   99850     }else{
   99851       p2 += fts3PutColNumber(&p, iCol2);
   99852       fts3ColumnlistCopy(&p, &p2);
   99853     }
   99854   }
   99855 
   99856   *p++ = '\0';
   99857   *pp = p;
   99858   *pp1 = p1 + 1;
   99859   *pp2 = p2 + 1;
   99860 }
   99861 
   99862 /*
   99863 ** nToken==1 searches for adjacent positions.
   99864 */
   99865 static int fts3PoslistPhraseMerge(
   99866   char **pp,                      /* Output buffer */
   99867   int nToken,                     /* Maximum difference in token positions */
   99868   int isSaveLeft,                 /* Save the left position */
   99869   char **pp1,                     /* Left input list */
   99870   char **pp2                      /* Right input list */
   99871 ){
   99872   char *p = (pp ? *pp : 0);
   99873   char *p1 = *pp1;
   99874   char *p2 = *pp2;
   99875 
   99876   int iCol1 = 0;
   99877   int iCol2 = 0;
   99878   assert( *p1!=0 && *p2!=0 );
   99879   if( *p1==0x01 ){
   99880     p1++;
   99881     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
   99882   }
   99883   if( *p2==0x01 ){
   99884     p2++;
   99885     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
   99886   }
   99887 
   99888   while( 1 ){
   99889     if( iCol1==iCol2 ){
   99890       char *pSave = p;
   99891       sqlite3_int64 iPrev = 0;
   99892       sqlite3_int64 iPos1 = 0;
   99893       sqlite3_int64 iPos2 = 0;
   99894 
   99895       if( pp && iCol1 ){
   99896         *p++ = 0x01;
   99897         p += sqlite3Fts3PutVarint(p, iCol1);
   99898       }
   99899 
   99900       assert( *p1!=0x00 && *p2!=0x00 && *p1!=0x01 && *p2!=0x01 );
   99901       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
   99902       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
   99903 
   99904       while( 1 ){
   99905         if( iPos2>iPos1 && iPos2<=iPos1+nToken ){
   99906           sqlite3_int64 iSave;
   99907           if( !pp ){
   99908             fts3PoslistCopy(0, &p2);
   99909             fts3PoslistCopy(0, &p1);
   99910             *pp1 = p1;
   99911             *pp2 = p2;
   99912             return 1;
   99913           }
   99914           iSave = isSaveLeft ? iPos1 : iPos2;
   99915           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
   99916           pSave = 0;
   99917         }
   99918         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
   99919           if( (*p2&0xFE)==0 ) break;
   99920           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
   99921         }else{
   99922           if( (*p1&0xFE)==0 ) break;
   99923           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
   99924         }
   99925       }
   99926 
   99927       if( pSave ){
   99928         assert( pp && p );
   99929         p = pSave;
   99930       }
   99931 
   99932       fts3ColumnlistCopy(0, &p1);
   99933       fts3ColumnlistCopy(0, &p2);
   99934       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
   99935       if( 0==*p1 || 0==*p2 ) break;
   99936 
   99937       p1++;
   99938       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
   99939       p2++;
   99940       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
   99941     }
   99942 
   99943     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
   99944     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
   99945     ** end of the position list, or the 0x01 that precedes the next
   99946     ** column-number in the position list.
   99947     */
   99948     else if( iCol1<iCol2 ){
   99949       fts3ColumnlistCopy(0, &p1);
   99950       if( 0==*p1 ) break;
   99951       p1++;
   99952       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
   99953     }else{
   99954       fts3ColumnlistCopy(0, &p2);
   99955       if( 0==*p2 ) break;
   99956       p2++;
   99957       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
   99958     }
   99959   }
   99960 
   99961   fts3PoslistCopy(0, &p2);
   99962   fts3PoslistCopy(0, &p1);
   99963   *pp1 = p1;
   99964   *pp2 = p2;
   99965   if( !pp || *pp==p ){
   99966     return 0;
   99967   }
   99968   *p++ = 0x00;
   99969   *pp = p;
   99970   return 1;
   99971 }
   99972 
   99973 /*
   99974 ** Merge two position-lists as required by the NEAR operator.
   99975 */
   99976 static int fts3PoslistNearMerge(
   99977   char **pp,                      /* Output buffer */
   99978   char *aTmp,                     /* Temporary buffer space */
   99979   int nRight,                     /* Maximum difference in token positions */
   99980   int nLeft,                      /* Maximum difference in token positions */
   99981   char **pp1,                     /* IN/OUT: Left input list */
   99982   char **pp2                      /* IN/OUT: Right input list */
   99983 ){
   99984   char *p1 = *pp1;
   99985   char *p2 = *pp2;
   99986 
   99987   if( !pp ){
   99988     if( fts3PoslistPhraseMerge(0, nRight, 0, pp1, pp2) ) return 1;
   99989     *pp1 = p1;
   99990     *pp2 = p2;
   99991     return fts3PoslistPhraseMerge(0, nLeft, 0, pp2, pp1);
   99992   }else{
   99993     char *pTmp1 = aTmp;
   99994     char *pTmp2;
   99995     char *aTmp2;
   99996     int res = 1;
   99997 
   99998     fts3PoslistPhraseMerge(&pTmp1, nRight, 0, pp1, pp2);
   99999     aTmp2 = pTmp2 = pTmp1;
   100000     *pp1 = p1;
   100001     *pp2 = p2;
   100002     fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, pp2, pp1);
   100003     if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
   100004       fts3PoslistMerge(pp, &aTmp, &aTmp2);
   100005     }else if( pTmp1!=aTmp ){
   100006       fts3PoslistCopy(pp, &aTmp);
   100007     }else if( pTmp2!=aTmp2 ){
   100008       fts3PoslistCopy(pp, &aTmp2);
   100009     }else{
   100010       res = 0;
   100011     }
   100012 
   100013     return res;
   100014   }
   100015 }
   100016 
   100017 /*
   100018 ** Values that may be used as the first parameter to fts3DoclistMerge().
   100019 */
   100020 #define MERGE_NOT        2        /* D + D -> D */
   100021 #define MERGE_AND        3        /* D + D -> D */
   100022 #define MERGE_OR         4        /* D + D -> D */
   100023 #define MERGE_POS_OR     5        /* P + P -> P */
   100024 #define MERGE_PHRASE     6        /* P + P -> D */
   100025 #define MERGE_POS_PHRASE 7        /* P + P -> P */
   100026 #define MERGE_NEAR       8        /* P + P -> D */
   100027 #define MERGE_POS_NEAR   9        /* P + P -> P */
   100028 
   100029 /*
   100030 ** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
   100031 ** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
   100032 ** which is guaranteed to be large enough to hold the results. The number
   100033 ** of bytes written to aBuffer is stored in *pnBuffer before returning.
   100034 **
   100035 ** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
   100036 ** occurs while allocating a temporary buffer as part of the merge operation,
   100037 ** SQLITE_NOMEM is returned.
   100038 */
   100039 static int fts3DoclistMerge(
   100040   int mergetype,                  /* One of the MERGE_XXX constants */
   100041   int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
   100042   int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
   100043   char *aBuffer,                  /* Pre-allocated output buffer */
   100044   int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
   100045   char *a1,                       /* Buffer containing first doclist */
   100046   int n1,                         /* Size of buffer a1 */
   100047   char *a2,                       /* Buffer containing second doclist */
   100048   int n2                          /* Size of buffer a2 */
   100049 ){
   100050   sqlite3_int64 i1 = 0;
   100051   sqlite3_int64 i2 = 0;
   100052   sqlite3_int64 iPrev = 0;
   100053 
   100054   char *p = aBuffer;
   100055   char *p1 = a1;
   100056   char *p2 = a2;
   100057   char *pEnd1 = &a1[n1];
   100058   char *pEnd2 = &a2[n2];
   100059 
   100060   assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR
   100061        || mergetype==MERGE_AND    || mergetype==MERGE_NOT
   100062        || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
   100063        || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
   100064   );
   100065 
   100066   if( !aBuffer ){
   100067     *pnBuffer = 0;
   100068     return SQLITE_NOMEM;
   100069   }
   100070 
   100071   /* Read the first docid from each doclist */
   100072   fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   100073   fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   100074 
   100075   switch( mergetype ){
   100076     case MERGE_OR:
   100077     case MERGE_POS_OR:
   100078       while( p1 || p2 ){
   100079         if( p2 && p1 && i1==i2 ){
   100080           fts3PutDeltaVarint(&p, &iPrev, i1);
   100081           if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
   100082           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   100083           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   100084         }else if( !p2 || (p1 && i1<i2) ){
   100085           fts3PutDeltaVarint(&p, &iPrev, i1);
   100086           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
   100087           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   100088         }else{
   100089           fts3PutDeltaVarint(&p, &iPrev, i2);
   100090           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
   100091           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   100092         }
   100093       }
   100094       break;
   100095 
   100096     case MERGE_AND:
   100097       while( p1 && p2 ){
   100098         if( i1==i2 ){
   100099           fts3PutDeltaVarint(&p, &iPrev, i1);
   100100           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   100101           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   100102         }else if( i1<i2 ){
   100103           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   100104         }else{
   100105           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   100106         }
   100107       }
   100108       break;
   100109 
   100110     case MERGE_NOT:
   100111       while( p1 ){
   100112         if( p2 && i1==i2 ){
   100113           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   100114           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   100115         }else if( !p2 || i1<i2 ){
   100116           fts3PutDeltaVarint(&p, &iPrev, i1);
   100117           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   100118         }else{
   100119           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   100120         }
   100121       }
   100122       break;
   100123 
   100124     case MERGE_POS_PHRASE:
   100125     case MERGE_PHRASE: {
   100126       char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
   100127       while( p1 && p2 ){
   100128         if( i1==i2 ){
   100129           char *pSave = p;
   100130           sqlite3_int64 iPrevSave = iPrev;
   100131           fts3PutDeltaVarint(&p, &iPrev, i1);
   100132           if( 0==fts3PoslistPhraseMerge(ppPos, 1, 0, &p1, &p2) ){
   100133             p = pSave;
   100134             iPrev = iPrevSave;
   100135           }
   100136           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   100137           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   100138         }else if( i1<i2 ){
   100139           fts3PoslistCopy(0, &p1);
   100140           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   100141         }else{
   100142           fts3PoslistCopy(0, &p2);
   100143           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   100144         }
   100145       }
   100146       break;
   100147     }
   100148 
   100149     default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
   100150       char *aTmp = 0;
   100151       char **ppPos = 0;
   100152       if( mergetype==MERGE_POS_NEAR ){
   100153         ppPos = &p;
   100154         aTmp = sqlite3_malloc(2*(n1+n2+1));
   100155         if( !aTmp ){
   100156           return SQLITE_NOMEM;
   100157         }
   100158       }
   100159 
   100160       while( p1 && p2 ){
   100161         if( i1==i2 ){
   100162           char *pSave = p;
   100163           sqlite3_int64 iPrevSave = iPrev;
   100164           fts3PutDeltaVarint(&p, &iPrev, i1);
   100165 
   100166           if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
   100167             iPrev = iPrevSave;
   100168             p = pSave;
   100169           }
   100170 
   100171           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   100172           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   100173         }else if( i1<i2 ){
   100174           fts3PoslistCopy(0, &p1);
   100175           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   100176         }else{
   100177           fts3PoslistCopy(0, &p2);
   100178           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   100179         }
   100180       }
   100181       sqlite3_free(aTmp);
   100182       break;
   100183     }
   100184   }
   100185 
   100186   *pnBuffer = (int)(p-aBuffer);
   100187   return SQLITE_OK;
   100188 }
   100189 
   100190 /*
   100191 ** A pointer to an instance of this structure is used as the context
   100192 ** argument to sqlite3Fts3SegReaderIterate()
   100193 */
   100194 typedef struct TermSelect TermSelect;
   100195 struct TermSelect {
   100196   int isReqPos;
   100197   char *aOutput;                  /* Malloc'd output buffer */
   100198   int nOutput;                    /* Size of output in bytes */
   100199 };
   100200 
   100201 /*
   100202 ** This function is used as the sqlite3Fts3SegReaderIterate() callback when
   100203 ** querying the full-text index for a doclist associated with a term or
   100204 ** term-prefix.
   100205 */
   100206 static int fts3TermSelectCb(
   100207   Fts3Table *p,                   /* Virtual table object */
   100208   void *pContext,                 /* Pointer to TermSelect structure */
   100209   char *zTerm,
   100210   int nTerm,
   100211   char *aDoclist,
   100212   int nDoclist
   100213 ){
   100214   TermSelect *pTS = (TermSelect *)pContext;
   100215   int nNew = pTS->nOutput + nDoclist;
   100216   char *aNew = sqlite3_malloc(nNew);
   100217 
   100218   UNUSED_PARAMETER(p);
   100219   UNUSED_PARAMETER(zTerm);
   100220   UNUSED_PARAMETER(nTerm);
   100221 
   100222   if( !aNew ){
   100223     return SQLITE_NOMEM;
   100224   }
   100225 
   100226   if( pTS->nOutput==0 ){
   100227     /* If this is the first term selected, copy the doclist to the output
   100228     ** buffer using memcpy(). TODO: Add a way to transfer control of the
   100229     ** aDoclist buffer from the caller so as to avoid the memcpy().
   100230     */
   100231     memcpy(aNew, aDoclist, nDoclist);
   100232   }else{
   100233     /* The output buffer is not empty. Merge doclist aDoclist with the
   100234     ** existing output. This can only happen with prefix-searches (as
   100235     ** searches for exact terms return exactly one doclist).
   100236     */
   100237     int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
   100238     fts3DoclistMerge(mergetype, 0, 0,
   100239         aNew, &nNew, pTS->aOutput, pTS->nOutput, aDoclist, nDoclist
   100240     );
   100241   }
   100242 
   100243   sqlite3_free(pTS->aOutput);
   100244   pTS->aOutput = aNew;
   100245   pTS->nOutput = nNew;
   100246 
   100247   return SQLITE_OK;
   100248 }
   100249 
   100250 /*
   100251 ** This function retreives the doclist for the specified term (or term
   100252 ** prefix) from the database.
   100253 **
   100254 ** The returned doclist may be in one of two formats, depending on the
   100255 ** value of parameter isReqPos. If isReqPos is zero, then the doclist is
   100256 ** a sorted list of delta-compressed docids. If isReqPos is non-zero,
   100257 ** then the returned list is in the same format as is stored in the
   100258 ** database without the found length specifier at the start of on-disk
   100259 ** doclists.
   100260 */
   100261 static int fts3TermSelect(
   100262   Fts3Table *p,                   /* Virtual table handle */
   100263   int iColumn,                    /* Column to query (or -ve for all columns) */
   100264   const char *zTerm,              /* Term to query for */
   100265   int nTerm,                      /* Size of zTerm in bytes */
   100266   int isPrefix,                   /* True for a prefix search */
   100267   int isReqPos,                   /* True to include position lists in output */
   100268   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
   100269   char **ppOut                    /* OUT: Malloced result buffer */
   100270 ){
   100271   int i;
   100272   TermSelect tsc;
   100273   Fts3SegFilter filter;           /* Segment term filter configuration */
   100274   Fts3SegReader **apSegment;      /* Array of segments to read data from */
   100275   int nSegment = 0;               /* Size of apSegment array */
   100276   int nAlloc = 16;                /* Allocated size of segment array */
   100277   int rc;                         /* Return code */
   100278   sqlite3_stmt *pStmt = 0;        /* SQL statement to scan %_segdir table */
   100279   int iAge = 0;                   /* Used to assign ages to segments */
   100280 
   100281   apSegment = (Fts3SegReader **)sqlite3_malloc(sizeof(Fts3SegReader*)*nAlloc);
   100282   if( !apSegment ) return SQLITE_NOMEM;
   100283   rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &apSegment[0]);
   100284   if( rc!=SQLITE_OK ) goto finished;
   100285   if( apSegment[0] ){
   100286     nSegment = 1;
   100287   }
   100288 
   100289   /* Loop through the entire %_segdir table. For each segment, create a
   100290   ** Fts3SegReader to iterate through the subset of the segment leaves
   100291   ** that may contain a term that matches zTerm/nTerm. For non-prefix
   100292   ** searches, this is always a single leaf. For prefix searches, this
   100293   ** may be a contiguous block of leaves.
   100294   **
   100295   ** The code in this loop does not actually load any leaves into memory
   100296   ** (unless the root node happens to be a leaf). It simply examines the
   100297   ** b-tree structure to determine which leaves need to be inspected.
   100298   */
   100299   rc = sqlite3Fts3AllSegdirs(p, &pStmt);
   100300   while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
   100301     Fts3SegReader *pNew = 0;
   100302     int nRoot = sqlite3_column_bytes(pStmt, 4);
   100303     char const *zRoot = sqlite3_column_blob(pStmt, 4);
   100304     if( sqlite3_column_int64(pStmt, 1)==0 ){
   100305       /* The entire segment is stored on the root node (which must be a
   100306       ** leaf). Do not bother inspecting any data in this case, just
   100307       ** create a Fts3SegReader to scan the single leaf.
   100308       */
   100309       rc = sqlite3Fts3SegReaderNew(p, iAge, 0, 0, 0, zRoot, nRoot, &pNew);
   100310     }else{
   100311       int rc2;                    /* Return value of sqlite3Fts3ReadBlock() */
   100312       sqlite3_int64 i1;           /* Blockid of leaf that may contain zTerm */
   100313       rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &i1);
   100314       if( rc==SQLITE_OK ){
   100315         sqlite3_int64 i2 = sqlite3_column_int64(pStmt, 2);
   100316         rc = sqlite3Fts3SegReaderNew(p, iAge, i1, i2, 0, 0, 0, &pNew);
   100317       }
   100318 
   100319       /* The following call to ReadBlock() serves to reset the SQL statement
   100320       ** used to retrieve blocks of data from the %_segments table. If it is
   100321       ** not reset here, then it may remain classified as an active statement
   100322       ** by SQLite, which may lead to "DROP TABLE" or "DETACH" commands
   100323       ** failing.
   100324       */
   100325       rc2 = sqlite3Fts3ReadBlock(p, 0, 0, 0);
   100326       if( rc==SQLITE_OK ){
   100327         rc = rc2;
   100328       }
   100329     }
   100330     iAge++;
   100331 
   100332     /* If a new Fts3SegReader was allocated, add it to the apSegment array. */
   100333     assert( pNew!=0 || rc!=SQLITE_OK );
   100334     if( pNew ){
   100335       if( nSegment==nAlloc ){
   100336         Fts3SegReader **pArray;
   100337         nAlloc += 16;
   100338         pArray = (Fts3SegReader **)sqlite3_realloc(
   100339             apSegment, nAlloc*sizeof(Fts3SegReader *)
   100340         );
   100341         if( !pArray ){
   100342           sqlite3Fts3SegReaderFree(p, pNew);
   100343           rc = SQLITE_NOMEM;
   100344           goto finished;
   100345         }
   100346         apSegment = pArray;
   100347       }
   100348       apSegment[nSegment++] = pNew;
   100349     }
   100350   }
   100351   if( rc!=SQLITE_DONE ){
   100352     assert( rc!=SQLITE_OK );
   100353     goto finished;
   100354   }
   100355 
   100356   memset(&tsc, 0, sizeof(TermSelect));
   100357   tsc.isReqPos = isReqPos;
   100358 
   100359   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY
   100360         | (isPrefix ? FTS3_SEGMENT_PREFIX : 0)
   100361         | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
   100362         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
   100363   filter.iCol = iColumn;
   100364   filter.zTerm = zTerm;
   100365   filter.nTerm = nTerm;
   100366 
   100367   rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment, &filter,
   100368       fts3TermSelectCb, (void *)&tsc
   100369   );
   100370 
   100371   if( rc==SQLITE_OK ){
   100372     *ppOut = tsc.aOutput;
   100373     *pnOut = tsc.nOutput;
   100374   }else{
   100375     sqlite3_free(tsc.aOutput);
   100376   }
   100377 
   100378 finished:
   100379   sqlite3_reset(pStmt);
   100380   for(i=0; i<nSegment; i++){
   100381     sqlite3Fts3SegReaderFree(p, apSegment[i]);
   100382   }
   100383   sqlite3_free(apSegment);
   100384   return rc;
   100385 }
   100386 
   100387 
   100388 /*
   100389 ** Return a DocList corresponding to the phrase *pPhrase.
   100390 */
   100391 static int fts3PhraseSelect(
   100392   Fts3Table *p,                   /* Virtual table handle */
   100393   Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
   100394   int isReqPos,                   /* True if output should contain positions */
   100395   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
   100396   int *pnOut                      /* OUT: Size of buffer at *paOut */
   100397 ){
   100398   char *pOut = 0;
   100399   int nOut = 0;
   100400   int rc = SQLITE_OK;
   100401   int ii;
   100402   int iCol = pPhrase->iColumn;
   100403   int isTermPos = (pPhrase->nToken>1 || isReqPos);
   100404 
   100405   for(ii=0; ii<pPhrase->nToken; ii++){
   100406     struct PhraseToken *pTok = &pPhrase->aToken[ii];
   100407     char *z = pTok->z;            /* Next token of the phrase */
   100408     int n = pTok->n;              /* Size of z in bytes */
   100409     int isPrefix = pTok->isPrefix;/* True if token is a prefix */
   100410     char *pList;                  /* Pointer to token doclist */
   100411     int nList;                    /* Size of buffer at pList */
   100412 
   100413     rc = fts3TermSelect(p, iCol, z, n, isPrefix, isTermPos, &nList, &pList);
   100414     if( rc!=SQLITE_OK ) break;
   100415 
   100416     if( ii==0 ){
   100417       pOut = pList;
   100418       nOut = nList;
   100419     }else{
   100420       /* Merge the new term list and the current output. If this is the
   100421       ** last term in the phrase, and positions are not required in the
   100422       ** output of this function, the positions can be dropped as part
   100423       ** of this merge. Either way, the result of this merge will be
   100424       ** smaller than nList bytes. The code in fts3DoclistMerge() is written
   100425       ** so that it is safe to use pList as the output as well as an input
   100426       ** in this case.
   100427       */
   100428       int mergetype = MERGE_POS_PHRASE;
   100429       if( ii==pPhrase->nToken-1 && !isReqPos ){
   100430         mergetype = MERGE_PHRASE;
   100431       }
   100432       fts3DoclistMerge(mergetype, 0, 0, pList, &nOut, pOut, nOut, pList, nList);
   100433       sqlite3_free(pOut);
   100434       pOut = pList;
   100435     }
   100436     assert( nOut==0 || pOut!=0 );
   100437   }
   100438 
   100439   if( rc==SQLITE_OK ){
   100440     *paOut = pOut;
   100441     *pnOut = nOut;
   100442   }else{
   100443     sqlite3_free(pOut);
   100444   }
   100445   return rc;
   100446 }
   100447 
   100448 /*
   100449 ** Evaluate the full-text expression pExpr against fts3 table pTab. Store
   100450 ** the resulting doclist in *paOut and *pnOut.
   100451 */
   100452 static int evalFts3Expr(
   100453   Fts3Table *p,                   /* Virtual table handle */
   100454   Fts3Expr *pExpr,                /* Parsed fts3 expression */
   100455   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
   100456   int *pnOut,                     /* OUT: Size of buffer at *paOut */
   100457   int isReqPos                    /* Require positions in output buffer */
   100458 ){
   100459   int rc = SQLITE_OK;             /* Return code */
   100460 
   100461   /* Zero the output parameters. */
   100462   *paOut = 0;
   100463   *pnOut = 0;
   100464 
   100465   if( pExpr ){
   100466     assert( pExpr->eType==FTSQUERY_PHRASE
   100467          || pExpr->eType==FTSQUERY_NEAR
   100468          || isReqPos==0
   100469     );
   100470     if( pExpr->eType==FTSQUERY_PHRASE ){
   100471       rc = fts3PhraseSelect(p, pExpr->pPhrase,
   100472           isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
   100473           paOut, pnOut
   100474       );
   100475     }else{
   100476       char *aLeft;
   100477       char *aRight;
   100478       int nLeft;
   100479       int nRight;
   100480 
   100481       if( 0==(rc = evalFts3Expr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
   100482        && 0==(rc = evalFts3Expr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
   100483       ){
   100484         assert( pExpr->eType==FTSQUERY_NEAR || pExpr->eType==FTSQUERY_OR
   100485             || pExpr->eType==FTSQUERY_AND  || pExpr->eType==FTSQUERY_NOT
   100486         );
   100487         switch( pExpr->eType ){
   100488           case FTSQUERY_NEAR: {
   100489             Fts3Expr *pLeft;
   100490             Fts3Expr *pRight;
   100491             int mergetype = isReqPos ? MERGE_POS_NEAR : MERGE_NEAR;
   100492             int nParam1;
   100493             int nParam2;
   100494             char *aBuffer;
   100495 
   100496             if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
   100497               mergetype = MERGE_POS_NEAR;
   100498             }
   100499             pLeft = pExpr->pLeft;
   100500             while( pLeft->eType==FTSQUERY_NEAR ){
   100501               pLeft=pLeft->pRight;
   100502             }
   100503             pRight = pExpr->pRight;
   100504             assert( pRight->eType==FTSQUERY_PHRASE );
   100505             assert( pLeft->eType==FTSQUERY_PHRASE );
   100506 
   100507             nParam1 = pExpr->nNear+1;
   100508             nParam2 = nParam1+pLeft->pPhrase->nToken+pRight->pPhrase->nToken-2;
   100509             aBuffer = sqlite3_malloc(nLeft+nRight+1);
   100510             rc = fts3DoclistMerge(mergetype, nParam1, nParam2, aBuffer,
   100511                 pnOut, aLeft, nLeft, aRight, nRight
   100512             );
   100513             if( rc!=SQLITE_OK ){
   100514               sqlite3_free(aBuffer);
   100515             }else{
   100516               *paOut = aBuffer;
   100517             }
   100518             sqlite3_free(aLeft);
   100519             break;
   100520           }
   100521 
   100522           case FTSQUERY_OR: {
   100523             /* Allocate a buffer for the output. The maximum size is the
   100524             ** sum of the sizes of the two input buffers. The +1 term is
   100525             ** so that a buffer of zero bytes is never allocated - this can
   100526             ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
   100527             */
   100528             char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
   100529             rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
   100530                 aLeft, nLeft, aRight, nRight
   100531             );
   100532             *paOut = aBuffer;
   100533             sqlite3_free(aLeft);
   100534             break;
   100535           }
   100536 
   100537           default: {
   100538             assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
   100539             fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
   100540                 aLeft, nLeft, aRight, nRight
   100541             );
   100542             *paOut = aLeft;
   100543             break;
   100544           }
   100545         }
   100546       }
   100547       sqlite3_free(aRight);
   100548     }
   100549   }
   100550 
   100551   return rc;
   100552 }
   100553 
   100554 /*
   100555 ** This is the xFilter interface for the virtual table.  See
   100556 ** the virtual table xFilter method documentation for additional
   100557 ** information.
   100558 **
   100559 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
   100560 ** the %_content table.
   100561 **
   100562 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
   100563 ** in the %_content table.
   100564 **
   100565 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
   100566 ** column on the left-hand side of the MATCH operator is column
   100567 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
   100568 ** side of the MATCH operator.
   100569 */
   100570 /* TODO(shess) Upgrade the cursor initialization and destruction to
   100571 ** account for fts3FilterMethod() being called multiple times on the
   100572 ** same cursor. The current solution is very fragile. Apply fix to
   100573 ** fts3 as appropriate.
   100574 */
   100575 static int fts3FilterMethod(
   100576   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   100577   int idxNum,                     /* Strategy index */
   100578   const char *idxStr,             /* Unused */
   100579   int nVal,                       /* Number of elements in apVal */
   100580   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   100581 ){
   100582   const char *azSql[] = {
   100583     "SELECT * FROM %Q.'%q_content' WHERE docid = ?", /* non-full-table-scan */
   100584     "SELECT * FROM %Q.'%q_content'",                 /* full-table-scan */
   100585   };
   100586   int rc;                         /* Return code */
   100587   char *zSql;                     /* SQL statement used to access %_content */
   100588   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
   100589   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   100590 
   100591   UNUSED_PARAMETER(idxStr);
   100592   UNUSED_PARAMETER(nVal);
   100593 
   100594   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
   100595   assert( nVal==0 || nVal==1 );
   100596   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
   100597 
   100598   /* In case the cursor has been used before, clear it now. */
   100599   sqlite3_finalize(pCsr->pStmt);
   100600   sqlite3_free(pCsr->aDoclist);
   100601   sqlite3Fts3ExprFree(pCsr->pExpr);
   100602   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
   100603 
   100604   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
   100605   ** statement loops through all rows of the %_content table. For a
   100606   ** full-text query or docid lookup, the statement retrieves a single
   100607   ** row by docid.
   100608   */
   100609   zSql = sqlite3_mprintf(azSql[idxNum==FTS3_FULLSCAN_SEARCH], p->zDb, p->zName);
   100610   if( !zSql ){
   100611     rc = SQLITE_NOMEM;
   100612   }else{
   100613     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
   100614     sqlite3_free(zSql);
   100615   }
   100616   if( rc!=SQLITE_OK ) return rc;
   100617   pCsr->eSearch = (i16)idxNum;
   100618 
   100619   if( idxNum==FTS3_DOCID_SEARCH ){
   100620     rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
   100621   }else if( idxNum!=FTS3_FULLSCAN_SEARCH ){
   100622     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
   100623     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
   100624 
   100625     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
   100626       return SQLITE_NOMEM;
   100627     }
   100628 
   100629     rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn,
   100630         iCol, zQuery, -1, &pCsr->pExpr
   100631     );
   100632     if( rc!=SQLITE_OK ) return rc;
   100633 
   100634     rc = evalFts3Expr(p, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
   100635     pCsr->pNextId = pCsr->aDoclist;
   100636     pCsr->iPrevId = 0;
   100637   }
   100638 
   100639   if( rc!=SQLITE_OK ) return rc;
   100640   return fts3NextMethod(pCursor);
   100641 }
   100642 
   100643 /*
   100644 ** This is the xEof method of the virtual table. SQLite calls this
   100645 ** routine to find out if it has reached the end of a result set.
   100646 */
   100647 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
   100648   return ((Fts3Cursor *)pCursor)->isEof;
   100649 }
   100650 
   100651 /*
   100652 ** This is the xRowid method. The SQLite core calls this routine to
   100653 ** retrieve the rowid for the current row of the result set. fts3
   100654 ** exposes %_content.docid as the rowid for the virtual table. The
   100655 ** rowid should be written to *pRowid.
   100656 */
   100657 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
   100658   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
   100659   if( pCsr->aDoclist ){
   100660     *pRowid = pCsr->iPrevId;
   100661   }else{
   100662     *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
   100663   }
   100664   return SQLITE_OK;
   100665 }
   100666 
   100667 /*
   100668 ** This is the xColumn method, called by SQLite to request a value from
   100669 ** the row that the supplied cursor currently points to.
   100670 */
   100671 static int fts3ColumnMethod(
   100672   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   100673   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
   100674   int iCol                        /* Index of column to read value from */
   100675 ){
   100676   int rc;                         /* Return Code */
   100677   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
   100678   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
   100679 
   100680   /* The column value supplied by SQLite must be in range. */
   100681   assert( iCol>=0 && iCol<=p->nColumn+1 );
   100682 
   100683   if( iCol==p->nColumn+1 ){
   100684     /* This call is a request for the "docid" column. Since "docid" is an
   100685     ** alias for "rowid", use the xRowid() method to obtain the value.
   100686     */
   100687     sqlite3_int64 iRowid;
   100688     rc = fts3RowidMethod(pCursor, &iRowid);
   100689     sqlite3_result_int64(pContext, iRowid);
   100690   }else if( iCol==p->nColumn ){
   100691     /* The extra column whose name is the same as the table.
   100692     ** Return a blob which is a pointer to the cursor.
   100693     */
   100694     sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
   100695     rc = SQLITE_OK;
   100696   }else{
   100697     rc = fts3CursorSeek(0, pCsr);
   100698     if( rc==SQLITE_OK ){
   100699       sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
   100700     }
   100701   }
   100702   return rc;
   100703 }
   100704 
   100705 /*
   100706 ** This function is the implementation of the xUpdate callback used by
   100707 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
   100708 ** inserted, updated or deleted.
   100709 */
   100710 static int fts3UpdateMethod(
   100711   sqlite3_vtab *pVtab,            /* Virtual table handle */
   100712   int nArg,                       /* Size of argument array */
   100713   sqlite3_value **apVal,          /* Array of arguments */
   100714   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
   100715 ){
   100716   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
   100717 }
   100718 
   100719 /*
   100720 ** Implementation of xSync() method. Flush the contents of the pending-terms
   100721 ** hash-table to the database.
   100722 */
   100723 static int fts3SyncMethod(sqlite3_vtab *pVtab){
   100724   return sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
   100725 }
   100726 
   100727 /*
   100728 ** Implementation of xBegin() method. This is a no-op.
   100729 */
   100730 static int fts3BeginMethod(sqlite3_vtab *pVtab){
   100731   UNUSED_PARAMETER(pVtab);
   100732   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
   100733   return SQLITE_OK;
   100734 }
   100735 
   100736 /*
   100737 ** Implementation of xCommit() method. This is a no-op. The contents of
   100738 ** the pending-terms hash-table have already been flushed into the database
   100739 ** by fts3SyncMethod().
   100740 */
   100741 static int fts3CommitMethod(sqlite3_vtab *pVtab){
   100742   UNUSED_PARAMETER(pVtab);
   100743   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
   100744   return SQLITE_OK;
   100745 }
   100746 
   100747 /*
   100748 ** Implementation of xRollback(). Discard the contents of the pending-terms
   100749 ** hash-table. Any changes made to the database are reverted by SQLite.
   100750 */
   100751 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
   100752   sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
   100753   return SQLITE_OK;
   100754 }
   100755 
   100756 /*
   100757 ** Load the doclist associated with expression pExpr to pExpr->aDoclist.
   100758 ** The loaded doclist contains positions as well as the document ids.
   100759 ** This is used by the matchinfo(), snippet() and offsets() auxillary
   100760 ** functions.
   100761 */
   100762 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *pTab, Fts3Expr *pExpr){
   100763   return evalFts3Expr(pTab, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
   100764 }
   100765 
   100766 /*
   100767 ** After ExprLoadDoclist() (see above) has been called, this function is
   100768 ** used to iterate through the position lists that make up the doclist
   100769 ** stored in pExpr->aDoclist.
   100770 */
   100771 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
   100772   Fts3Expr *pExpr,                /* Access this expressions doclist */
   100773   sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
   100774   int iCol                        /* Column of requested pos-list */
   100775 ){
   100776   assert( pExpr->isLoaded );
   100777   if( pExpr->aDoclist ){
   100778     char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
   100779     char *pCsr = pExpr->pCurrent;
   100780 
   100781     assert( pCsr );
   100782     while( pCsr<pEnd ){
   100783       if( pExpr->iCurrent<iDocid ){
   100784         fts3PoslistCopy(0, &pCsr);
   100785         fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
   100786         pExpr->pCurrent = pCsr;
   100787       }else{
   100788         if( pExpr->iCurrent==iDocid ){
   100789           int iThis = 0;
   100790           if( iCol<0 ){
   100791             /* If iCol is negative, return a pointer to the start of the
   100792             ** position-list (instead of a pointer to the start of a list
   100793             ** of offsets associated with a specific column).
   100794             */
   100795             return pCsr;
   100796           }
   100797           while( iThis<iCol ){
   100798             fts3ColumnlistCopy(0, &pCsr);
   100799             if( *pCsr==0x00 ) return 0;
   100800             pCsr++;
   100801             pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
   100802           }
   100803           if( iCol==iThis ) return pCsr;
   100804         }
   100805         return 0;
   100806       }
   100807     }
   100808   }
   100809 
   100810   return 0;
   100811 }
   100812 
   100813 /*
   100814 ** Helper function used by the implementation of the overloaded snippet(),
   100815 ** offsets() and optimize() SQL functions.
   100816 **
   100817 ** If the value passed as the third argument is a blob of size
   100818 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
   100819 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
   100820 ** message is written to context pContext and SQLITE_ERROR returned. The
   100821 ** string passed via zFunc is used as part of the error message.
   100822 */
   100823 static int fts3FunctionArg(
   100824   sqlite3_context *pContext,      /* SQL function call context */
   100825   const char *zFunc,              /* Function name */
   100826   sqlite3_value *pVal,            /* argv[0] passed to function */
   100827   Fts3Cursor **ppCsr         /* OUT: Store cursor handle here */
   100828 ){
   100829   Fts3Cursor *pRet;
   100830   if( sqlite3_value_type(pVal)!=SQLITE_BLOB
   100831    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
   100832   ){
   100833     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
   100834     sqlite3_result_error(pContext, zErr, -1);
   100835     sqlite3_free(zErr);
   100836     return SQLITE_ERROR;
   100837   }
   100838   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
   100839   *ppCsr = pRet;
   100840   return SQLITE_OK;
   100841 }
   100842 
   100843 /*
   100844 ** Implementation of the snippet() function for FTS3
   100845 */
   100846 static void fts3SnippetFunc(
   100847   sqlite3_context *pContext,      /* SQLite function call context */
   100848   int nVal,                       /* Size of apVal[] array */
   100849   sqlite3_value **apVal           /* Array of arguments */
   100850 ){
   100851   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   100852   const char *zStart = "<b>";
   100853   const char *zEnd = "</b>";
   100854   const char *zEllipsis = "<b>...</b>";
   100855 
   100856   /* There must be at least one argument passed to this function (otherwise
   100857   ** the non-overloaded version would have been called instead of this one).
   100858   */
   100859   assert( nVal>=1 );
   100860 
   100861   if( nVal>4 ){
   100862     sqlite3_result_error(pContext,
   100863         "wrong number of arguments to function snippet()", -1);
   100864     return;
   100865   }
   100866   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
   100867 
   100868   switch( nVal ){
   100869     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
   100870     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
   100871     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
   100872   }
   100873   if( !zEllipsis || !zEnd || !zStart ){
   100874     sqlite3_result_error_nomem(pContext);
   100875   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
   100876     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis);
   100877   }
   100878 }
   100879 
   100880 /*
   100881 ** Implementation of the snippet2() function for FTS3
   100882 */
   100883 static void fts3Snippet2Func(
   100884   sqlite3_context *pContext,      /* SQLite function call context */
   100885   int nVal,                       /* Size of apVal[] array */
   100886   sqlite3_value **apVal           /* Array of arguments */
   100887 ){
   100888   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   100889   const char *zStart = "<b>";
   100890   const char *zEnd = "</b>";
   100891   const char *zEllipsis = "<b>...</b>";
   100892   int iCol = -1;
   100893   int nToken = 10;
   100894 
   100895   /* There must be at least one argument passed to this function (otherwise
   100896   ** the non-overloaded version would have been called instead of this one).
   100897   */
   100898   assert( nVal>=1 );
   100899 
   100900   if( nVal>6 ){
   100901     sqlite3_result_error(pContext,
   100902         "wrong number of arguments to function snippet()", -1);
   100903     return;
   100904   }
   100905   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
   100906 
   100907   switch( nVal ){
   100908     case 6: nToken = sqlite3_value_int(apVal[5]);
   100909     case 5: iCol = sqlite3_value_int(apVal[4]);
   100910     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
   100911     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
   100912     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
   100913   }
   100914   if( !zEllipsis || !zEnd || !zStart ){
   100915     sqlite3_result_error_nomem(pContext);
   100916   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
   100917     sqlite3Fts3Snippet2(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
   100918   }
   100919 }
   100920 
   100921 /*
   100922 ** Implementation of the offsets() function for FTS3
   100923 */
   100924 static void fts3OffsetsFunc(
   100925   sqlite3_context *pContext,      /* SQLite function call context */
   100926   int nVal,                       /* Size of argument array */
   100927   sqlite3_value **apVal           /* Array of arguments */
   100928 ){
   100929   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   100930 
   100931   UNUSED_PARAMETER(nVal);
   100932 
   100933   assert( nVal==1 );
   100934   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
   100935   assert( pCsr );
   100936   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
   100937     sqlite3Fts3Offsets(pContext, pCsr);
   100938   }
   100939 }
   100940 
   100941 /*
   100942 ** Implementation of the special optimize() function for FTS3. This
   100943 ** function merges all segments in the database to a single segment.
   100944 ** Example usage is:
   100945 **
   100946 **   SELECT optimize(t) FROM t LIMIT 1;
   100947 **
   100948 ** where 't' is the name of an FTS3 table.
   100949 */
   100950 static void fts3OptimizeFunc(
   100951   sqlite3_context *pContext,      /* SQLite function call context */
   100952   int nVal,                       /* Size of argument array */
   100953   sqlite3_value **apVal           /* Array of arguments */
   100954 ){
   100955   int rc;                         /* Return code */
   100956   Fts3Table *p;                   /* Virtual table handle */
   100957   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
   100958 
   100959   UNUSED_PARAMETER(nVal);
   100960 
   100961   assert( nVal==1 );
   100962   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
   100963   p = (Fts3Table *)pCursor->base.pVtab;
   100964   assert( p );
   100965 
   100966   rc = sqlite3Fts3Optimize(p);
   100967 
   100968   switch( rc ){
   100969     case SQLITE_OK:
   100970       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
   100971       break;
   100972     case SQLITE_DONE:
   100973       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
   100974       break;
   100975     default:
   100976       sqlite3_result_error_code(pContext, rc);
   100977       break;
   100978   }
   100979 }
   100980 
   100981 /*
   100982 ** Implementation of the matchinfo() function for FTS3
   100983 */
   100984 static void fts3MatchinfoFunc(
   100985   sqlite3_context *pContext,      /* SQLite function call context */
   100986   int nVal,                       /* Size of argument array */
   100987   sqlite3_value **apVal           /* Array of arguments */
   100988 ){
   100989   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   100990 
   100991   if( nVal!=1 ){
   100992     sqlite3_result_error(pContext,
   100993         "wrong number of arguments to function matchinfo()", -1);
   100994     return;
   100995   }
   100996 
   100997   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
   100998     sqlite3Fts3Matchinfo(pContext, pCsr);
   100999   }
   101000 }
   101001 
   101002 /*
   101003 ** This routine implements the xFindFunction method for the FTS3
   101004 ** virtual table.
   101005 */
   101006 static int fts3FindFunctionMethod(
   101007   sqlite3_vtab *pVtab,            /* Virtual table handle */
   101008   int nArg,                       /* Number of SQL function arguments */
   101009   const char *zName,              /* Name of SQL function */
   101010   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
   101011   void **ppArg                    /* Unused */
   101012 ){
   101013   struct Overloaded {
   101014     const char *zName;
   101015     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   101016   } aOverload[] = {
   101017     { "snippet", fts3SnippetFunc },
   101018     { "snippet2", fts3Snippet2Func },
   101019     { "offsets", fts3OffsetsFunc },
   101020     { "optimize", fts3OptimizeFunc },
   101021     { "matchinfo", fts3MatchinfoFunc },
   101022   };
   101023   int i;                          /* Iterator variable */
   101024 
   101025   UNUSED_PARAMETER(pVtab);
   101026   UNUSED_PARAMETER(nArg);
   101027   UNUSED_PARAMETER(ppArg);
   101028 
   101029   for(i=0; i<SizeofArray(aOverload); i++){
   101030     if( strcmp(zName, aOverload[i].zName)==0 ){
   101031       *pxFunc = aOverload[i].xFunc;
   101032       return 1;
   101033     }
   101034   }
   101035 
   101036   /* No function of the specified name was found. Return 0. */
   101037   return 0;
   101038 }
   101039 
   101040 /*
   101041 ** Implementation of FTS3 xRename method. Rename an fts3 table.
   101042 */
   101043 static int fts3RenameMethod(
   101044   sqlite3_vtab *pVtab,            /* Virtual table handle */
   101045   const char *zName               /* New name of table */
   101046 ){
   101047   Fts3Table *p = (Fts3Table *)pVtab;
   101048   int rc = SQLITE_NOMEM;          /* Return Code */
   101049   char *zSql;                     /* SQL script to run to rename tables */
   101050 
   101051   zSql = sqlite3_mprintf(
   101052     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
   101053     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
   101054     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
   101055     , p->zDb, p->zName, zName
   101056     , p->zDb, p->zName, zName
   101057     , p->zDb, p->zName, zName
   101058   );
   101059   if( zSql ){
   101060     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
   101061     sqlite3_free(zSql);
   101062   }
   101063   return rc;
   101064 }
   101065 
   101066 static const sqlite3_module fts3Module = {
   101067   /* iVersion      */ 0,
   101068   /* xCreate       */ fts3CreateMethod,
   101069   /* xConnect      */ fts3ConnectMethod,
   101070   /* xBestIndex    */ fts3BestIndexMethod,
   101071   /* xDisconnect   */ fts3DisconnectMethod,
   101072   /* xDestroy      */ fts3DestroyMethod,
   101073   /* xOpen         */ fts3OpenMethod,
   101074   /* xClose        */ fulltextClose,
   101075   /* xFilter       */ fts3FilterMethod,
   101076   /* xNext         */ fts3NextMethod,
   101077   /* xEof          */ fts3EofMethod,
   101078   /* xColumn       */ fts3ColumnMethod,
   101079   /* xRowid        */ fts3RowidMethod,
   101080   /* xUpdate       */ fts3UpdateMethod,
   101081   /* xBegin        */ fts3BeginMethod,
   101082   /* xSync         */ fts3SyncMethod,
   101083   /* xCommit       */ fts3CommitMethod,
   101084   /* xRollback     */ fts3RollbackMethod,
   101085   /* xFindFunction */ fts3FindFunctionMethod,
   101086   /* xRename */       fts3RenameMethod,
   101087 };
   101088 
   101089 /*
   101090 ** This function is registered as the module destructor (called when an
   101091 ** FTS3 enabled database connection is closed). It frees the memory
   101092 ** allocated for the tokenizer hash table.
   101093 */
   101094 static void hashDestroy(void *p){
   101095   Fts3Hash *pHash = (Fts3Hash *)p;
   101096   sqlite3Fts3HashClear(pHash);
   101097   sqlite3_free(pHash);
   101098 }
   101099 
   101100 /*
   101101 ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
   101102 ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
   101103 ** two forward declarations are for functions declared in these files
   101104 ** used to retrieve the respective implementations.
   101105 **
   101106 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
   101107 ** to by the argument to point a the "simple" tokenizer implementation.
   101108 ** Function ...PorterTokenizerModule() sets *pModule to point to the
   101109 ** porter tokenizer/stemmer implementation.
   101110 */
   101111 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   101112 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   101113 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   101114 
   101115 /*
   101116 ** Initialise the fts3 extension. If this extension is built as part
   101117 ** of the sqlite library, then this function is called directly by
   101118 ** SQLite. If fts3 is built as a dynamically loadable extension, this
   101119 ** function is called by the sqlite3_extension_init() entry point.
   101120 */
   101121 // Begin Android change
   101122 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db, const char* registerAs){
   101123 // End Android change
   101124 
   101125   int rc = SQLITE_OK;
   101126   Fts3Hash *pHash = 0;
   101127   const sqlite3_tokenizer_module *pSimple = 0;
   101128   const sqlite3_tokenizer_module *pPorter = 0;
   101129 
   101130 #ifdef SQLITE_ENABLE_ICU
   101131   const sqlite3_tokenizer_module *pIcu = 0;
   101132   sqlite3Fts3IcuTokenizerModule(&pIcu);
   101133 #endif
   101134 
   101135   sqlite3Fts3SimpleTokenizerModule(&pSimple);
   101136   sqlite3Fts3PorterTokenizerModule(&pPorter);
   101137 
   101138   /* Allocate and initialise the hash-table used to store tokenizers. */
   101139   pHash = sqlite3_malloc(sizeof(Fts3Hash));
   101140   if( !pHash ){
   101141     rc = SQLITE_NOMEM;
   101142   }else{
   101143     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
   101144   }
   101145 
   101146   /* Load the built-in tokenizers into the hash table */
   101147   if( rc==SQLITE_OK ){
   101148     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
   101149      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
   101150 #ifdef SQLITE_ENABLE_ICU
   101151      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
   101152 #endif
   101153     ){
   101154       rc = SQLITE_NOMEM;
   101155     }
   101156   }
   101157 
   101158 #ifdef SQLITE_TEST
   101159   if( rc==SQLITE_OK ){
   101160     rc = sqlite3Fts3ExprInitTestInterface(db);
   101161   }
   101162 #endif
   101163 
   101164   /* Create the virtual table wrapper around the hash-table and overload
   101165   ** the two scalar functions. If this is successful, register the
   101166   ** module with sqlite.
   101167   */
   101168   if( SQLITE_OK==rc
   101169    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
   101170    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
   101171    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet2", -1))
   101172    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
   101173    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", -1))
   101174    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
   101175   ){
   101176     // Begin Android change
   101177     /* Also register as fts1 and fts2 */
   101178     return sqlite3_create_module_v2(
   101179         db, registerAs, &fts3Module, (void *)pHash, hashDestroy
   101180     // End Android change
   101181     );
   101182   }
   101183 
   101184   /* An error has occurred. Delete the hash table and return the error code. */
   101185   assert( rc!=SQLITE_OK );
   101186   if( pHash ){
   101187     sqlite3Fts3HashClear(pHash);
   101188     sqlite3_free(pHash);
   101189   }
   101190   return rc;
   101191 }
   101192 
   101193 #if !SQLITE_CORE
   101194 SQLITE_API int sqlite3_extension_init(
   101195   sqlite3 *db,
   101196   char **pzErrMsg,
   101197   const sqlite3_api_routines *pApi
   101198 ){
   101199   SQLITE_EXTENSION_INIT2(pApi)
   101200   return sqlite3Fts3Init(db);
   101201 }
   101202 #endif
   101203 
   101204 #endif
   101205 
   101206 /************** End of fts3.c ************************************************/
   101207 /************** Begin file fts3_expr.c ***************************************/
   101208 /*
   101209 ** 2008 Nov 28
   101210 **
   101211 ** The author disclaims copyright to this source code.  In place of
   101212 ** a legal notice, here is a blessing:
   101213 **
   101214 **    May you do good and not evil.
   101215 **    May you find forgiveness for yourself and forgive others.
   101216 **    May you share freely, never taking more than you give.
   101217 **
   101218 ******************************************************************************
   101219 **
   101220 ** This module contains code that implements a parser for fts3 query strings
   101221 ** (the right-hand argument to the MATCH operator). Because the supported
   101222 ** syntax is relatively simple, the whole tokenizer/parser system is
   101223 ** hand-coded.
   101224 */
   101225 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   101226 
   101227 /*
   101228 ** By default, this module parses the legacy syntax that has been
   101229 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
   101230 ** is defined, then it uses the new syntax. The differences between
   101231 ** the new and the old syntaxes are:
   101232 **
   101233 **  a) The new syntax supports parenthesis. The old does not.
   101234 **
   101235 **  b) The new syntax supports the AND and NOT operators. The old does not.
   101236 **
   101237 **  c) The old syntax supports the "-" token qualifier. This is not
   101238 **     supported by the new syntax (it is replaced by the NOT operator).
   101239 **
   101240 **  d) When using the old syntax, the OR operator has a greater precedence
   101241 **     than an implicit AND. When using the new, both implicity and explicit
   101242 **     AND operators have a higher precedence than OR.
   101243 **
   101244 ** If compiled with SQLITE_TEST defined, then this module exports the
   101245 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
   101246 ** to zero causes the module to use the old syntax. If it is set to
   101247 ** non-zero the new syntax is activated. This is so both syntaxes can
   101248 ** be tested using a single build of testfixture.
   101249 **
   101250 ** The following describes the syntax supported by the fts3 MATCH
   101251 ** operator in a similar format to that used by the lemon parser
   101252 ** generator. This module does not use actually lemon, it uses a
   101253 ** custom parser.
   101254 **
   101255 **   query ::= andexpr (OR andexpr)*.
   101256 **
   101257 **   andexpr ::= notexpr (AND? notexpr)*.
   101258 **
   101259 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
   101260 **   notexpr ::= LP query RP.
   101261 **
   101262 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
   101263 **
   101264 **   distance_opt ::= .
   101265 **   distance_opt ::= / INTEGER.
   101266 **
   101267 **   phrase ::= TOKEN.
   101268 **   phrase ::= COLUMN:TOKEN.
   101269 **   phrase ::= "TOKEN TOKEN TOKEN...".
   101270 */
   101271 
   101272 #ifdef SQLITE_TEST
   101273 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
   101274 #else
   101275 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
   101276 #  define sqlite3_fts3_enable_parentheses 1
   101277 # else
   101278 #  define sqlite3_fts3_enable_parentheses 0
   101279 # endif
   101280 #endif
   101281 
   101282 /*
   101283 ** Default span for NEAR operators.
   101284 */
   101285 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
   101286 
   101287 
   101288 typedef struct ParseContext ParseContext;
   101289 struct ParseContext {
   101290   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
   101291   const char **azCol;                 /* Array of column names for fts3 table */
   101292   int nCol;                           /* Number of entries in azCol[] */
   101293   int iDefaultCol;                    /* Default column to query */
   101294   sqlite3_context *pCtx;              /* Write error message here */
   101295   int nNest;                          /* Number of nested brackets */
   101296 };
   101297 
   101298 /*
   101299 ** This function is equivalent to the standard isspace() function.
   101300 **
   101301 ** The standard isspace() can be awkward to use safely, because although it
   101302 ** is defined to accept an argument of type int, its behaviour when passed
   101303 ** an integer that falls outside of the range of the unsigned char type
   101304 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
   101305 ** is defined to accept an argument of type char, and always returns 0 for
   101306 ** any values that fall outside of the range of the unsigned char type (i.e.
   101307 ** negative values).
   101308 */
   101309 static int fts3isspace(char c){
   101310   return (c&0x80)==0 ? isspace(c) : 0;
   101311 }
   101312 
   101313 /*
   101314 ** Extract the next token from buffer z (length n) using the tokenizer
   101315 ** and other information (column names etc.) in pParse. Create an Fts3Expr
   101316 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
   101317 ** single token and set *ppExpr to point to it. If the end of the buffer is
   101318 ** reached before a token is found, set *ppExpr to zero. It is the
   101319 ** responsibility of the caller to eventually deallocate the allocated
   101320 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
   101321 **
   101322 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
   101323 ** fails.
   101324 */
   101325 static int getNextToken(
   101326   ParseContext *pParse,                   /* fts3 query parse context */
   101327   int iCol,                               /* Value for Fts3Phrase.iColumn */
   101328   const char *z, int n,                   /* Input string */
   101329   Fts3Expr **ppExpr,                      /* OUT: expression */
   101330   int *pnConsumed                         /* OUT: Number of bytes consumed */
   101331 ){
   101332   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
   101333   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   101334   int rc;
   101335   sqlite3_tokenizer_cursor *pCursor;
   101336   Fts3Expr *pRet = 0;
   101337   int nConsumed = 0;
   101338 
   101339   rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
   101340   if( rc==SQLITE_OK ){
   101341     const char *zToken;
   101342     int nToken, iStart, iEnd, iPosition;
   101343     int nByte;                               /* total space to allocate */
   101344 
   101345     pCursor->pTokenizer = pTokenizer;
   101346     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
   101347 
   101348     if( rc==SQLITE_OK ){
   101349       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
   101350       pRet = (Fts3Expr *)sqlite3_malloc(nByte);
   101351       if( !pRet ){
   101352         rc = SQLITE_NOMEM;
   101353       }else{
   101354         memset(pRet, 0, nByte);
   101355         pRet->eType = FTSQUERY_PHRASE;
   101356         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
   101357         pRet->pPhrase->nToken = 1;
   101358         pRet->pPhrase->iColumn = iCol;
   101359         pRet->pPhrase->aToken[0].n = nToken;
   101360         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
   101361         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
   101362 
   101363         if( iEnd<n && z[iEnd]=='*' ){
   101364           pRet->pPhrase->aToken[0].isPrefix = 1;
   101365           iEnd++;
   101366         }
   101367         if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
   101368           pRet->pPhrase->isNot = 1;
   101369         }
   101370       }
   101371       nConsumed = iEnd;
   101372     }
   101373 
   101374     pModule->xClose(pCursor);
   101375   }
   101376 
   101377   *pnConsumed = nConsumed;
   101378   *ppExpr = pRet;
   101379   return rc;
   101380 }
   101381 
   101382 
   101383 /*
   101384 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
   101385 ** then free the old allocation.
   101386 */
   101387 static void *fts3ReallocOrFree(void *pOrig, int nNew){
   101388   void *pRet = sqlite3_realloc(pOrig, nNew);
   101389   if( !pRet ){
   101390     sqlite3_free(pOrig);
   101391   }
   101392   return pRet;
   101393 }
   101394 
   101395 /*
   101396 ** Buffer zInput, length nInput, contains the contents of a quoted string
   101397 ** that appeared as part of an fts3 query expression. Neither quote character
   101398 ** is included in the buffer. This function attempts to tokenize the entire
   101399 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
   101400 ** containing the results.
   101401 **
   101402 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
   101403 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
   101404 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
   101405 ** to 0.
   101406 */
   101407 static int getNextString(
   101408   ParseContext *pParse,                   /* fts3 query parse context */
   101409   const char *zInput, int nInput,         /* Input string */
   101410   Fts3Expr **ppExpr                       /* OUT: expression */
   101411 ){
   101412   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
   101413   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   101414   int rc;
   101415   Fts3Expr *p = 0;
   101416   sqlite3_tokenizer_cursor *pCursor = 0;
   101417   char *zTemp = 0;
   101418   int nTemp = 0;
   101419 
   101420   rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
   101421   if( rc==SQLITE_OK ){
   101422     int ii;
   101423     pCursor->pTokenizer = pTokenizer;
   101424     for(ii=0; rc==SQLITE_OK; ii++){
   101425       const char *zToken;
   101426       int nToken, iBegin, iEnd, iPos;
   101427       rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
   101428       if( rc==SQLITE_OK ){
   101429         int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
   101430         p = fts3ReallocOrFree(p, nByte+ii*sizeof(struct PhraseToken));
   101431         zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
   101432         if( !p || !zTemp ){
   101433           goto no_mem;
   101434         }
   101435         if( ii==0 ){
   101436           memset(p, 0, nByte);
   101437           p->pPhrase = (Fts3Phrase *)&p[1];
   101438         }
   101439         p->pPhrase = (Fts3Phrase *)&p[1];
   101440         p->pPhrase->nToken = ii+1;
   101441         p->pPhrase->aToken[ii].n = nToken;
   101442         memcpy(&zTemp[nTemp], zToken, nToken);
   101443         nTemp += nToken;
   101444         if( iEnd<nInput && zInput[iEnd]=='*' ){
   101445           p->pPhrase->aToken[ii].isPrefix = 1;
   101446         }else{
   101447           p->pPhrase->aToken[ii].isPrefix = 0;
   101448         }
   101449       }
   101450     }
   101451 
   101452     pModule->xClose(pCursor);
   101453     pCursor = 0;
   101454   }
   101455 
   101456   if( rc==SQLITE_DONE ){
   101457     int jj;
   101458     char *zNew = NULL;
   101459     int nNew = 0;
   101460     int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
   101461     nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(struct PhraseToken);
   101462     p = fts3ReallocOrFree(p, nByte + nTemp);
   101463     if( !p ){
   101464       goto no_mem;
   101465     }
   101466     if( zTemp ){
   101467       zNew = &(((char *)p)[nByte]);
   101468       memcpy(zNew, zTemp, nTemp);
   101469     }else{
   101470       memset(p, 0, nByte+nTemp);
   101471     }
   101472     p->pPhrase = (Fts3Phrase *)&p[1];
   101473     for(jj=0; jj<p->pPhrase->nToken; jj++){
   101474       p->pPhrase->aToken[jj].z = &zNew[nNew];
   101475       nNew += p->pPhrase->aToken[jj].n;
   101476     }
   101477     sqlite3_free(zTemp);
   101478     p->eType = FTSQUERY_PHRASE;
   101479     p->pPhrase->iColumn = pParse->iDefaultCol;
   101480     rc = SQLITE_OK;
   101481   }
   101482 
   101483   *ppExpr = p;
   101484   return rc;
   101485 no_mem:
   101486 
   101487   if( pCursor ){
   101488     pModule->xClose(pCursor);
   101489   }
   101490   sqlite3_free(zTemp);
   101491   sqlite3_free(p);
   101492   *ppExpr = 0;
   101493   return SQLITE_NOMEM;
   101494 }
   101495 
   101496 /*
   101497 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
   101498 ** call fts3ExprParse(). So this forward declaration is required.
   101499 */
   101500 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
   101501 
   101502 /*
   101503 ** The output variable *ppExpr is populated with an allocated Fts3Expr
   101504 ** structure, or set to 0 if the end of the input buffer is reached.
   101505 **
   101506 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
   101507 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
   101508 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
   101509 */
   101510 static int getNextNode(
   101511   ParseContext *pParse,                   /* fts3 query parse context */
   101512   const char *z, int n,                   /* Input string */
   101513   Fts3Expr **ppExpr,                      /* OUT: expression */
   101514   int *pnConsumed                         /* OUT: Number of bytes consumed */
   101515 ){
   101516   static const struct Fts3Keyword {
   101517     char *z;                              /* Keyword text */
   101518     unsigned char n;                      /* Length of the keyword */
   101519     unsigned char parenOnly;              /* Only valid in paren mode */
   101520     unsigned char eType;                  /* Keyword code */
   101521   } aKeyword[] = {
   101522     { "OR" ,  2, 0, FTSQUERY_OR   },
   101523     { "AND",  3, 1, FTSQUERY_AND  },
   101524     { "NOT",  3, 1, FTSQUERY_NOT  },
   101525     { "NEAR", 4, 0, FTSQUERY_NEAR }
   101526   };
   101527   int ii;
   101528   int iCol;
   101529   int iColLen;
   101530   int rc;
   101531   Fts3Expr *pRet = 0;
   101532 
   101533   const char *zInput = z;
   101534   int nInput = n;
   101535 
   101536   /* Skip over any whitespace before checking for a keyword, an open or
   101537   ** close bracket, or a quoted string.
   101538   */
   101539   while( nInput>0 && fts3isspace(*zInput) ){
   101540     nInput--;
   101541     zInput++;
   101542   }
   101543   if( nInput==0 ){
   101544     return SQLITE_DONE;
   101545   }
   101546 
   101547   /* See if we are dealing with a keyword. */
   101548   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
   101549     const struct Fts3Keyword *pKey = &aKeyword[ii];
   101550 
   101551     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
   101552       continue;
   101553     }
   101554 
   101555     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
   101556       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
   101557       int nKey = pKey->n;
   101558       char cNext;
   101559 
   101560       /* If this is a "NEAR" keyword, check for an explicit nearness. */
   101561       if( pKey->eType==FTSQUERY_NEAR ){
   101562         assert( nKey==4 );
   101563         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
   101564           nNear = 0;
   101565           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
   101566             nNear = nNear * 10 + (zInput[nKey] - '0');
   101567           }
   101568         }
   101569       }
   101570 
   101571       /* At this point this is probably a keyword. But for that to be true,
   101572       ** the next byte must contain either whitespace, an open or close
   101573       ** parenthesis, a quote character, or EOF.
   101574       */
   101575       cNext = zInput[nKey];
   101576       if( fts3isspace(cNext)
   101577        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
   101578       ){
   101579         pRet = (Fts3Expr *)sqlite3_malloc(sizeof(Fts3Expr));
   101580         if( !pRet ){
   101581           return SQLITE_NOMEM;
   101582         }
   101583         memset(pRet, 0, sizeof(Fts3Expr));
   101584         pRet->eType = pKey->eType;
   101585         pRet->nNear = nNear;
   101586         *ppExpr = pRet;
   101587         *pnConsumed = (int)((zInput - z) + nKey);
   101588         return SQLITE_OK;
   101589       }
   101590 
   101591       /* Turns out that wasn't a keyword after all. This happens if the
   101592       ** user has supplied a token such as "ORacle". Continue.
   101593       */
   101594     }
   101595   }
   101596 
   101597   /* Check for an open bracket. */
   101598   if( sqlite3_fts3_enable_parentheses ){
   101599     if( *zInput=='(' ){
   101600       int nConsumed;
   101601       int rc;
   101602       pParse->nNest++;
   101603       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
   101604       if( rc==SQLITE_OK && !*ppExpr ){
   101605         rc = SQLITE_DONE;
   101606       }
   101607       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
   101608       return rc;
   101609     }
   101610 
   101611     /* Check for a close bracket. */
   101612     if( *zInput==')' ){
   101613       pParse->nNest--;
   101614       *pnConsumed = (int)((zInput - z) + 1);
   101615       return SQLITE_DONE;
   101616     }
   101617   }
   101618 
   101619   /* See if we are dealing with a quoted phrase. If this is the case, then
   101620   ** search for the closing quote and pass the whole string to getNextString()
   101621   ** for processing. This is easy to do, as fts3 has no syntax for escaping
   101622   ** a quote character embedded in a string.
   101623   */
   101624   if( *zInput=='"' ){
   101625     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
   101626     *pnConsumed = (int)((zInput - z) + ii + 1);
   101627     if( ii==nInput ){
   101628       return SQLITE_ERROR;
   101629     }
   101630     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
   101631   }
   101632 
   101633 
   101634   /* If control flows to this point, this must be a regular token, or
   101635   ** the end of the input. Read a regular token using the sqlite3_tokenizer
   101636   ** interface. Before doing so, figure out if there is an explicit
   101637   ** column specifier for the token.
   101638   **
   101639   ** TODO: Strangely, it is not possible to associate a column specifier
   101640   ** with a quoted phrase, only with a single token. Not sure if this was
   101641   ** an implementation artifact or an intentional decision when fts3 was
   101642   ** first implemented. Whichever it was, this module duplicates the
   101643   ** limitation.
   101644   */
   101645   iCol = pParse->iDefaultCol;
   101646   iColLen = 0;
   101647   for(ii=0; ii<pParse->nCol; ii++){
   101648     const char *zStr = pParse->azCol[ii];
   101649     int nStr = (int)strlen(zStr);
   101650     if( nInput>nStr && zInput[nStr]==':'
   101651      && sqlite3_strnicmp(zStr, zInput, nStr)==0
   101652     ){
   101653       iCol = ii;
   101654       iColLen = (int)((zInput - z) + nStr + 1);
   101655       break;
   101656     }
   101657   }
   101658   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
   101659   *pnConsumed += iColLen;
   101660   return rc;
   101661 }
   101662 
   101663 /*
   101664 ** The argument is an Fts3Expr structure for a binary operator (any type
   101665 ** except an FTSQUERY_PHRASE). Return an integer value representing the
   101666 ** precedence of the operator. Lower values have a higher precedence (i.e.
   101667 ** group more tightly). For example, in the C language, the == operator
   101668 ** groups more tightly than ||, and would therefore have a higher precedence.
   101669 **
   101670 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
   101671 ** is defined), the order of the operators in precedence from highest to
   101672 ** lowest is:
   101673 **
   101674 **   NEAR
   101675 **   NOT
   101676 **   AND (including implicit ANDs)
   101677 **   OR
   101678 **
   101679 ** Note that when using the old query syntax, the OR operator has a higher
   101680 ** precedence than the AND operator.
   101681 */
   101682 static int opPrecedence(Fts3Expr *p){
   101683   assert( p->eType!=FTSQUERY_PHRASE );
   101684   if( sqlite3_fts3_enable_parentheses ){
   101685     return p->eType;
   101686   }else if( p->eType==FTSQUERY_NEAR ){
   101687     return 1;
   101688   }else if( p->eType==FTSQUERY_OR ){
   101689     return 2;
   101690   }
   101691   assert( p->eType==FTSQUERY_AND );
   101692   return 3;
   101693 }
   101694 
   101695 /*
   101696 ** Argument ppHead contains a pointer to the current head of a query
   101697 ** expression tree being parsed. pPrev is the expression node most recently
   101698 ** inserted into the tree. This function adds pNew, which is always a binary
   101699 ** operator node, into the expression tree based on the relative precedence
   101700 ** of pNew and the existing nodes of the tree. This may result in the head
   101701 ** of the tree changing, in which case *ppHead is set to the new root node.
   101702 */
   101703 static void insertBinaryOperator(
   101704   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
   101705   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
   101706   Fts3Expr *pNew           /* New binary node to insert into expression tree */
   101707 ){
   101708   Fts3Expr *pSplit = pPrev;
   101709   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
   101710     pSplit = pSplit->pParent;
   101711   }
   101712 
   101713   if( pSplit->pParent ){
   101714     assert( pSplit->pParent->pRight==pSplit );
   101715     pSplit->pParent->pRight = pNew;
   101716     pNew->pParent = pSplit->pParent;
   101717   }else{
   101718     *ppHead = pNew;
   101719   }
   101720   pNew->pLeft = pSplit;
   101721   pSplit->pParent = pNew;
   101722 }
   101723 
   101724 /*
   101725 ** Parse the fts3 query expression found in buffer z, length n. This function
   101726 ** returns either when the end of the buffer is reached or an unmatched
   101727 ** closing bracket - ')' - is encountered.
   101728 **
   101729 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
   101730 ** parsed form of the expression and *pnConsumed is set to the number of
   101731 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
   101732 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
   101733 */
   101734 static int fts3ExprParse(
   101735   ParseContext *pParse,                   /* fts3 query parse context */
   101736   const char *z, int n,                   /* Text of MATCH query */
   101737   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
   101738   int *pnConsumed                         /* OUT: Number of bytes consumed */
   101739 ){
   101740   Fts3Expr *pRet = 0;
   101741   Fts3Expr *pPrev = 0;
   101742   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
   101743   int nIn = n;
   101744   const char *zIn = z;
   101745   int rc = SQLITE_OK;
   101746   int isRequirePhrase = 1;
   101747 
   101748   while( rc==SQLITE_OK ){
   101749     Fts3Expr *p = 0;
   101750     int nByte = 0;
   101751     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
   101752     if( rc==SQLITE_OK ){
   101753       int isPhrase;
   101754 
   101755       if( !sqlite3_fts3_enable_parentheses
   101756        && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot
   101757       ){
   101758         /* Create an implicit NOT operator. */
   101759         Fts3Expr *pNot = sqlite3_malloc(sizeof(Fts3Expr));
   101760         if( !pNot ){
   101761           sqlite3Fts3ExprFree(p);
   101762           rc = SQLITE_NOMEM;
   101763           goto exprparse_out;
   101764         }
   101765         memset(pNot, 0, sizeof(Fts3Expr));
   101766         pNot->eType = FTSQUERY_NOT;
   101767         pNot->pRight = p;
   101768         if( pNotBranch ){
   101769           pNot->pLeft = pNotBranch;
   101770         }
   101771         pNotBranch = pNot;
   101772         p = pPrev;
   101773       }else{
   101774         int eType = p->eType;
   101775         assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
   101776         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
   101777 
   101778         /* The isRequirePhrase variable is set to true if a phrase or
   101779         ** an expression contained in parenthesis is required. If a
   101780         ** binary operator (AND, OR, NOT or NEAR) is encounted when
   101781         ** isRequirePhrase is set, this is a syntax error.
   101782         */
   101783         if( !isPhrase && isRequirePhrase ){
   101784           sqlite3Fts3ExprFree(p);
   101785           rc = SQLITE_ERROR;
   101786           goto exprparse_out;
   101787         }
   101788 
   101789         if( isPhrase && !isRequirePhrase ){
   101790           /* Insert an implicit AND operator. */
   101791           Fts3Expr *pAnd;
   101792           assert( pRet && pPrev );
   101793           pAnd = sqlite3_malloc(sizeof(Fts3Expr));
   101794           if( !pAnd ){
   101795             sqlite3Fts3ExprFree(p);
   101796             rc = SQLITE_NOMEM;
   101797             goto exprparse_out;
   101798           }
   101799           memset(pAnd, 0, sizeof(Fts3Expr));
   101800           pAnd->eType = FTSQUERY_AND;
   101801           insertBinaryOperator(&pRet, pPrev, pAnd);
   101802           pPrev = pAnd;
   101803         }
   101804 
   101805         /* This test catches attempts to make either operand of a NEAR
   101806         ** operator something other than a phrase. For example, either of
   101807         ** the following:
   101808         **
   101809         **    (bracketed expression) NEAR phrase
   101810         **    phrase NEAR (bracketed expression)
   101811         **
   101812         ** Return an error in either case.
   101813         */
   101814         if( pPrev && (
   101815             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
   101816          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
   101817         )){
   101818           sqlite3Fts3ExprFree(p);
   101819           rc = SQLITE_ERROR;
   101820           goto exprparse_out;
   101821         }
   101822 
   101823         if( isPhrase ){
   101824           if( pRet ){
   101825             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
   101826             pPrev->pRight = p;
   101827             p->pParent = pPrev;
   101828           }else{
   101829             pRet = p;
   101830           }
   101831         }else{
   101832           insertBinaryOperator(&pRet, pPrev, p);
   101833         }
   101834         isRequirePhrase = !isPhrase;
   101835       }
   101836       assert( nByte>0 );
   101837     }
   101838     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
   101839     nIn -= nByte;
   101840     zIn += nByte;
   101841     pPrev = p;
   101842   }
   101843 
   101844   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
   101845     rc = SQLITE_ERROR;
   101846   }
   101847 
   101848   if( rc==SQLITE_DONE ){
   101849     rc = SQLITE_OK;
   101850     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
   101851       if( !pRet ){
   101852         rc = SQLITE_ERROR;
   101853       }else{
   101854         Fts3Expr *pIter = pNotBranch;
   101855         while( pIter->pLeft ){
   101856           pIter = pIter->pLeft;
   101857         }
   101858         pIter->pLeft = pRet;
   101859         pRet = pNotBranch;
   101860       }
   101861     }
   101862   }
   101863   *pnConsumed = n - nIn;
   101864 
   101865 exprparse_out:
   101866   if( rc!=SQLITE_OK ){
   101867     sqlite3Fts3ExprFree(pRet);
   101868     sqlite3Fts3ExprFree(pNotBranch);
   101869     pRet = 0;
   101870   }
   101871   *ppExpr = pRet;
   101872   return rc;
   101873 }
   101874 
   101875 /*
   101876 ** Parameters z and n contain a pointer to and length of a buffer containing
   101877 ** an fts3 query expression, respectively. This function attempts to parse the
   101878 ** query expression and create a tree of Fts3Expr structures representing the
   101879 ** parsed expression. If successful, *ppExpr is set to point to the head
   101880 ** of the parsed expression tree and SQLITE_OK is returned. If an error
   101881 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
   101882 ** error) is returned and *ppExpr is set to 0.
   101883 **
   101884 ** If parameter n is a negative number, then z is assumed to point to a
   101885 ** nul-terminated string and the length is determined using strlen().
   101886 **
   101887 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
   101888 ** use to normalize query tokens while parsing the expression. The azCol[]
   101889 ** array, which is assumed to contain nCol entries, should contain the names
   101890 ** of each column in the target fts3 table, in order from left to right.
   101891 ** Column names must be nul-terminated strings.
   101892 **
   101893 ** The iDefaultCol parameter should be passed the index of the table column
   101894 ** that appears on the left-hand-side of the MATCH operator (the default
   101895 ** column to match against for tokens for which a column name is not explicitly
   101896 ** specified as part of the query string), or -1 if tokens may by default
   101897 ** match any table column.
   101898 */
   101899 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
   101900   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
   101901   char **azCol,                       /* Array of column names for fts3 table */
   101902   int nCol,                           /* Number of entries in azCol[] */
   101903   int iDefaultCol,                    /* Default column to query */
   101904   const char *z, int n,               /* Text of MATCH query */
   101905   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
   101906 ){
   101907   int nParsed;
   101908   int rc;
   101909   ParseContext sParse;
   101910   sParse.pTokenizer = pTokenizer;
   101911   sParse.azCol = (const char **)azCol;
   101912   sParse.nCol = nCol;
   101913   sParse.iDefaultCol = iDefaultCol;
   101914   sParse.nNest = 0;
   101915   if( z==0 ){
   101916     *ppExpr = 0;
   101917     return SQLITE_OK;
   101918   }
   101919   if( n<0 ){
   101920     n = (int)strlen(z);
   101921   }
   101922   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
   101923 
   101924   /* Check for mismatched parenthesis */
   101925   if( rc==SQLITE_OK && sParse.nNest ){
   101926     rc = SQLITE_ERROR;
   101927     sqlite3Fts3ExprFree(*ppExpr);
   101928     *ppExpr = 0;
   101929   }
   101930 
   101931   return rc;
   101932 }
   101933 
   101934 /*
   101935 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
   101936 */
   101937 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
   101938   if( p ){
   101939     sqlite3Fts3ExprFree(p->pLeft);
   101940     sqlite3Fts3ExprFree(p->pRight);
   101941     sqlite3_free(p->aDoclist);
   101942     sqlite3_free(p);
   101943   }
   101944 }
   101945 
   101946 /****************************************************************************
   101947 *****************************************************************************
   101948 ** Everything after this point is just test code.
   101949 */
   101950 
   101951 #ifdef SQLITE_TEST
   101952 
   101953 
   101954 /*
   101955 ** Function to query the hash-table of tokenizers (see README.tokenizers).
   101956 */
   101957 static int queryTestTokenizer(
   101958   sqlite3 *db,
   101959   const char *zName,
   101960   const sqlite3_tokenizer_module **pp
   101961 ){
   101962   int rc;
   101963   sqlite3_stmt *pStmt;
   101964   const char zSql[] = "SELECT fts3_tokenizer(?)";
   101965 
   101966   *pp = 0;
   101967   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   101968   if( rc!=SQLITE_OK ){
   101969     return rc;
   101970   }
   101971 
   101972   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   101973   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   101974     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
   101975       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
   101976     }
   101977   }
   101978 
   101979   return sqlite3_finalize(pStmt);
   101980 }
   101981 
   101982 /*
   101983 ** This function is part of the test interface for the query parser. It
   101984 ** writes a text representation of the query expression pExpr into the
   101985 ** buffer pointed to by argument zBuf. It is assumed that zBuf is large
   101986 ** enough to store the required text representation.
   101987 */
   101988 static void exprToString(Fts3Expr *pExpr, char *zBuf){
   101989   switch( pExpr->eType ){
   101990     case FTSQUERY_PHRASE: {
   101991       Fts3Phrase *pPhrase = pExpr->pPhrase;
   101992       int i;
   101993       zBuf += sprintf(zBuf, "PHRASE %d %d", pPhrase->iColumn, pPhrase->isNot);
   101994       for(i=0; i<pPhrase->nToken; i++){
   101995         zBuf += sprintf(zBuf," %.*s",pPhrase->aToken[i].n,pPhrase->aToken[i].z);
   101996         zBuf += sprintf(zBuf,"%s", (pPhrase->aToken[i].isPrefix?"+":""));
   101997       }
   101998       return;
   101999     }
   102000 
   102001     case FTSQUERY_NEAR:
   102002       zBuf += sprintf(zBuf, "NEAR/%d ", pExpr->nNear);
   102003       break;
   102004     case FTSQUERY_NOT:
   102005       zBuf += sprintf(zBuf, "NOT ");
   102006       break;
   102007     case FTSQUERY_AND:
   102008       zBuf += sprintf(zBuf, "AND ");
   102009       break;
   102010     case FTSQUERY_OR:
   102011       zBuf += sprintf(zBuf, "OR ");
   102012       break;
   102013   }
   102014 
   102015   zBuf += sprintf(zBuf, "{");
   102016   exprToString(pExpr->pLeft, zBuf);
   102017   zBuf += strlen(zBuf);
   102018   zBuf += sprintf(zBuf, "} ");
   102019 
   102020   zBuf += sprintf(zBuf, "{");
   102021   exprToString(pExpr->pRight, zBuf);
   102022   zBuf += strlen(zBuf);
   102023   zBuf += sprintf(zBuf, "}");
   102024 }
   102025 
   102026 /*
   102027 ** This is the implementation of a scalar SQL function used to test the
   102028 ** expression parser. It should be called as follows:
   102029 **
   102030 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
   102031 **
   102032 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
   102033 ** to parse the query expression (see README.tokenizers). The second argument
   102034 ** is the query expression to parse. Each subsequent argument is the name
   102035 ** of a column of the fts3 table that the query expression may refer to.
   102036 ** For example:
   102037 **
   102038 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
   102039 */
   102040 static void fts3ExprTest(
   102041   sqlite3_context *context,
   102042   int argc,
   102043   sqlite3_value **argv
   102044 ){
   102045   sqlite3_tokenizer_module const *pModule = 0;
   102046   sqlite3_tokenizer *pTokenizer = 0;
   102047   int rc;
   102048   char **azCol = 0;
   102049   const char *zExpr;
   102050   int nExpr;
   102051   int nCol;
   102052   int ii;
   102053   Fts3Expr *pExpr;
   102054   sqlite3 *db = sqlite3_context_db_handle(context);
   102055 
   102056   if( argc<3 ){
   102057     sqlite3_result_error(context,
   102058         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
   102059     );
   102060     return;
   102061   }
   102062 
   102063   rc = queryTestTokenizer(db,
   102064                           (const char *)sqlite3_value_text(argv[0]), &pModule);
   102065   if( rc==SQLITE_NOMEM ){
   102066     sqlite3_result_error_nomem(context);
   102067     goto exprtest_out;
   102068   }else if( !pModule ){
   102069     sqlite3_result_error(context, "No such tokenizer module", -1);
   102070     goto exprtest_out;
   102071   }
   102072 
   102073   rc = pModule->xCreate(0, 0, &pTokenizer);
   102074   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
   102075   if( rc==SQLITE_NOMEM ){
   102076     sqlite3_result_error_nomem(context);
   102077     goto exprtest_out;
   102078   }
   102079   pTokenizer->pModule = pModule;
   102080 
   102081   zExpr = (const char *)sqlite3_value_text(argv[1]);
   102082   nExpr = sqlite3_value_bytes(argv[1]);
   102083   nCol = argc-2;
   102084   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
   102085   if( !azCol ){
   102086     sqlite3_result_error_nomem(context);
   102087     goto exprtest_out;
   102088   }
   102089   for(ii=0; ii<nCol; ii++){
   102090     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
   102091   }
   102092 
   102093   rc = sqlite3Fts3ExprParse(
   102094       pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
   102095   );
   102096   if( rc==SQLITE_NOMEM ){
   102097     sqlite3_result_error_nomem(context);
   102098     goto exprtest_out;
   102099   }else if( rc==SQLITE_OK ){
   102100     char zBuf[4096];
   102101     exprToString(pExpr, zBuf);
   102102     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   102103     sqlite3Fts3ExprFree(pExpr);
   102104   }else{
   102105     sqlite3_result_error(context, "Error parsing expression", -1);
   102106   }
   102107 
   102108 exprtest_out:
   102109   if( pModule && pTokenizer ){
   102110     rc = pModule->xDestroy(pTokenizer);
   102111   }
   102112   sqlite3_free(azCol);
   102113 }
   102114 
   102115 /*
   102116 ** Register the query expression parser test function fts3_exprtest()
   102117 ** with database connection db.
   102118 */
   102119 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
   102120   return sqlite3_create_function(
   102121       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
   102122   );
   102123 }
   102124 
   102125 #endif
   102126 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   102127 
   102128 /************** End of fts3_expr.c *******************************************/
   102129 /************** Begin file fts3_hash.c ***************************************/
   102130 /*
   102131 ** 2001 September 22
   102132 **
   102133 ** The author disclaims copyright to this source code.  In place of
   102134 ** a legal notice, here is a blessing:
   102135 **
   102136 **    May you do good and not evil.
   102137 **    May you find forgiveness for yourself and forgive others.
   102138 **    May you share freely, never taking more than you give.
   102139 **
   102140 *************************************************************************
   102141 ** This is the implementation of generic hash-tables used in SQLite.
   102142 ** We've modified it slightly to serve as a standalone hash table
   102143 ** implementation for the full-text indexing module.
   102144 */
   102145 
   102146 /*
   102147 ** The code in this file is only compiled if:
   102148 **
   102149 **     * The FTS3 module is being built as an extension
   102150 **       (in which case SQLITE_CORE is not defined), or
   102151 **
   102152 **     * The FTS3 module is being built into the core of
   102153 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   102154 */
   102155 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   102156 
   102157 
   102158 
   102159 /*
   102160 ** Malloc and Free functions
   102161 */
   102162 static void *fts3HashMalloc(int n){
   102163   void *p = sqlite3_malloc(n);
   102164   if( p ){
   102165     memset(p, 0, n);
   102166   }
   102167   return p;
   102168 }
   102169 static void fts3HashFree(void *p){
   102170   sqlite3_free(p);
   102171 }
   102172 
   102173 /* Turn bulk memory into a hash table object by initializing the
   102174 ** fields of the Hash structure.
   102175 **
   102176 ** "pNew" is a pointer to the hash table that is to be initialized.
   102177 ** keyClass is one of the constants
   102178 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
   102179 ** determines what kind of key the hash table will use.  "copyKey" is
   102180 ** true if the hash table should make its own private copy of keys and
   102181 ** false if it should just use the supplied pointer.
   102182 */
   102183 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
   102184   assert( pNew!=0 );
   102185   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
   102186   pNew->keyClass = keyClass;
   102187   pNew->copyKey = copyKey;
   102188   pNew->first = 0;
   102189   pNew->count = 0;
   102190   pNew->htsize = 0;
   102191   pNew->ht = 0;
   102192 }
   102193 
   102194 /* Remove all entries from a hash table.  Reclaim all memory.
   102195 ** Call this routine to delete a hash table or to reset a hash table
   102196 ** to the empty state.
   102197 */
   102198 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
   102199   Fts3HashElem *elem;         /* For looping over all elements of the table */
   102200 
   102201   assert( pH!=0 );
   102202   elem = pH->first;
   102203   pH->first = 0;
   102204   fts3HashFree(pH->ht);
   102205   pH->ht = 0;
   102206   pH->htsize = 0;
   102207   while( elem ){
   102208     Fts3HashElem *next_elem = elem->next;
   102209     if( pH->copyKey && elem->pKey ){
   102210       fts3HashFree(elem->pKey);
   102211     }
   102212     fts3HashFree(elem);
   102213     elem = next_elem;
   102214   }
   102215   pH->count = 0;
   102216 }
   102217 
   102218 /*
   102219 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
   102220 */
   102221 static int fts3StrHash(const void *pKey, int nKey){
   102222   const char *z = (const char *)pKey;
   102223   int h = 0;
   102224   if( nKey<=0 ) nKey = (int) strlen(z);
   102225   while( nKey > 0  ){
   102226     h = (h<<3) ^ h ^ *z++;
   102227     nKey--;
   102228   }
   102229   return h & 0x7fffffff;
   102230 }
   102231 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
   102232   if( n1!=n2 ) return 1;
   102233   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
   102234 }
   102235 
   102236 /*
   102237 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
   102238 */
   102239 static int fts3BinHash(const void *pKey, int nKey){
   102240   int h = 0;
   102241   const char *z = (const char *)pKey;
   102242   while( nKey-- > 0 ){
   102243     h = (h<<3) ^ h ^ *(z++);
   102244   }
   102245   return h & 0x7fffffff;
   102246 }
   102247 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
   102248   if( n1!=n2 ) return 1;
   102249   return memcmp(pKey1,pKey2,n1);
   102250 }
   102251 
   102252 /*
   102253 ** Return a pointer to the appropriate hash function given the key class.
   102254 **
   102255 ** The C syntax in this function definition may be unfamilar to some
   102256 ** programmers, so we provide the following additional explanation:
   102257 **
   102258 ** The name of the function is "ftsHashFunction".  The function takes a
   102259 ** single parameter "keyClass".  The return value of ftsHashFunction()
   102260 ** is a pointer to another function.  Specifically, the return value
   102261 ** of ftsHashFunction() is a pointer to a function that takes two parameters
   102262 ** with types "const void*" and "int" and returns an "int".
   102263 */
   102264 static int (*ftsHashFunction(int keyClass))(const void*,int){
   102265   if( keyClass==FTS3_HASH_STRING ){
   102266     return &fts3StrHash;
   102267   }else{
   102268     assert( keyClass==FTS3_HASH_BINARY );
   102269     return &fts3BinHash;
   102270   }
   102271 }
   102272 
   102273 /*
   102274 ** Return a pointer to the appropriate hash function given the key class.
   102275 **
   102276 ** For help in interpreted the obscure C code in the function definition,
   102277 ** see the header comment on the previous function.
   102278 */
   102279 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
   102280   if( keyClass==FTS3_HASH_STRING ){
   102281     return &fts3StrCompare;
   102282   }else{
   102283     assert( keyClass==FTS3_HASH_BINARY );
   102284     return &fts3BinCompare;
   102285   }
   102286 }
   102287 
   102288 /* Link an element into the hash table
   102289 */
   102290 static void fts3HashInsertElement(
   102291   Fts3Hash *pH,            /* The complete hash table */
   102292   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
   102293   Fts3HashElem *pNew       /* The element to be inserted */
   102294 ){
   102295   Fts3HashElem *pHead;     /* First element already in pEntry */
   102296   pHead = pEntry->chain;
   102297   if( pHead ){
   102298     pNew->next = pHead;
   102299     pNew->prev = pHead->prev;
   102300     if( pHead->prev ){ pHead->prev->next = pNew; }
   102301     else             { pH->first = pNew; }
   102302     pHead->prev = pNew;
   102303   }else{
   102304     pNew->next = pH->first;
   102305     if( pH->first ){ pH->first->prev = pNew; }
   102306     pNew->prev = 0;
   102307     pH->first = pNew;
   102308   }
   102309   pEntry->count++;
   102310   pEntry->chain = pNew;
   102311 }
   102312 
   102313 
   102314 /* Resize the hash table so that it cantains "new_size" buckets.
   102315 ** "new_size" must be a power of 2.  The hash table might fail
   102316 ** to resize if sqliteMalloc() fails.
   102317 **
   102318 ** Return non-zero if a memory allocation error occurs.
   102319 */
   102320 static int fts3Rehash(Fts3Hash *pH, int new_size){
   102321   struct _fts3ht *new_ht;          /* The new hash table */
   102322   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
   102323   int (*xHash)(const void*,int);   /* The hash function */
   102324 
   102325   assert( (new_size & (new_size-1))==0 );
   102326   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
   102327   if( new_ht==0 ) return 1;
   102328   fts3HashFree(pH->ht);
   102329   pH->ht = new_ht;
   102330   pH->htsize = new_size;
   102331   xHash = ftsHashFunction(pH->keyClass);
   102332   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
   102333     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
   102334     next_elem = elem->next;
   102335     fts3HashInsertElement(pH, &new_ht[h], elem);
   102336   }
   102337   return 0;
   102338 }
   102339 
   102340 /* This function (for internal use only) locates an element in an
   102341 ** hash table that matches the given key.  The hash for this key has
   102342 ** already been computed and is passed as the 4th parameter.
   102343 */
   102344 static Fts3HashElem *fts3FindElementByHash(
   102345   const Fts3Hash *pH, /* The pH to be searched */
   102346   const void *pKey,   /* The key we are searching for */
   102347   int nKey,
   102348   int h               /* The hash for this key. */
   102349 ){
   102350   Fts3HashElem *elem;            /* Used to loop thru the element list */
   102351   int count;                     /* Number of elements left to test */
   102352   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
   102353 
   102354   if( pH->ht ){
   102355     struct _fts3ht *pEntry = &pH->ht[h];
   102356     elem = pEntry->chain;
   102357     count = pEntry->count;
   102358     xCompare = ftsCompareFunction(pH->keyClass);
   102359     while( count-- && elem ){
   102360       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
   102361         return elem;
   102362       }
   102363       elem = elem->next;
   102364     }
   102365   }
   102366   return 0;
   102367 }
   102368 
   102369 /* Remove a single entry from the hash table given a pointer to that
   102370 ** element and a hash on the element's key.
   102371 */
   102372 static void fts3RemoveElementByHash(
   102373   Fts3Hash *pH,         /* The pH containing "elem" */
   102374   Fts3HashElem* elem,   /* The element to be removed from the pH */
   102375   int h                 /* Hash value for the element */
   102376 ){
   102377   struct _fts3ht *pEntry;
   102378   if( elem->prev ){
   102379     elem->prev->next = elem->next;
   102380   }else{
   102381     pH->first = elem->next;
   102382   }
   102383   if( elem->next ){
   102384     elem->next->prev = elem->prev;
   102385   }
   102386   pEntry = &pH->ht[h];
   102387   if( pEntry->chain==elem ){
   102388     pEntry->chain = elem->next;
   102389   }
   102390   pEntry->count--;
   102391   if( pEntry->count<=0 ){
   102392     pEntry->chain = 0;
   102393   }
   102394   if( pH->copyKey && elem->pKey ){
   102395     fts3HashFree(elem->pKey);
   102396   }
   102397   fts3HashFree( elem );
   102398   pH->count--;
   102399   if( pH->count<=0 ){
   102400     assert( pH->first==0 );
   102401     assert( pH->count==0 );
   102402     fts3HashClear(pH);
   102403   }
   102404 }
   102405 
   102406 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
   102407   const Fts3Hash *pH,
   102408   const void *pKey,
   102409   int nKey
   102410 ){
   102411   int h;                          /* A hash on key */
   102412   int (*xHash)(const void*,int);  /* The hash function */
   102413 
   102414   if( pH==0 || pH->ht==0 ) return 0;
   102415   xHash = ftsHashFunction(pH->keyClass);
   102416   assert( xHash!=0 );
   102417   h = (*xHash)(pKey,nKey);
   102418   assert( (pH->htsize & (pH->htsize-1))==0 );
   102419   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
   102420 }
   102421 
   102422 /*
   102423 ** Attempt to locate an element of the hash table pH with a key
   102424 ** that matches pKey,nKey.  Return the data for this element if it is
   102425 ** found, or NULL if there is no match.
   102426 */
   102427 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
   102428   Fts3HashElem *pElem;            /* The element that matches key (if any) */
   102429 
   102430   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
   102431   return pElem ? pElem->data : 0;
   102432 }
   102433 
   102434 /* Insert an element into the hash table pH.  The key is pKey,nKey
   102435 ** and the data is "data".
   102436 **
   102437 ** If no element exists with a matching key, then a new
   102438 ** element is created.  A copy of the key is made if the copyKey
   102439 ** flag is set.  NULL is returned.
   102440 **
   102441 ** If another element already exists with the same key, then the
   102442 ** new data replaces the old data and the old data is returned.
   102443 ** The key is not copied in this instance.  If a malloc fails, then
   102444 ** the new data is returned and the hash table is unchanged.
   102445 **
   102446 ** If the "data" parameter to this function is NULL, then the
   102447 ** element corresponding to "key" is removed from the hash table.
   102448 */
   102449 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
   102450   Fts3Hash *pH,        /* The hash table to insert into */
   102451   const void *pKey,    /* The key */
   102452   int nKey,            /* Number of bytes in the key */
   102453   void *data           /* The data */
   102454 ){
   102455   int hraw;                 /* Raw hash value of the key */
   102456   int h;                    /* the hash of the key modulo hash table size */
   102457   Fts3HashElem *elem;       /* Used to loop thru the element list */
   102458   Fts3HashElem *new_elem;   /* New element added to the pH */
   102459   int (*xHash)(const void*,int);  /* The hash function */
   102460 
   102461   assert( pH!=0 );
   102462   xHash = ftsHashFunction(pH->keyClass);
   102463   assert( xHash!=0 );
   102464   hraw = (*xHash)(pKey, nKey);
   102465   assert( (pH->htsize & (pH->htsize-1))==0 );
   102466   h = hraw & (pH->htsize-1);
   102467   elem = fts3FindElementByHash(pH,pKey,nKey,h);
   102468   if( elem ){
   102469     void *old_data = elem->data;
   102470     if( data==0 ){
   102471       fts3RemoveElementByHash(pH,elem,h);
   102472     }else{
   102473       elem->data = data;
   102474     }
   102475     return old_data;
   102476   }
   102477   if( data==0 ) return 0;
   102478   if( (pH->htsize==0 && fts3Rehash(pH,8))
   102479    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
   102480   ){
   102481     pH->count = 0;
   102482     return data;
   102483   }
   102484   assert( pH->htsize>0 );
   102485   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
   102486   if( new_elem==0 ) return data;
   102487   if( pH->copyKey && pKey!=0 ){
   102488     new_elem->pKey = fts3HashMalloc( nKey );
   102489     if( new_elem->pKey==0 ){
   102490       fts3HashFree(new_elem);
   102491       return data;
   102492     }
   102493     memcpy((void*)new_elem->pKey, pKey, nKey);
   102494   }else{
   102495     new_elem->pKey = (void*)pKey;
   102496   }
   102497   new_elem->nKey = nKey;
   102498   pH->count++;
   102499   assert( pH->htsize>0 );
   102500   assert( (pH->htsize & (pH->htsize-1))==0 );
   102501   h = hraw & (pH->htsize-1);
   102502   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
   102503   new_elem->data = data;
   102504   return 0;
   102505 }
   102506 
   102507 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   102508 
   102509 /************** End of fts3_hash.c *******************************************/
   102510 /************** Begin file fts3_porter.c *************************************/
   102511 /*
   102512 ** 2006 September 30
   102513 **
   102514 ** The author disclaims copyright to this source code.  In place of
   102515 ** a legal notice, here is a blessing:
   102516 **
   102517 **    May you do good and not evil.
   102518 **    May you find forgiveness for yourself and forgive others.
   102519 **    May you share freely, never taking more than you give.
   102520 **
   102521 *************************************************************************
   102522 ** Implementation of the full-text-search tokenizer that implements
   102523 ** a Porter stemmer.
   102524 */
   102525 
   102526 /*
   102527 ** The code in this file is only compiled if:
   102528 **
   102529 **     * The FTS3 module is being built as an extension
   102530 **       (in which case SQLITE_CORE is not defined), or
   102531 **
   102532 **     * The FTS3 module is being built into the core of
   102533 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   102534 */
   102535 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   102536 
   102537 
   102538 
   102539 
   102540 /*
   102541 ** Class derived from sqlite3_tokenizer
   102542 */
   102543 typedef struct porter_tokenizer {
   102544   sqlite3_tokenizer base;      /* Base class */
   102545 } porter_tokenizer;
   102546 
   102547 /*
   102548 ** Class derived from sqlit3_tokenizer_cursor
   102549 */
   102550 typedef struct porter_tokenizer_cursor {
   102551   sqlite3_tokenizer_cursor base;
   102552   const char *zInput;          /* input we are tokenizing */
   102553   int nInput;                  /* size of the input */
   102554   int iOffset;                 /* current position in zInput */
   102555   int iToken;                  /* index of next token to be returned */
   102556   char *zToken;                /* storage for current token */
   102557   int nAllocated;              /* space allocated to zToken buffer */
   102558 } porter_tokenizer_cursor;
   102559 
   102560 
   102561 /*
   102562 ** Create a new tokenizer instance.
   102563 */
   102564 static int porterCreate(
   102565   int argc, const char * const *argv,
   102566   sqlite3_tokenizer **ppTokenizer
   102567 ){
   102568   porter_tokenizer *t;
   102569 
   102570   UNUSED_PARAMETER(argc);
   102571   UNUSED_PARAMETER(argv);
   102572 
   102573   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
   102574   if( t==NULL ) return SQLITE_NOMEM;
   102575   memset(t, 0, sizeof(*t));
   102576   *ppTokenizer = &t->base;
   102577   return SQLITE_OK;
   102578 }
   102579 
   102580 /*
   102581 ** Destroy a tokenizer
   102582 */
   102583 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
   102584   sqlite3_free(pTokenizer);
   102585   return SQLITE_OK;
   102586 }
   102587 
   102588 /*
   102589 ** Prepare to begin tokenizing a particular string.  The input
   102590 ** string to be tokenized is zInput[0..nInput-1].  A cursor
   102591 ** used to incrementally tokenize this string is returned in
   102592 ** *ppCursor.
   102593 */
   102594 static int porterOpen(
   102595   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   102596   const char *zInput, int nInput,        /* String to be tokenized */
   102597   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   102598 ){
   102599   porter_tokenizer_cursor *c;
   102600 
   102601   UNUSED_PARAMETER(pTokenizer);
   102602 
   102603   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
   102604   if( c==NULL ) return SQLITE_NOMEM;
   102605 
   102606   c->zInput = zInput;
   102607   if( zInput==0 ){
   102608     c->nInput = 0;
   102609   }else if( nInput<0 ){
   102610     c->nInput = (int)strlen(zInput);
   102611   }else{
   102612     c->nInput = nInput;
   102613   }
   102614   c->iOffset = 0;                 /* start tokenizing at the beginning */
   102615   c->iToken = 0;
   102616   c->zToken = NULL;               /* no space allocated, yet. */
   102617   c->nAllocated = 0;
   102618 
   102619   *ppCursor = &c->base;
   102620   return SQLITE_OK;
   102621 }
   102622 
   102623 /*
   102624 ** Close a tokenization cursor previously opened by a call to
   102625 ** porterOpen() above.
   102626 */
   102627 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
   102628   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
   102629   sqlite3_free(c->zToken);
   102630   sqlite3_free(c);
   102631   return SQLITE_OK;
   102632 }
   102633 /*
   102634 ** Vowel or consonant
   102635 */
   102636 static const char cType[] = {
   102637    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
   102638    1, 1, 1, 2, 1
   102639 };
   102640 
   102641 /*
   102642 ** isConsonant() and isVowel() determine if their first character in
   102643 ** the string they point to is a consonant or a vowel, according
   102644 ** to Porter ruls.
   102645 **
   102646 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
   102647 ** 'Y' is a consonant unless it follows another consonant,
   102648 ** in which case it is a vowel.
   102649 **
   102650 ** In these routine, the letters are in reverse order.  So the 'y' rule
   102651 ** is that 'y' is a consonant unless it is followed by another
   102652 ** consonent.
   102653 */
   102654 static int isVowel(const char*);
   102655 static int isConsonant(const char *z){
   102656   int j;
   102657   char x = *z;
   102658   if( x==0 ) return 0;
   102659   assert( x>='a' && x<='z' );
   102660   j = cType[x-'a'];
   102661   if( j<2 ) return j;
   102662   return z[1]==0 || isVowel(z + 1);
   102663 }
   102664 static int isVowel(const char *z){
   102665   int j;
   102666   char x = *z;
   102667   if( x==0 ) return 0;
   102668   assert( x>='a' && x<='z' );
   102669   j = cType[x-'a'];
   102670   if( j<2 ) return 1-j;
   102671   return isConsonant(z + 1);
   102672 }
   102673 
   102674 /*
   102675 ** Let any sequence of one or more vowels be represented by V and let
   102676 ** C be sequence of one or more consonants.  Then every word can be
   102677 ** represented as:
   102678 **
   102679 **           [C] (VC){m} [V]
   102680 **
   102681 ** In prose:  A word is an optional consonant followed by zero or
   102682 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
   102683 ** number of vowel consonant pairs.  This routine computes the value
   102684 ** of m for the first i bytes of a word.
   102685 **
   102686 ** Return true if the m-value for z is 1 or more.  In other words,
   102687 ** return true if z contains at least one vowel that is followed
   102688 ** by a consonant.
   102689 **
   102690 ** In this routine z[] is in reverse order.  So we are really looking
   102691 ** for an instance of of a consonant followed by a vowel.
   102692 */
   102693 static int m_gt_0(const char *z){
   102694   while( isVowel(z) ){ z++; }
   102695   if( *z==0 ) return 0;
   102696   while( isConsonant(z) ){ z++; }
   102697   return *z!=0;
   102698 }
   102699 
   102700 /* Like mgt0 above except we are looking for a value of m which is
   102701 ** exactly 1
   102702 */
   102703 static int m_eq_1(const char *z){
   102704   while( isVowel(z) ){ z++; }
   102705   if( *z==0 ) return 0;
   102706   while( isConsonant(z) ){ z++; }
   102707   if( *z==0 ) return 0;
   102708   while( isVowel(z) ){ z++; }
   102709   if( *z==0 ) return 1;
   102710   while( isConsonant(z) ){ z++; }
   102711   return *z==0;
   102712 }
   102713 
   102714 /* Like mgt0 above except we are looking for a value of m>1 instead
   102715 ** or m>0
   102716 */
   102717 static int m_gt_1(const char *z){
   102718   while( isVowel(z) ){ z++; }
   102719   if( *z==0 ) return 0;
   102720   while( isConsonant(z) ){ z++; }
   102721   if( *z==0 ) return 0;
   102722   while( isVowel(z) ){ z++; }
   102723   if( *z==0 ) return 0;
   102724   while( isConsonant(z) ){ z++; }
   102725   return *z!=0;
   102726 }
   102727 
   102728 /*
   102729 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
   102730 */
   102731 static int hasVowel(const char *z){
   102732   while( isConsonant(z) ){ z++; }
   102733   return *z!=0;
   102734 }
   102735 
   102736 /*
   102737 ** Return TRUE if the word ends in a double consonant.
   102738 **
   102739 ** The text is reversed here. So we are really looking at
   102740 ** the first two characters of z[].
   102741 */
   102742 static int doubleConsonant(const char *z){
   102743   return isConsonant(z) && z[0]==z[1];
   102744 }
   102745 
   102746 /*
   102747 ** Return TRUE if the word ends with three letters which
   102748 ** are consonant-vowel-consonent and where the final consonant
   102749 ** is not 'w', 'x', or 'y'.
   102750 **
   102751 ** The word is reversed here.  So we are really checking the
   102752 ** first three letters and the first one cannot be in [wxy].
   102753 */
   102754 static int star_oh(const char *z){
   102755   return
   102756     isConsonant(z) &&
   102757     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
   102758     isVowel(z+1) &&
   102759     isConsonant(z+2);
   102760 }
   102761 
   102762 /*
   102763 ** If the word ends with zFrom and xCond() is true for the stem
   102764 ** of the word that preceeds the zFrom ending, then change the
   102765 ** ending to zTo.
   102766 **
   102767 ** The input word *pz and zFrom are both in reverse order.  zTo
   102768 ** is in normal order.
   102769 **
   102770 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
   102771 ** match.  Not that TRUE is returned even if xCond() fails and
   102772 ** no substitution occurs.
   102773 */
   102774 static int stem(
   102775   char **pz,             /* The word being stemmed (Reversed) */
   102776   const char *zFrom,     /* If the ending matches this... (Reversed) */
   102777   const char *zTo,       /* ... change the ending to this (not reversed) */
   102778   int (*xCond)(const char*)   /* Condition that must be true */
   102779 ){
   102780   char *z = *pz;
   102781   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
   102782   if( *zFrom!=0 ) return 0;
   102783   if( xCond && !xCond(z) ) return 1;
   102784   while( *zTo ){
   102785     *(--z) = *(zTo++);
   102786   }
   102787   *pz = z;
   102788   return 1;
   102789 }
   102790 
   102791 /*
   102792 ** This is the fallback stemmer used when the porter stemmer is
   102793 ** inappropriate.  The input word is copied into the output with
   102794 ** US-ASCII case folding.  If the input word is too long (more
   102795 ** than 20 bytes if it contains no digits or more than 6 bytes if
   102796 ** it contains digits) then word is truncated to 20 or 6 bytes
   102797 ** by taking 10 or 3 bytes from the beginning and end.
   102798 */
   102799 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
   102800   int i, mx, j;
   102801   int hasDigit = 0;
   102802   for(i=0; i<nIn; i++){
   102803     char c = zIn[i];
   102804     if( c>='A' && c<='Z' ){
   102805       zOut[i] = c - 'A' + 'a';
   102806     }else{
   102807       if( c>='0' && c<='9' ) hasDigit = 1;
   102808       zOut[i] = c;
   102809     }
   102810   }
   102811   mx = hasDigit ? 3 : 10;
   102812   if( nIn>mx*2 ){
   102813     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
   102814       zOut[j] = zOut[i];
   102815     }
   102816     i = j;
   102817   }
   102818   zOut[i] = 0;
   102819   *pnOut = i;
   102820 }
   102821 
   102822 
   102823 /*
   102824 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
   102825 ** zOut is at least big enough to hold nIn bytes.  Write the actual
   102826 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
   102827 **
   102828 ** Any upper-case characters in the US-ASCII character set ([A-Z])
   102829 ** are converted to lower case.  Upper-case UTF characters are
   102830 ** unchanged.
   102831 **
   102832 ** Words that are longer than about 20 bytes are stemmed by retaining
   102833 ** a few bytes from the beginning and the end of the word.  If the
   102834 ** word contains digits, 3 bytes are taken from the beginning and
   102835 ** 3 bytes from the end.  For long words without digits, 10 bytes
   102836 ** are taken from each end.  US-ASCII case folding still applies.
   102837 **
   102838 ** If the input word contains not digits but does characters not
   102839 ** in [a-zA-Z] then no stemming is attempted and this routine just
   102840 ** copies the input into the input into the output with US-ASCII
   102841 ** case folding.
   102842 **
   102843 ** Stemming never increases the length of the word.  So there is
   102844 ** no chance of overflowing the zOut buffer.
   102845 */
   102846 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
   102847   int i, j;
   102848   char zReverse[28];
   102849   char *z, *z2;
   102850   if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
   102851     /* The word is too big or too small for the porter stemmer.
   102852     ** Fallback to the copy stemmer */
   102853     copy_stemmer(zIn, nIn, zOut, pnOut);
   102854     return;
   102855   }
   102856   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
   102857     char c = zIn[i];
   102858     if( c>='A' && c<='Z' ){
   102859       zReverse[j] = c + 'a' - 'A';
   102860     }else if( c>='a' && c<='z' ){
   102861       zReverse[j] = c;
   102862     }else{
   102863       /* The use of a character not in [a-zA-Z] means that we fallback
   102864       ** to the copy stemmer */
   102865       copy_stemmer(zIn, nIn, zOut, pnOut);
   102866       return;
   102867     }
   102868   }
   102869   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
   102870   z = &zReverse[j+1];
   102871 
   102872 
   102873   /* Step 1a */
   102874   if( z[0]=='s' ){
   102875     if(
   102876      !stem(&z, "sess", "ss", 0) &&
   102877      !stem(&z, "sei", "i", 0)  &&
   102878      !stem(&z, "ss", "ss", 0)
   102879     ){
   102880       z++;
   102881     }
   102882   }
   102883 
   102884   /* Step 1b */
   102885   z2 = z;
   102886   if( stem(&z, "dee", "ee", m_gt_0) ){
   102887     /* Do nothing.  The work was all in the test */
   102888   }else if(
   102889      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
   102890       && z!=z2
   102891   ){
   102892      if( stem(&z, "ta", "ate", 0) ||
   102893          stem(&z, "lb", "ble", 0) ||
   102894          stem(&z, "zi", "ize", 0) ){
   102895        /* Do nothing.  The work was all in the test */
   102896      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
   102897        z++;
   102898      }else if( m_eq_1(z) && star_oh(z) ){
   102899        *(--z) = 'e';
   102900      }
   102901   }
   102902 
   102903   /* Step 1c */
   102904   if( z[0]=='y' && hasVowel(z+1) ){
   102905     z[0] = 'i';
   102906   }
   102907 
   102908   /* Step 2 */
   102909   switch( z[1] ){
   102910    case 'a':
   102911      stem(&z, "lanoita", "ate", m_gt_0) ||
   102912      stem(&z, "lanoit", "tion", m_gt_0);
   102913      break;
   102914    case 'c':
   102915      stem(&z, "icne", "ence", m_gt_0) ||
   102916      stem(&z, "icna", "ance", m_gt_0);
   102917      break;
   102918    case 'e':
   102919      stem(&z, "rezi", "ize", m_gt_0);
   102920      break;
   102921    case 'g':
   102922      stem(&z, "igol", "log", m_gt_0);
   102923      break;
   102924    case 'l':
   102925      stem(&z, "ilb", "ble", m_gt_0) ||
   102926      stem(&z, "illa", "al", m_gt_0) ||
   102927      stem(&z, "iltne", "ent", m_gt_0) ||
   102928      stem(&z, "ile", "e", m_gt_0) ||
   102929      stem(&z, "ilsuo", "ous", m_gt_0);
   102930      break;
   102931    case 'o':
   102932      stem(&z, "noitazi", "ize", m_gt_0) ||
   102933      stem(&z, "noita", "ate", m_gt_0) ||
   102934      stem(&z, "rota", "ate", m_gt_0);
   102935      break;
   102936    case 's':
   102937      stem(&z, "msila", "al", m_gt_0) ||
   102938      stem(&z, "ssenevi", "ive", m_gt_0) ||
   102939      stem(&z, "ssenluf", "ful", m_gt_0) ||
   102940      stem(&z, "ssensuo", "ous", m_gt_0);
   102941      break;
   102942    case 't':
   102943      stem(&z, "itila", "al", m_gt_0) ||
   102944      stem(&z, "itivi", "ive", m_gt_0) ||
   102945      stem(&z, "itilib", "ble", m_gt_0);
   102946      break;
   102947   }
   102948 
   102949   /* Step 3 */
   102950   switch( z[0] ){
   102951    case 'e':
   102952      stem(&z, "etaci", "ic", m_gt_0) ||
   102953      stem(&z, "evita", "", m_gt_0)   ||
   102954      stem(&z, "ezila", "al", m_gt_0);
   102955      break;
   102956    case 'i':
   102957      stem(&z, "itici", "ic", m_gt_0);
   102958      break;
   102959    case 'l':
   102960      stem(&z, "laci", "ic", m_gt_0) ||
   102961      stem(&z, "luf", "", m_gt_0);
   102962      break;
   102963    case 's':
   102964      stem(&z, "ssen", "", m_gt_0);
   102965      break;
   102966   }
   102967 
   102968   /* Step 4 */
   102969   switch( z[1] ){
   102970    case 'a':
   102971      if( z[0]=='l' && m_gt_1(z+2) ){
   102972        z += 2;
   102973      }
   102974      break;
   102975    case 'c':
   102976      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
   102977        z += 4;
   102978      }
   102979      break;
   102980    case 'e':
   102981      if( z[0]=='r' && m_gt_1(z+2) ){
   102982        z += 2;
   102983      }
   102984      break;
   102985    case 'i':
   102986      if( z[0]=='c' && m_gt_1(z+2) ){
   102987        z += 2;
   102988      }
   102989      break;
   102990    case 'l':
   102991      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
   102992        z += 4;
   102993      }
   102994      break;
   102995    case 'n':
   102996      if( z[0]=='t' ){
   102997        if( z[2]=='a' ){
   102998          if( m_gt_1(z+3) ){
   102999            z += 3;
   103000          }
   103001        }else if( z[2]=='e' ){
   103002          stem(&z, "tneme", "", m_gt_1) ||
   103003          stem(&z, "tnem", "", m_gt_1) ||
   103004          stem(&z, "tne", "", m_gt_1);
   103005        }
   103006      }
   103007      break;
   103008    case 'o':
   103009      if( z[0]=='u' ){
   103010        if( m_gt_1(z+2) ){
   103011          z += 2;
   103012        }
   103013      }else if( z[3]=='s' || z[3]=='t' ){
   103014        stem(&z, "noi", "", m_gt_1);
   103015      }
   103016      break;
   103017    case 's':
   103018      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
   103019        z += 3;
   103020      }
   103021      break;
   103022    case 't':
   103023      stem(&z, "eta", "", m_gt_1) ||
   103024      stem(&z, "iti", "", m_gt_1);
   103025      break;
   103026    case 'u':
   103027      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
   103028        z += 3;
   103029      }
   103030      break;
   103031    case 'v':
   103032    case 'z':
   103033      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
   103034        z += 3;
   103035      }
   103036      break;
   103037   }
   103038 
   103039   /* Step 5a */
   103040   if( z[0]=='e' ){
   103041     if( m_gt_1(z+1) ){
   103042       z++;
   103043     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
   103044       z++;
   103045     }
   103046   }
   103047 
   103048   /* Step 5b */
   103049   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
   103050     z++;
   103051   }
   103052 
   103053   /* z[] is now the stemmed word in reverse order.  Flip it back
   103054   ** around into forward order and return.
   103055   */
   103056   *pnOut = i = (int)strlen(z);
   103057   zOut[i] = 0;
   103058   while( *z ){
   103059     zOut[--i] = *(z++);
   103060   }
   103061 }
   103062 
   103063 /*
   103064 ** Characters that can be part of a token.  We assume any character
   103065 ** whose value is greater than 0x80 (any UTF character) can be
   103066 ** part of a token.  In other words, delimiters all must have
   103067 ** values of 0x7f or lower.
   103068 */
   103069 static const char porterIdChar[] = {
   103070 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
   103071     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
   103072     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
   103073     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
   103074     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
   103075     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
   103076 };
   103077 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
   103078 
   103079 /*
   103080 ** Extract the next token from a tokenization cursor.  The cursor must
   103081 ** have been opened by a prior call to porterOpen().
   103082 */
   103083 static int porterNext(
   103084   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
   103085   const char **pzToken,               /* OUT: *pzToken is the token text */
   103086   int *pnBytes,                       /* OUT: Number of bytes in token */
   103087   int *piStartOffset,                 /* OUT: Starting offset of token */
   103088   int *piEndOffset,                   /* OUT: Ending offset of token */
   103089   int *piPosition                     /* OUT: Position integer of token */
   103090 ){
   103091   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
   103092   const char *z = c->zInput;
   103093 
   103094   while( c->iOffset<c->nInput ){
   103095     int iStartOffset, ch;
   103096 
   103097     /* Scan past delimiter characters */
   103098     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
   103099       c->iOffset++;
   103100     }
   103101 
   103102     /* Count non-delimiter characters. */
   103103     iStartOffset = c->iOffset;
   103104     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
   103105       c->iOffset++;
   103106     }
   103107 
   103108     if( c->iOffset>iStartOffset ){
   103109       int n = c->iOffset-iStartOffset;
   103110       if( n>c->nAllocated ){
   103111         c->nAllocated = n+20;
   103112         c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
   103113         if( c->zToken==NULL ) return SQLITE_NOMEM;
   103114       }
   103115       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
   103116       *pzToken = c->zToken;
   103117       *piStartOffset = iStartOffset;
   103118       *piEndOffset = c->iOffset;
   103119       *piPosition = c->iToken++;
   103120       return SQLITE_OK;
   103121     }
   103122   }
   103123   return SQLITE_DONE;
   103124 }
   103125 
   103126 /*
   103127 ** The set of routines that implement the porter-stemmer tokenizer
   103128 */
   103129 static const sqlite3_tokenizer_module porterTokenizerModule = {
   103130   0,
   103131   porterCreate,
   103132   porterDestroy,
   103133   porterOpen,
   103134   porterClose,
   103135   porterNext,
   103136 };
   103137 
   103138 /*
   103139 ** Allocate a new porter tokenizer.  Return a pointer to the new
   103140 ** tokenizer in *ppModule
   103141 */
   103142 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
   103143   sqlite3_tokenizer_module const**ppModule
   103144 ){
   103145   *ppModule = &porterTokenizerModule;
   103146 }
   103147 
   103148 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   103149 
   103150 /************** End of fts3_porter.c *****************************************/
   103151 /************** Begin file fts3_tokenizer.c **********************************/
   103152 /*
   103153 ** 2007 June 22
   103154 **
   103155 ** The author disclaims copyright to this source code.  In place of
   103156 ** a legal notice, here is a blessing:
   103157 **
   103158 **    May you do good and not evil.
   103159 **    May you find forgiveness for yourself and forgive others.
   103160 **    May you share freely, never taking more than you give.
   103161 **
   103162 ******************************************************************************
   103163 **
   103164 ** This is part of an SQLite module implementing full-text search.
   103165 ** This particular file implements the generic tokenizer interface.
   103166 */
   103167 
   103168 /*
   103169 ** The code in this file is only compiled if:
   103170 **
   103171 **     * The FTS3 module is being built as an extension
   103172 **       (in which case SQLITE_CORE is not defined), or
   103173 **
   103174 **     * The FTS3 module is being built into the core of
   103175 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   103176 */
   103177 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   103178 
   103179 #ifndef SQLITE_CORE
   103180   SQLITE_EXTENSION_INIT1
   103181 #endif
   103182 
   103183 
   103184 /*
   103185 ** Implementation of the SQL scalar function for accessing the underlying
   103186 ** hash table. This function may be called as follows:
   103187 **
   103188 **   SELECT <function-name>(<key-name>);
   103189 **   SELECT <function-name>(<key-name>, <pointer>);
   103190 **
   103191 ** where <function-name> is the name passed as the second argument
   103192 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
   103193 **
   103194 ** If the <pointer> argument is specified, it must be a blob value
   103195 ** containing a pointer to be stored as the hash data corresponding
   103196 ** to the string <key-name>. If <pointer> is not specified, then
   103197 ** the string <key-name> must already exist in the has table. Otherwise,
   103198 ** an error is returned.
   103199 **
   103200 ** Whether or not the <pointer> argument is specified, the value returned
   103201 ** is a blob containing the pointer stored as the hash data corresponding
   103202 ** to string <key-name> (after the hash-table is updated, if applicable).
   103203 */
   103204 static void scalarFunc(
   103205   sqlite3_context *context,
   103206   int argc,
   103207   sqlite3_value **argv
   103208 ){
   103209   Fts3Hash *pHash;
   103210   void *pPtr = 0;
   103211   const unsigned char *zName;
   103212   int nName;
   103213 
   103214   assert( argc==1 || argc==2 );
   103215 
   103216   pHash = (Fts3Hash *)sqlite3_user_data(context);
   103217 
   103218   zName = sqlite3_value_text(argv[0]);
   103219   nName = sqlite3_value_bytes(argv[0])+1;
   103220 
   103221   if( argc==2 ){
   103222     void *pOld;
   103223     int n = sqlite3_value_bytes(argv[1]);
   103224     if( n!=sizeof(pPtr) ){
   103225       sqlite3_result_error(context, "argument type mismatch", -1);
   103226       return;
   103227     }
   103228     pPtr = *(void **)sqlite3_value_blob(argv[1]);
   103229     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
   103230     if( pOld==pPtr ){
   103231       sqlite3_result_error(context, "out of memory", -1);
   103232       return;
   103233     }
   103234   }else{
   103235     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
   103236     if( !pPtr ){
   103237       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
   103238       sqlite3_result_error(context, zErr, -1);
   103239       sqlite3_free(zErr);
   103240       return;
   103241     }
   103242   }
   103243 
   103244   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
   103245 }
   103246 
   103247 static int fts3IsIdChar(char c){
   103248   static const char isFtsIdChar[] = {
   103249       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
   103250       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
   103251       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
   103252       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
   103253       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
   103254       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
   103255       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
   103256       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
   103257   };
   103258   return (c&0x80 || isFtsIdChar[(int)(c)]);
   103259 }
   103260 
   103261 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
   103262   const char *z1;
   103263   const char *z2 = 0;
   103264 
   103265   /* Find the start of the next token. */
   103266   z1 = zStr;
   103267   while( z2==0 ){
   103268     char c = *z1;
   103269     switch( c ){
   103270       case '\0': return 0;        /* No more tokens here */
   103271       case '\'':
   103272       case '"':
   103273       case '`': {
   103274         z2 = z1;
   103275         while( *++z2 && (*z2!=c || *++z2==c) );
   103276         break;
   103277       }
   103278       case '[':
   103279         z2 = &z1[1];
   103280         while( *z2 && z2[0]!=']' ) z2++;
   103281         if( *z2 ) z2++;
   103282         break;
   103283 
   103284       default:
   103285         if( fts3IsIdChar(*z1) ){
   103286           z2 = &z1[1];
   103287           while( fts3IsIdChar(*z2) ) z2++;
   103288         }else{
   103289           z1++;
   103290         }
   103291     }
   103292   }
   103293 
   103294   *pn = (int)(z2-z1);
   103295   return z1;
   103296 }
   103297 
   103298 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
   103299   Fts3Hash *pHash,                /* Tokenizer hash table */
   103300   const char *zArg,               /* Possible tokenizer specification */
   103301   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
   103302   const char **pzTokenizer,       /* OUT: Set to zArg if is tokenizer */
   103303   char **pzErr                    /* OUT: Set to malloced error message */
   103304 ){
   103305   int rc;
   103306   char *z = (char *)zArg;
   103307   int n;
   103308   char *zCopy;
   103309   char *zEnd;                     /* Pointer to nul-term of zCopy */
   103310   sqlite3_tokenizer_module *m;
   103311 
   103312   if( !z ){
   103313     zCopy = sqlite3_mprintf("simple");
   103314   }else{
   103315     if( sqlite3_strnicmp(z, "tokenize", 8) || fts3IsIdChar(z[8])){
   103316       return SQLITE_OK;
   103317     }
   103318     zCopy = sqlite3_mprintf("%s", &z[8]);
   103319     *pzTokenizer = zArg;
   103320   }
   103321   if( !zCopy ){
   103322     return SQLITE_NOMEM;
   103323   }
   103324 
   103325   zEnd = &zCopy[strlen(zCopy)];
   103326 
   103327   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
   103328   z[n] = '\0';
   103329   sqlite3Fts3Dequote(z);
   103330 
   103331   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, z, (int)strlen(z)+1);
   103332   if( !m ){
   103333     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
   103334     rc = SQLITE_ERROR;
   103335   }else{
   103336     char const **aArg = 0;
   103337     int iArg = 0;
   103338     z = &z[n+1];
   103339     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
   103340       int nNew = sizeof(char *)*(iArg+1);
   103341       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
   103342       if( !aNew ){
   103343         sqlite3_free(zCopy);
   103344         sqlite3_free((void *)aArg);
   103345         return SQLITE_NOMEM;
   103346       }
   103347       aArg = aNew;
   103348       aArg[iArg++] = z;
   103349       z[n] = '\0';
   103350       sqlite3Fts3Dequote(z);
   103351       z = &z[n+1];
   103352     }
   103353     rc = m->xCreate(iArg, aArg, ppTok);
   103354     assert( rc!=SQLITE_OK || *ppTok );
   103355     if( rc!=SQLITE_OK ){
   103356       *pzErr = sqlite3_mprintf("unknown tokenizer");
   103357     }else{
   103358       (*ppTok)->pModule = m;
   103359     }
   103360     sqlite3_free((void *)aArg);
   103361   }
   103362 
   103363   sqlite3_free(zCopy);
   103364   return rc;
   103365 }
   103366 
   103367 
   103368 #ifdef SQLITE_TEST
   103369 
   103370 
   103371 /*
   103372 ** Implementation of a special SQL scalar function for testing tokenizers
   103373 ** designed to be used in concert with the Tcl testing framework. This
   103374 ** function must be called with two arguments:
   103375 **
   103376 **   SELECT <function-name>(<key-name>, <input-string>);
   103377 **   SELECT <function-name>(<key-name>, <pointer>);
   103378 **
   103379 ** where <function-name> is the name passed as the second argument
   103380 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
   103381 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
   103382 **
   103383 ** The return value is a string that may be interpreted as a Tcl
   103384 ** list. For each token in the <input-string>, three elements are
   103385 ** added to the returned list. The first is the token position, the
   103386 ** second is the token text (folded, stemmed, etc.) and the third is the
   103387 ** substring of <input-string> associated with the token. For example,
   103388 ** using the built-in "simple" tokenizer:
   103389 **
   103390 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
   103391 **
   103392 ** will return the string:
   103393 **
   103394 **   "{0 i I 1 dont don't 2 see see 3 how how}"
   103395 **
   103396 */
   103397 static void testFunc(
   103398   sqlite3_context *context,
   103399   int argc,
   103400   sqlite3_value **argv
   103401 ){
   103402   Fts3Hash *pHash;
   103403   sqlite3_tokenizer_module *p;
   103404   sqlite3_tokenizer *pTokenizer = 0;
   103405   sqlite3_tokenizer_cursor *pCsr = 0;
   103406 
   103407   const char *zErr = 0;
   103408 
   103409   const char *zName;
   103410   int nName;
   103411   const char *zInput;
   103412   int nInput;
   103413 
   103414   const char *zArg = 0;
   103415 
   103416   const char *zToken;
   103417   int nToken;
   103418   int iStart;
   103419   int iEnd;
   103420   int iPos;
   103421 
   103422   Tcl_Obj *pRet;
   103423 
   103424   assert( argc==2 || argc==3 );
   103425 
   103426   nName = sqlite3_value_bytes(argv[0]);
   103427   zName = (const char *)sqlite3_value_text(argv[0]);
   103428   nInput = sqlite3_value_bytes(argv[argc-1]);
   103429   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
   103430 
   103431   if( argc==3 ){
   103432     zArg = (const char *)sqlite3_value_text(argv[1]);
   103433   }
   103434 
   103435   pHash = (Fts3Hash *)sqlite3_user_data(context);
   103436   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
   103437 
   103438   if( !p ){
   103439     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
   103440     sqlite3_result_error(context, zErr, -1);
   103441     sqlite3_free(zErr);
   103442     return;
   103443   }
   103444 
   103445   pRet = Tcl_NewObj();
   103446   Tcl_IncrRefCount(pRet);
   103447 
   103448   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
   103449     zErr = "error in xCreate()";
   103450     goto finish;
   103451   }
   103452   pTokenizer->pModule = p;
   103453   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
   103454     zErr = "error in xOpen()";
   103455     goto finish;
   103456   }
   103457   pCsr->pTokenizer = pTokenizer;
   103458 
   103459   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
   103460     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
   103461     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
   103462     zToken = &zInput[iStart];
   103463     nToken = iEnd-iStart;
   103464     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
   103465   }
   103466 
   103467   if( SQLITE_OK!=p->xClose(pCsr) ){
   103468     zErr = "error in xClose()";
   103469     goto finish;
   103470   }
   103471   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
   103472     zErr = "error in xDestroy()";
   103473     goto finish;
   103474   }
   103475 
   103476 finish:
   103477   if( zErr ){
   103478     sqlite3_result_error(context, zErr, -1);
   103479   }else{
   103480     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
   103481   }
   103482   Tcl_DecrRefCount(pRet);
   103483 }
   103484 
   103485 static
   103486 int registerTokenizer(
   103487   sqlite3 *db,
   103488   char *zName,
   103489   const sqlite3_tokenizer_module *p
   103490 ){
   103491   int rc;
   103492   sqlite3_stmt *pStmt;
   103493   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
   103494 
   103495   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   103496   if( rc!=SQLITE_OK ){
   103497     return rc;
   103498   }
   103499 
   103500   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   103501   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
   103502   sqlite3_step(pStmt);
   103503 
   103504   return sqlite3_finalize(pStmt);
   103505 }
   103506 
   103507 static
   103508 int queryTokenizer(
   103509   sqlite3 *db,
   103510   char *zName,
   103511   const sqlite3_tokenizer_module **pp
   103512 ){
   103513   int rc;
   103514   sqlite3_stmt *pStmt;
   103515   const char zSql[] = "SELECT fts3_tokenizer(?)";
   103516 
   103517   *pp = 0;
   103518   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   103519   if( rc!=SQLITE_OK ){
   103520     return rc;
   103521   }
   103522 
   103523   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   103524   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   103525     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
   103526       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
   103527     }
   103528   }
   103529 
   103530   return sqlite3_finalize(pStmt);
   103531 }
   103532 
   103533 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   103534 
   103535 /*
   103536 ** Implementation of the scalar function fts3_tokenizer_internal_test().
   103537 ** This function is used for testing only, it is not included in the
   103538 ** build unless SQLITE_TEST is defined.
   103539 **
   103540 ** The purpose of this is to test that the fts3_tokenizer() function
   103541 ** can be used as designed by the C-code in the queryTokenizer and
   103542 ** registerTokenizer() functions above. These two functions are repeated
   103543 ** in the README.tokenizer file as an example, so it is important to
   103544 ** test them.
   103545 **
   103546 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
   103547 ** function with no arguments. An assert() will fail if a problem is
   103548 ** detected. i.e.:
   103549 **
   103550 **     SELECT fts3_tokenizer_internal_test();
   103551 **
   103552 */
   103553 static void intTestFunc(
   103554   sqlite3_context *context,
   103555   int argc,
   103556   sqlite3_value **argv
   103557 ){
   103558   int rc;
   103559   const sqlite3_tokenizer_module *p1;
   103560   const sqlite3_tokenizer_module *p2;
   103561   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
   103562 
   103563   UNUSED_PARAMETER(argc);
   103564   UNUSED_PARAMETER(argv);
   103565 
   103566   /* Test the query function */
   103567   sqlite3Fts3SimpleTokenizerModule(&p1);
   103568   rc = queryTokenizer(db, "simple", &p2);
   103569   assert( rc==SQLITE_OK );
   103570   assert( p1==p2 );
   103571   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
   103572   assert( rc==SQLITE_ERROR );
   103573   assert( p2==0 );
   103574   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
   103575 
   103576   /* Test the storage function */
   103577   rc = registerTokenizer(db, "nosuchtokenizer", p1);
   103578   assert( rc==SQLITE_OK );
   103579   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
   103580   assert( rc==SQLITE_OK );
   103581   assert( p2==p1 );
   103582 
   103583   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
   103584 }
   103585 
   103586 #endif
   103587 
   103588 /*
   103589 ** Set up SQL objects in database db used to access the contents of
   103590 ** the hash table pointed to by argument pHash. The hash table must
   103591 ** been initialised to use string keys, and to take a private copy
   103592 ** of the key when a value is inserted. i.e. by a call similar to:
   103593 **
   103594 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
   103595 **
   103596 ** This function adds a scalar function (see header comment above
   103597 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
   103598 ** defined at compilation time, a temporary virtual table (see header
   103599 ** comment above struct HashTableVtab) to the database schema. Both
   103600 ** provide read/write access to the contents of *pHash.
   103601 **
   103602 ** The third argument to this function, zName, is used as the name
   103603 ** of both the scalar and, if created, the virtual table.
   103604 */
   103605 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
   103606   sqlite3 *db,
   103607   Fts3Hash *pHash,
   103608   const char *zName
   103609 ){
   103610   int rc = SQLITE_OK;
   103611   void *p = (void *)pHash;
   103612   const int any = SQLITE_ANY;
   103613 
   103614 #ifdef SQLITE_TEST
   103615   char *zTest = 0;
   103616   char *zTest2 = 0;
   103617   void *pdb = (void *)db;
   103618   zTest = sqlite3_mprintf("%s_test", zName);
   103619   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
   103620   if( !zTest || !zTest2 ){
   103621     rc = SQLITE_NOMEM;
   103622   }
   103623 #endif
   103624 
   103625   if( SQLITE_OK!=rc
   103626    || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
   103627    || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
   103628 #ifdef SQLITE_TEST
   103629    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
   103630    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
   103631    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
   103632 #endif
   103633    );
   103634 
   103635 #ifdef SQLITE_TEST
   103636   sqlite3_free(zTest);
   103637   sqlite3_free(zTest2);
   103638 #endif
   103639 
   103640   return rc;
   103641 }
   103642 
   103643 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   103644 
   103645 /************** End of fts3_tokenizer.c **************************************/
   103646 /************** Begin file fts3_tokenizer1.c *********************************/
   103647 /*
   103648 ** 2006 Oct 10
   103649 **
   103650 ** The author disclaims copyright to this source code.  In place of
   103651 ** a legal notice, here is a blessing:
   103652 **
   103653 **    May you do good and not evil.
   103654 **    May you find forgiveness for yourself and forgive others.
   103655 **    May you share freely, never taking more than you give.
   103656 **
   103657 ******************************************************************************
   103658 **
   103659 ** Implementation of the "simple" full-text-search tokenizer.
   103660 */
   103661 
   103662 /*
   103663 ** The code in this file is only compiled if:
   103664 **
   103665 **     * The FTS3 module is being built as an extension
   103666 **       (in which case SQLITE_CORE is not defined), or
   103667 **
   103668 **     * The FTS3 module is being built into the core of
   103669 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   103670 */
   103671 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   103672 
   103673 
   103674 
   103675 
   103676 typedef struct simple_tokenizer {
   103677   sqlite3_tokenizer base;
   103678   char delim[128];             /* flag ASCII delimiters */
   103679 } simple_tokenizer;
   103680 
   103681 typedef struct simple_tokenizer_cursor {
   103682   sqlite3_tokenizer_cursor base;
   103683   const char *pInput;          /* input we are tokenizing */
   103684   int nBytes;                  /* size of the input */
   103685   int iOffset;                 /* current position in pInput */
   103686   int iToken;                  /* index of next token to be returned */
   103687   char *pToken;                /* storage for current token */
   103688   int nTokenAllocated;         /* space allocated to zToken buffer */
   103689 } simple_tokenizer_cursor;
   103690 
   103691 
   103692 static int simpleDelim(simple_tokenizer *t, unsigned char c){
   103693   return c<0x80 && t->delim[c];
   103694 }
   103695 
   103696 /*
   103697 ** Create a new tokenizer instance.
   103698 */
   103699 static int simpleCreate(
   103700   int argc, const char * const *argv,
   103701   sqlite3_tokenizer **ppTokenizer
   103702 ){
   103703   simple_tokenizer *t;
   103704 
   103705   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
   103706   if( t==NULL ) return SQLITE_NOMEM;
   103707   memset(t, 0, sizeof(*t));
   103708 
   103709   /* TODO(shess) Delimiters need to remain the same from run to run,
   103710   ** else we need to reindex.  One solution would be a meta-table to
   103711   ** track such information in the database, then we'd only want this
   103712   ** information on the initial create.
   103713   */
   103714   if( argc>1 ){
   103715     int i, n = (int)strlen(argv[1]);
   103716     for(i=0; i<n; i++){
   103717       unsigned char ch = argv[1][i];
   103718       /* We explicitly don't support UTF-8 delimiters for now. */
   103719       if( ch>=0x80 ){
   103720         sqlite3_free(t);
   103721         return SQLITE_ERROR;
   103722       }
   103723       t->delim[ch] = 1;
   103724     }
   103725   } else {
   103726     /* Mark non-alphanumeric ASCII characters as delimiters */
   103727     int i;
   103728     for(i=1; i<0x80; i++){
   103729       t->delim[i] = !isalnum(i) ? -1 : 0;
   103730     }
   103731   }
   103732 
   103733   *ppTokenizer = &t->base;
   103734   return SQLITE_OK;
   103735 }
   103736 
   103737 /*
   103738 ** Destroy a tokenizer
   103739 */
   103740 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
   103741   sqlite3_free(pTokenizer);
   103742   return SQLITE_OK;
   103743 }
   103744 
   103745 /*
   103746 ** Prepare to begin tokenizing a particular string.  The input
   103747 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   103748 ** used to incrementally tokenize this string is returned in
   103749 ** *ppCursor.
   103750 */
   103751 static int simpleOpen(
   103752   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   103753   const char *pInput, int nBytes,        /* String to be tokenized */
   103754   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   103755 ){
   103756   simple_tokenizer_cursor *c;
   103757 
   103758   UNUSED_PARAMETER(pTokenizer);
   103759 
   103760   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
   103761   if( c==NULL ) return SQLITE_NOMEM;
   103762 
   103763   c->pInput = pInput;
   103764   if( pInput==0 ){
   103765     c->nBytes = 0;
   103766   }else if( nBytes<0 ){
   103767     c->nBytes = (int)strlen(pInput);
   103768   }else{
   103769     c->nBytes = nBytes;
   103770   }
   103771   c->iOffset = 0;                 /* start tokenizing at the beginning */
   103772   c->iToken = 0;
   103773   c->pToken = NULL;               /* no space allocated, yet. */
   103774   c->nTokenAllocated = 0;
   103775 
   103776   *ppCursor = &c->base;
   103777   return SQLITE_OK;
   103778 }
   103779 
   103780 /*
   103781 ** Close a tokenization cursor previously opened by a call to
   103782 ** simpleOpen() above.
   103783 */
   103784 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
   103785   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
   103786   sqlite3_free(c->pToken);
   103787   sqlite3_free(c);
   103788   return SQLITE_OK;
   103789 }
   103790 
   103791 /*
   103792 ** Extract the next token from a tokenization cursor.  The cursor must
   103793 ** have been opened by a prior call to simpleOpen().
   103794 */
   103795 static int simpleNext(
   103796   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
   103797   const char **ppToken,               /* OUT: *ppToken is the token text */
   103798   int *pnBytes,                       /* OUT: Number of bytes in token */
   103799   int *piStartOffset,                 /* OUT: Starting offset of token */
   103800   int *piEndOffset,                   /* OUT: Ending offset of token */
   103801   int *piPosition                     /* OUT: Position integer of token */
   103802 ){
   103803   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
   103804   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
   103805   unsigned char *p = (unsigned char *)c->pInput;
   103806 
   103807   while( c->iOffset<c->nBytes ){
   103808     int iStartOffset;
   103809 
   103810     /* Scan past delimiter characters */
   103811     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
   103812       c->iOffset++;
   103813     }
   103814 
   103815     /* Count non-delimiter characters. */
   103816     iStartOffset = c->iOffset;
   103817     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
   103818       c->iOffset++;
   103819     }
   103820 
   103821     if( c->iOffset>iStartOffset ){
   103822       int i, n = c->iOffset-iStartOffset;
   103823       if( n>c->nTokenAllocated ){
   103824         c->nTokenAllocated = n+20;
   103825         c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
   103826         if( c->pToken==NULL ) return SQLITE_NOMEM;
   103827       }
   103828       for(i=0; i<n; i++){
   103829         /* TODO(shess) This needs expansion to handle UTF-8
   103830         ** case-insensitivity.
   103831         */
   103832         unsigned char ch = p[iStartOffset+i];
   103833         c->pToken[i] = (char)(ch<0x80 ? tolower(ch) : ch);
   103834       }
   103835       *ppToken = c->pToken;
   103836       *pnBytes = n;
   103837       *piStartOffset = iStartOffset;
   103838       *piEndOffset = c->iOffset;
   103839       *piPosition = c->iToken++;
   103840 
   103841       return SQLITE_OK;
   103842     }
   103843   }
   103844   return SQLITE_DONE;
   103845 }
   103846 
   103847 /*
   103848 ** The set of routines that implement the simple tokenizer
   103849 */
   103850 static const sqlite3_tokenizer_module simpleTokenizerModule = {
   103851   0,
   103852   simpleCreate,
   103853   simpleDestroy,
   103854   simpleOpen,
   103855   simpleClose,
   103856   simpleNext,
   103857 };
   103858 
   103859 /*
   103860 ** Allocate a new simple tokenizer.  Return a pointer to the new
   103861 ** tokenizer in *ppModule
   103862 */
   103863 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
   103864   sqlite3_tokenizer_module const**ppModule
   103865 ){
   103866   *ppModule = &simpleTokenizerModule;
   103867 }
   103868 
   103869 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   103870 
   103871 /************** End of fts3_tokenizer1.c *************************************/
   103872 /************** Begin file fts3_write.c **************************************/
   103873 /*
   103874 ** 2009 Oct 23
   103875 **
   103876 ** The author disclaims copyright to this source code.  In place of
   103877 ** a legal notice, here is a blessing:
   103878 **
   103879 **    May you do good and not evil.
   103880 **    May you find forgiveness for yourself and forgive others.
   103881 **    May you share freely, never taking more than you give.
   103882 **
   103883 ******************************************************************************
   103884 **
   103885 ** This file is part of the SQLite FTS3 extension module. Specifically,
   103886 ** this file contains code to insert, update and delete rows from FTS3
   103887 ** tables. It also contains code to merge FTS3 b-tree segments. Some
   103888 ** of the sub-routines used to merge segments are also used by the query
   103889 ** code in fts3.c.
   103890 */
   103891 
   103892 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   103893 
   103894 
   103895 typedef struct PendingList PendingList;
   103896 typedef struct SegmentNode SegmentNode;
   103897 typedef struct SegmentWriter SegmentWriter;
   103898 
   103899 /*
   103900 ** Data structure used while accumulating terms in the pending-terms hash
   103901 ** table. The hash table entry maps from term (a string) to a malloc'd
   103902 ** instance of this structure.
   103903 */
   103904 struct PendingList {
   103905   int nData;
   103906   char *aData;
   103907   int nSpace;
   103908   sqlite3_int64 iLastDocid;
   103909   sqlite3_int64 iLastCol;
   103910   sqlite3_int64 iLastPos;
   103911 };
   103912 
   103913 /*
   103914 ** An instance of this structure is used to iterate through the terms on
   103915 ** a contiguous set of segment b-tree leaf nodes. Although the details of
   103916 ** this structure are only manipulated by code in this file, opaque handles
   103917 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
   103918 ** terms when querying the full-text index. See functions:
   103919 **
   103920 **   sqlite3Fts3SegReaderNew()
   103921 **   sqlite3Fts3SegReaderFree()
   103922 **   sqlite3Fts3SegReaderIterate()
   103923 **
   103924 ** Methods used to manipulate Fts3SegReader structures:
   103925 **
   103926 **   fts3SegReaderNext()
   103927 **   fts3SegReaderFirstDocid()
   103928 **   fts3SegReaderNextDocid()
   103929 */
   103930 struct Fts3SegReader {
   103931   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
   103932   sqlite3_int64 iStartBlock;
   103933   sqlite3_int64 iEndBlock;
   103934   sqlite3_stmt *pStmt;            /* SQL Statement to access leaf nodes */
   103935   char *aNode;                    /* Pointer to node data (or NULL) */
   103936   int nNode;                      /* Size of buffer at aNode (or 0) */
   103937   int nTermAlloc;                 /* Allocated size of zTerm buffer */
   103938   Fts3HashElem **ppNextElem;
   103939 
   103940   /* Variables set by fts3SegReaderNext(). These may be read directly
   103941   ** by the caller. They are valid from the time SegmentReaderNew() returns
   103942   ** until SegmentReaderNext() returns something other than SQLITE_OK
   103943   ** (i.e. SQLITE_DONE).
   103944   */
   103945   int nTerm;                      /* Number of bytes in current term */
   103946   char *zTerm;                    /* Pointer to current term */
   103947   char *aDoclist;                 /* Pointer to doclist of current entry */
   103948   int nDoclist;                   /* Size of doclist in current entry */
   103949 
   103950   /* The following variables are used to iterate through the current doclist */
   103951   char *pOffsetList;
   103952   sqlite3_int64 iDocid;
   103953 };
   103954 
   103955 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
   103956 
   103957 /*
   103958 ** An instance of this structure is used to create a segment b-tree in the
   103959 ** database. The internal details of this type are only accessed by the
   103960 ** following functions:
   103961 **
   103962 **   fts3SegWriterAdd()
   103963 **   fts3SegWriterFlush()
   103964 **   fts3SegWriterFree()
   103965 */
   103966 struct SegmentWriter {
   103967   SegmentNode *pTree;             /* Pointer to interior tree structure */
   103968   sqlite3_int64 iFirst;           /* First slot in %_segments written */
   103969   sqlite3_int64 iFree;            /* Next free slot in %_segments */
   103970   char *zTerm;                    /* Pointer to previous term buffer */
   103971   int nTerm;                      /* Number of bytes in zTerm */
   103972   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
   103973   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
   103974   int nSize;                      /* Size of allocation at aData */
   103975   int nData;                      /* Bytes of data in aData */
   103976   char *aData;                    /* Pointer to block from malloc() */
   103977 };
   103978 
   103979 /*
   103980 ** Type SegmentNode is used by the following three functions to create
   103981 ** the interior part of the segment b+-tree structures (everything except
   103982 ** the leaf nodes). These functions and type are only ever used by code
   103983 ** within the fts3SegWriterXXX() family of functions described above.
   103984 **
   103985 **   fts3NodeAddTerm()
   103986 **   fts3NodeWrite()
   103987 **   fts3NodeFree()
   103988 */
   103989 struct SegmentNode {
   103990   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
   103991   SegmentNode *pRight;            /* Pointer to right-sibling */
   103992   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
   103993   int nEntry;                     /* Number of terms written to node so far */
   103994   char *zTerm;                    /* Pointer to previous term buffer */
   103995   int nTerm;                      /* Number of bytes in zTerm */
   103996   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
   103997   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
   103998   int nData;                      /* Bytes of valid data so far */
   103999   char *aData;                    /* Node data */
   104000 };
   104001 
   104002 /*
   104003 ** Valid values for the second argument to fts3SqlStmt().
   104004 */
   104005 #define SQL_DELETE_CONTENT             0
   104006 #define SQL_IS_EMPTY                   1
   104007 #define SQL_DELETE_ALL_CONTENT         2
   104008 #define SQL_DELETE_ALL_SEGMENTS        3
   104009 #define SQL_DELETE_ALL_SEGDIR          4
   104010 #define SQL_SELECT_CONTENT_BY_ROWID    5
   104011 #define SQL_NEXT_SEGMENT_INDEX         6
   104012 #define SQL_INSERT_SEGMENTS            7
   104013 #define SQL_NEXT_SEGMENTS_ID           8
   104014 #define SQL_INSERT_SEGDIR              9
   104015 #define SQL_SELECT_LEVEL              10
   104016 #define SQL_SELECT_ALL_LEVEL          11
   104017 #define SQL_SELECT_LEVEL_COUNT        12
   104018 #define SQL_SELECT_SEGDIR_COUNT_MAX   13
   104019 #define SQL_DELETE_SEGDIR_BY_LEVEL    14
   104020 #define SQL_DELETE_SEGMENTS_RANGE     15
   104021 #define SQL_CONTENT_INSERT            16
   104022 #define SQL_GET_BLOCK                 17
   104023 
   104024 /*
   104025 ** This function is used to obtain an SQLite prepared statement handle
   104026 ** for the statement identified by the second argument. If successful,
   104027 ** *pp is set to the requested statement handle and SQLITE_OK returned.
   104028 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
   104029 **
   104030 ** If argument apVal is not NULL, then it must point to an array with
   104031 ** at least as many entries as the requested statement has bound
   104032 ** parameters. The values are bound to the statements parameters before
   104033 ** returning.
   104034 */
   104035 static int fts3SqlStmt(
   104036   Fts3Table *p,                   /* Virtual table handle */
   104037   int eStmt,                      /* One of the SQL_XXX constants above */
   104038   sqlite3_stmt **pp,              /* OUT: Statement handle */
   104039   sqlite3_value **apVal           /* Values to bind to statement */
   104040 ){
   104041   const char *azSql[] = {
   104042 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
   104043 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
   104044 /* 2  */  "DELETE FROM %Q.'%q_content'",
   104045 /* 3  */  "DELETE FROM %Q.'%q_segments'",
   104046 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
   104047 /* 5  */  "SELECT * FROM %Q.'%q_content' WHERE rowid=?",
   104048 /* 6  */  "SELECT coalesce(max(idx)+1, 0) FROM %Q.'%q_segdir' WHERE level=?",
   104049 /* 7  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
   104050 /* 8  */  "SELECT coalesce(max(blockid)+1, 1) FROM %Q.'%q_segments'",
   104051 /* 9  */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
   104052 
   104053           /* Return segments in order from oldest to newest.*/
   104054 /* 10 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   104055             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
   104056 /* 11 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   104057             "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
   104058 
   104059 /* 12 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
   104060 /* 13 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
   104061 
   104062 /* 14 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
   104063 /* 15 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
   104064 /* 16 */  "INSERT INTO %Q.'%q_content' VALUES(%z)",
   104065 /* 17 */  "SELECT block FROM %Q.'%q_segments' WHERE blockid = ?",
   104066   };
   104067   int rc = SQLITE_OK;
   104068   sqlite3_stmt *pStmt;
   104069 
   104070   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
   104071   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
   104072 
   104073   pStmt = p->aStmt[eStmt];
   104074   if( !pStmt ){
   104075     char *zSql;
   104076     if( eStmt==SQL_CONTENT_INSERT ){
   104077       int i;                      /* Iterator variable */
   104078       char *zVarlist;             /* The "?, ?, ..." string */
   104079       zVarlist = (char *)sqlite3_malloc(2*p->nColumn+2);
   104080       if( !zVarlist ){
   104081         *pp = 0;
   104082         return SQLITE_NOMEM;
   104083       }
   104084       zVarlist[0] = '?';
   104085       zVarlist[p->nColumn*2+1] = '\0';
   104086       for(i=1; i<=p->nColumn; i++){
   104087         zVarlist[i*2-1] = ',';
   104088         zVarlist[i*2] = '?';
   104089       }
   104090       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, zVarlist);
   104091     }else{
   104092       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
   104093     }
   104094     if( !zSql ){
   104095       rc = SQLITE_NOMEM;
   104096     }else{
   104097       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
   104098       sqlite3_free(zSql);
   104099       assert( rc==SQLITE_OK || pStmt==0 );
   104100       p->aStmt[eStmt] = pStmt;
   104101     }
   104102   }
   104103   if( apVal ){
   104104     int i;
   104105     int nParam = sqlite3_bind_parameter_count(pStmt);
   104106     for(i=0; rc==SQLITE_OK && i<nParam; i++){
   104107       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
   104108     }
   104109   }
   104110   *pp = pStmt;
   104111   return rc;
   104112 }
   104113 
   104114 /*
   104115 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
   104116 ** array apVal[] to the SQL statement identified by eStmt, the statement
   104117 ** is executed.
   104118 **
   104119 ** Returns SQLITE_OK if the statement is successfully executed, or an
   104120 ** SQLite error code otherwise.
   104121 */
   104122 static int fts3SqlExec(Fts3Table *p, int eStmt, sqlite3_value **apVal){
   104123   sqlite3_stmt *pStmt;
   104124   int rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
   104125   if( rc==SQLITE_OK ){
   104126     sqlite3_step(pStmt);
   104127     rc = sqlite3_reset(pStmt);
   104128   }
   104129   return rc;
   104130 }
   104131 
   104132 
   104133 /*
   104134 ** Read a single block from the %_segments table. If the specified block
   104135 ** does not exist, return SQLITE_CORRUPT. If some other error (malloc, IO
   104136 ** etc.) occurs, return the appropriate SQLite error code.
   104137 **
   104138 ** Otherwise, if successful, set *pzBlock to point to a buffer containing
   104139 ** the block read from the database, and *pnBlock to the size of the read
   104140 ** block in bytes.
   104141 **
   104142 ** WARNING: The returned buffer is only valid until the next call to
   104143 ** sqlite3Fts3ReadBlock().
   104144 */
   104145 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
   104146   Fts3Table *p,
   104147   sqlite3_int64 iBlock,
   104148   char const **pzBlock,
   104149   int *pnBlock
   104150 ){
   104151   sqlite3_stmt *pStmt;
   104152   int rc = fts3SqlStmt(p, SQL_GET_BLOCK, &pStmt, 0);
   104153   if( rc!=SQLITE_OK ) return rc;
   104154   sqlite3_reset(pStmt);
   104155 
   104156   if( pzBlock ){
   104157     sqlite3_bind_int64(pStmt, 1, iBlock);
   104158     rc = sqlite3_step(pStmt);
   104159     if( rc!=SQLITE_ROW ){
   104160       return (rc==SQLITE_DONE ? SQLITE_CORRUPT : rc);
   104161     }
   104162 
   104163     *pnBlock = sqlite3_column_bytes(pStmt, 0);
   104164     *pzBlock = (char *)sqlite3_column_blob(pStmt, 0);
   104165     if( sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
   104166       return SQLITE_CORRUPT;
   104167     }
   104168   }
   104169   return SQLITE_OK;
   104170 }
   104171 
   104172 /*
   104173 ** Set *ppStmt to a statement handle that may be used to iterate through
   104174 ** all rows in the %_segdir table, from oldest to newest. If successful,
   104175 ** return SQLITE_OK. If an error occurs while preparing the statement,
   104176 ** return an SQLite error code.
   104177 **
   104178 ** There is only ever one instance of this SQL statement compiled for
   104179 ** each FTS3 table.
   104180 **
   104181 ** The statement returns the following columns from the %_segdir table:
   104182 **
   104183 **   0: idx
   104184 **   1: start_block
   104185 **   2: leaves_end_block
   104186 **   3: end_block
   104187 **   4: root
   104188 */
   104189 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, sqlite3_stmt **ppStmt){
   104190   return fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, ppStmt, 0);
   104191 }
   104192 
   104193 
   104194 /*
   104195 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
   104196 ** if successful, or an SQLite error code otherwise.
   104197 **
   104198 ** This function also serves to allocate the PendingList structure itself.
   104199 ** For example, to create a new PendingList structure containing two
   104200 ** varints:
   104201 **
   104202 **   PendingList *p = 0;
   104203 **   fts3PendingListAppendVarint(&p, 1);
   104204 **   fts3PendingListAppendVarint(&p, 2);
   104205 */
   104206 static int fts3PendingListAppendVarint(
   104207   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
   104208   sqlite3_int64 i                 /* Value to append to data */
   104209 ){
   104210   PendingList *p = *pp;
   104211 
   104212   /* Allocate or grow the PendingList as required. */
   104213   if( !p ){
   104214     p = sqlite3_malloc(sizeof(*p) + 100);
   104215     if( !p ){
   104216       return SQLITE_NOMEM;
   104217     }
   104218     p->nSpace = 100;
   104219     p->aData = (char *)&p[1];
   104220     p->nData = 0;
   104221   }
   104222   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
   104223     int nNew = p->nSpace * 2;
   104224     p = sqlite3_realloc(p, sizeof(*p) + nNew);
   104225     if( !p ){
   104226       sqlite3_free(*pp);
   104227       *pp = 0;
   104228       return SQLITE_NOMEM;
   104229     }
   104230     p->nSpace = nNew;
   104231     p->aData = (char *)&p[1];
   104232   }
   104233 
   104234   /* Append the new serialized varint to the end of the list. */
   104235   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
   104236   p->aData[p->nData] = '\0';
   104237   *pp = p;
   104238   return SQLITE_OK;
   104239 }
   104240 
   104241 /*
   104242 ** Add a docid/column/position entry to a PendingList structure. Non-zero
   104243 ** is returned if the structure is sqlite3_realloced as part of adding
   104244 ** the entry. Otherwise, zero.
   104245 **
   104246 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
   104247 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
   104248 ** it is set to SQLITE_OK.
   104249 */
   104250 static int fts3PendingListAppend(
   104251   PendingList **pp,               /* IN/OUT: PendingList structure */
   104252   sqlite3_int64 iDocid,           /* Docid for entry to add */
   104253   sqlite3_int64 iCol,             /* Column for entry to add */
   104254   sqlite3_int64 iPos,             /* Position of term for entry to add */
   104255   int *pRc                        /* OUT: Return code */
   104256 ){
   104257   PendingList *p = *pp;
   104258   int rc = SQLITE_OK;
   104259 
   104260   assert( !p || p->iLastDocid<=iDocid );
   104261 
   104262   if( !p || p->iLastDocid!=iDocid ){
   104263     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
   104264     if( p ){
   104265       assert( p->nData<p->nSpace );
   104266       assert( p->aData[p->nData]==0 );
   104267       p->nData++;
   104268     }
   104269     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
   104270       goto pendinglistappend_out;
   104271     }
   104272     p->iLastCol = -1;
   104273     p->iLastPos = 0;
   104274     p->iLastDocid = iDocid;
   104275   }
   104276   if( iCol>0 && p->iLastCol!=iCol ){
   104277     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
   104278      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
   104279     ){
   104280       goto pendinglistappend_out;
   104281     }
   104282     p->iLastCol = iCol;
   104283     p->iLastPos = 0;
   104284   }
   104285   if( iCol>=0 ){
   104286     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
   104287     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
   104288     if( rc==SQLITE_OK ){
   104289       p->iLastPos = iPos;
   104290     }
   104291   }
   104292 
   104293  pendinglistappend_out:
   104294   *pRc = rc;
   104295   if( p!=*pp ){
   104296     *pp = p;
   104297     return 1;
   104298   }
   104299   return 0;
   104300 }
   104301 
   104302 /*
   104303 ** Tokenize the nul-terminated string zText and add all tokens to the
   104304 ** pending-terms hash-table. The docid used is that currently stored in
   104305 ** p->iPrevDocid, and the column is specified by argument iCol.
   104306 **
   104307 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
   104308 */
   104309 static int fts3PendingTermsAdd(Fts3Table *p, const char *zText, int iCol){
   104310   int rc;
   104311   int iStart;
   104312   int iEnd;
   104313   int iPos;
   104314 
   104315   char const *zToken;
   104316   int nToken;
   104317 
   104318   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
   104319   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   104320   sqlite3_tokenizer_cursor *pCsr;
   104321   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
   104322       const char**,int*,int*,int*,int*);
   104323 
   104324   assert( pTokenizer && pModule );
   104325 
   104326   rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
   104327   if( rc!=SQLITE_OK ){
   104328     return rc;
   104329   }
   104330   pCsr->pTokenizer = pTokenizer;
   104331 
   104332   xNext = pModule->xNext;
   104333   while( SQLITE_OK==rc
   104334       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
   104335   ){
   104336     PendingList *pList;
   104337 
   104338     /* Positions cannot be negative; we use -1 as a terminator internally.
   104339     ** Tokens must have a non-zero length.
   104340     */
   104341     if( iPos<0 || !zToken || nToken<=0 ){
   104342       rc = SQLITE_ERROR;
   104343       break;
   104344     }
   104345 
   104346     pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
   104347     if( pList ){
   104348       p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
   104349     }
   104350     if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
   104351       if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
   104352         /* Malloc failed while inserting the new entry. This can only
   104353         ** happen if there was no previous entry for this token.
   104354         */
   104355         assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
   104356         sqlite3_free(pList);
   104357         rc = SQLITE_NOMEM;
   104358       }
   104359     }
   104360     if( rc==SQLITE_OK ){
   104361       p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
   104362     }
   104363   }
   104364 
   104365   pModule->xClose(pCsr);
   104366   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
   104367 }
   104368 
   104369 /*
   104370 ** Calling this function indicates that subsequent calls to
   104371 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
   104372 ** contents of the document with docid iDocid.
   104373 */
   104374 static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
   104375   /* TODO(shess) Explore whether partially flushing the buffer on
   104376   ** forced-flush would provide better performance.  I suspect that if
   104377   ** we ordered the doclists by size and flushed the largest until the
   104378   ** buffer was half empty, that would let the less frequent terms
   104379   ** generate longer doclists.
   104380   */
   104381   if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
   104382     int rc = sqlite3Fts3PendingTermsFlush(p);
   104383     if( rc!=SQLITE_OK ) return rc;
   104384   }
   104385   p->iPrevDocid = iDocid;
   104386   return SQLITE_OK;
   104387 }
   104388 
   104389 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
   104390   Fts3HashElem *pElem;
   104391   for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
   104392     sqlite3_free(fts3HashData(pElem));
   104393   }
   104394   fts3HashClear(&p->pendingTerms);
   104395   p->nPendingData = 0;
   104396 }
   104397 
   104398 /*
   104399 ** This function is called by the xUpdate() method as part of an INSERT
   104400 ** operation. It adds entries for each term in the new record to the
   104401 ** pendingTerms hash table.
   104402 **
   104403 ** Argument apVal is the same as the similarly named argument passed to
   104404 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
   104405 */
   104406 static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal){
   104407   int i;                          /* Iterator variable */
   104408   for(i=2; i<p->nColumn+2; i++){
   104409     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
   104410     if( zText ){
   104411       int rc = fts3PendingTermsAdd(p, zText, i-2);
   104412       if( rc!=SQLITE_OK ){
   104413         return rc;
   104414       }
   104415     }
   104416   }
   104417   return SQLITE_OK;
   104418 }
   104419 
   104420 /*
   104421 ** This function is called by the xUpdate() method for an INSERT operation.
   104422 ** The apVal parameter is passed a copy of the apVal argument passed by
   104423 ** SQLite to the xUpdate() method. i.e:
   104424 **
   104425 **   apVal[0]                Not used for INSERT.
   104426 **   apVal[1]                rowid
   104427 **   apVal[2]                Left-most user-defined column
   104428 **   ...
   104429 **   apVal[p->nColumn+1]     Right-most user-defined column
   104430 **   apVal[p->nColumn+2]     Hidden column with same name as table
   104431 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
   104432 */
   104433 static int fts3InsertData(
   104434   Fts3Table *p,                   /* Full-text table */
   104435   sqlite3_value **apVal,          /* Array of values to insert */
   104436   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
   104437 ){
   104438   int rc;                         /* Return code */
   104439   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
   104440 
   104441   /* Locate the statement handle used to insert data into the %_content
   104442   ** table. The SQL for this statement is:
   104443   **
   104444   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
   104445   **
   104446   ** The statement features N '?' variables, where N is the number of user
   104447   ** defined columns in the FTS3 table, plus one for the docid field.
   104448   */
   104449   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
   104450   if( rc!=SQLITE_OK ){
   104451     return rc;
   104452   }
   104453 
   104454   /* There is a quirk here. The users INSERT statement may have specified
   104455   ** a value for the "rowid" field, for the "docid" field, or for both.
   104456   ** Which is a problem, since "rowid" and "docid" are aliases for the
   104457   ** same value. For example:
   104458   **
   104459   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
   104460   **
   104461   ** In FTS3, this is an error. It is an error to specify non-NULL values
   104462   ** for both docid and some other rowid alias.
   104463   */
   104464   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
   104465     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
   104466      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
   104467     ){
   104468       /* A rowid/docid conflict. */
   104469       return SQLITE_ERROR;
   104470     }
   104471     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
   104472     if( rc!=SQLITE_OK ) return rc;
   104473   }
   104474 
   104475   /* Execute the statement to insert the record. Set *piDocid to the
   104476   ** new docid value.
   104477   */
   104478   sqlite3_step(pContentInsert);
   104479   rc = sqlite3_reset(pContentInsert);
   104480 
   104481   *piDocid = sqlite3_last_insert_rowid(p->db);
   104482   return rc;
   104483 }
   104484 
   104485 
   104486 
   104487 /*
   104488 ** Remove all data from the FTS3 table. Clear the hash table containing
   104489 ** pending terms.
   104490 */
   104491 static int fts3DeleteAll(Fts3Table *p){
   104492   int rc;                         /* Return code */
   104493 
   104494   /* Discard the contents of the pending-terms hash table. */
   104495   sqlite3Fts3PendingTermsClear(p);
   104496 
   104497   /* Delete everything from the %_content, %_segments and %_segdir tables. */
   104498   rc = fts3SqlExec(p, SQL_DELETE_ALL_CONTENT, 0);
   104499   if( rc==SQLITE_OK ){
   104500     rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGMENTS, 0);
   104501   }
   104502   if( rc==SQLITE_OK ){
   104503     rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGDIR, 0);
   104504   }
   104505   return rc;
   104506 }
   104507 
   104508 /*
   104509 ** The first element in the apVal[] array is assumed to contain the docid
   104510 ** (an integer) of a row about to be deleted. Remove all terms from the
   104511 ** full-text index.
   104512 */
   104513 static int fts3DeleteTerms(Fts3Table *p, sqlite3_value **apVal){
   104514   int rc;
   104515   sqlite3_stmt *pSelect;
   104516 
   104517   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
   104518   if( rc==SQLITE_OK ){
   104519     if( SQLITE_ROW==sqlite3_step(pSelect) ){
   104520       int i;
   104521       for(i=1; i<=p->nColumn; i++){
   104522         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
   104523         rc = fts3PendingTermsAdd(p, zText, -1);
   104524         if( rc!=SQLITE_OK ){
   104525           sqlite3_reset(pSelect);
   104526           return rc;
   104527         }
   104528       }
   104529     }
   104530     rc = sqlite3_reset(pSelect);
   104531   }else{
   104532     sqlite3_reset(pSelect);
   104533   }
   104534   return rc;
   104535 }
   104536 
   104537 /*
   104538 ** Forward declaration to account for the circular dependency between
   104539 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
   104540 */
   104541 static int fts3SegmentMerge(Fts3Table *, int);
   104542 
   104543 /*
   104544 ** This function allocates a new level iLevel index in the segdir table.
   104545 ** Usually, indexes are allocated within a level sequentially starting
   104546 ** with 0, so the allocated index is one greater than the value returned
   104547 ** by:
   104548 **
   104549 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
   104550 **
   104551 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
   104552 ** level, they are merged into a single level (iLevel+1) segment and the
   104553 ** allocated index is 0.
   104554 **
   104555 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
   104556 ** returned. Otherwise, an SQLite error code is returned.
   104557 */
   104558 static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
   104559   int rc;                         /* Return Code */
   104560   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
   104561   int iNext = 0;                  /* Result of query pNextIdx */
   104562 
   104563   /* Set variable iNext to the next available segdir index at level iLevel. */
   104564   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
   104565   if( rc==SQLITE_OK ){
   104566     sqlite3_bind_int(pNextIdx, 1, iLevel);
   104567     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
   104568       iNext = sqlite3_column_int(pNextIdx, 0);
   104569     }
   104570     rc = sqlite3_reset(pNextIdx);
   104571   }
   104572 
   104573   if( rc==SQLITE_OK ){
   104574     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
   104575     ** full, merge all segments in level iLevel into a single iLevel+1
   104576     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
   104577     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
   104578     */
   104579     if( iNext>=FTS3_MERGE_COUNT ){
   104580       rc = fts3SegmentMerge(p, iLevel);
   104581       *piIdx = 0;
   104582     }else{
   104583       *piIdx = iNext;
   104584     }
   104585   }
   104586 
   104587   return rc;
   104588 }
   104589 
   104590 /*
   104591 ** Move the iterator passed as the first argument to the next term in the
   104592 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
   104593 ** SQLITE_DONE. Otherwise, an SQLite error code.
   104594 */
   104595 static int fts3SegReaderNext(Fts3SegReader *pReader){
   104596   char *pNext;                    /* Cursor variable */
   104597   int nPrefix;                    /* Number of bytes in term prefix */
   104598   int nSuffix;                    /* Number of bytes in term suffix */
   104599 
   104600   if( !pReader->aDoclist ){
   104601     pNext = pReader->aNode;
   104602   }else{
   104603     pNext = &pReader->aDoclist[pReader->nDoclist];
   104604   }
   104605 
   104606   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
   104607     int rc;
   104608     if( fts3SegReaderIsPending(pReader) ){
   104609       Fts3HashElem *pElem = *(pReader->ppNextElem);
   104610       if( pElem==0 ){
   104611         pReader->aNode = 0;
   104612       }else{
   104613         PendingList *pList = (PendingList *)fts3HashData(pElem);
   104614         pReader->zTerm = (char *)fts3HashKey(pElem);
   104615         pReader->nTerm = fts3HashKeysize(pElem);
   104616         pReader->nNode = pReader->nDoclist = pList->nData + 1;
   104617         pReader->aNode = pReader->aDoclist = pList->aData;
   104618         pReader->ppNextElem++;
   104619         assert( pReader->aNode );
   104620       }
   104621       return SQLITE_OK;
   104622     }
   104623     if( !pReader->pStmt ){
   104624       pReader->aNode = 0;
   104625       return SQLITE_OK;
   104626     }
   104627     rc = sqlite3_step(pReader->pStmt);
   104628     if( rc!=SQLITE_ROW ){
   104629       pReader->aNode = 0;
   104630       return (rc==SQLITE_DONE ? SQLITE_OK : rc);
   104631     }
   104632     pReader->nNode = sqlite3_column_bytes(pReader->pStmt, 0);
   104633     pReader->aNode = (char *)sqlite3_column_blob(pReader->pStmt, 0);
   104634     pNext = pReader->aNode;
   104635   }
   104636 
   104637   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
   104638   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
   104639 
   104640   if( nPrefix+nSuffix>pReader->nTermAlloc ){
   104641     int nNew = (nPrefix+nSuffix)*2;
   104642     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
   104643     if( !zNew ){
   104644       return SQLITE_NOMEM;
   104645     }
   104646     pReader->zTerm = zNew;
   104647     pReader->nTermAlloc = nNew;
   104648   }
   104649   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
   104650   pReader->nTerm = nPrefix+nSuffix;
   104651   pNext += nSuffix;
   104652   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
   104653   assert( pNext<&pReader->aNode[pReader->nNode] );
   104654   pReader->aDoclist = pNext;
   104655   pReader->pOffsetList = 0;
   104656   return SQLITE_OK;
   104657 }
   104658 
   104659 /*
   104660 ** Set the SegReader to point to the first docid in the doclist associated
   104661 ** with the current term.
   104662 */
   104663 static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
   104664   int n;
   104665   assert( pReader->aDoclist );
   104666   assert( !pReader->pOffsetList );
   104667   n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
   104668   pReader->pOffsetList = &pReader->aDoclist[n];
   104669 }
   104670 
   104671 /*
   104672 ** Advance the SegReader to point to the next docid in the doclist
   104673 ** associated with the current term.
   104674 **
   104675 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
   104676 ** *ppOffsetList is set to point to the first column-offset list
   104677 ** in the doclist entry (i.e. immediately past the docid varint).
   104678 ** *pnOffsetList is set to the length of the set of column-offset
   104679 ** lists, not including the nul-terminator byte. For example:
   104680 */
   104681 static void fts3SegReaderNextDocid(
   104682   Fts3SegReader *pReader,
   104683   char **ppOffsetList,
   104684   int *pnOffsetList
   104685 ){
   104686   char *p = pReader->pOffsetList;
   104687   char c = 0;
   104688 
   104689   /* Pointer p currently points at the first byte of an offset list. The
   104690   ** following two lines advance it to point one byte past the end of
   104691   ** the same offset list.
   104692   */
   104693   while( *p | c ) c = *p++ & 0x80;
   104694   p++;
   104695 
   104696   /* If required, populate the output variables with a pointer to and the
   104697   ** size of the previous offset-list.
   104698   */
   104699   if( ppOffsetList ){
   104700     *ppOffsetList = pReader->pOffsetList;
   104701     *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
   104702   }
   104703 
   104704   /* If there are no more entries in the doclist, set pOffsetList to
   104705   ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
   104706   ** Fts3SegReader.pOffsetList to point to the next offset list before
   104707   ** returning.
   104708   */
   104709   if( p>=&pReader->aDoclist[pReader->nDoclist] ){
   104710     pReader->pOffsetList = 0;
   104711   }else{
   104712     sqlite3_int64 iDelta;
   104713     pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
   104714     pReader->iDocid += iDelta;
   104715   }
   104716 }
   104717 
   104718 /*
   104719 ** Free all allocations associated with the iterator passed as the
   104720 ** second argument.
   104721 */
   104722 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *p, Fts3SegReader *pReader){
   104723   if( pReader ){
   104724     if( pReader->pStmt ){
   104725       /* Move the leaf-range SELECT statement to the aLeavesStmt[] array,
   104726       ** so that it can be reused when required by another query.
   104727       */
   104728       assert( p->nLeavesStmt<p->nLeavesTotal );
   104729       sqlite3_reset(pReader->pStmt);
   104730       p->aLeavesStmt[p->nLeavesStmt++] = pReader->pStmt;
   104731     }
   104732     if( !fts3SegReaderIsPending(pReader) ){
   104733       sqlite3_free(pReader->zTerm);
   104734     }
   104735     sqlite3_free(pReader);
   104736   }
   104737 }
   104738 
   104739 /*
   104740 ** Allocate a new SegReader object.
   104741 */
   104742 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
   104743   Fts3Table *p,                   /* Virtual table handle */
   104744   int iAge,                       /* Segment "age". */
   104745   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
   104746   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
   104747   sqlite3_int64 iEndBlock,        /* Final block of segment */
   104748   const char *zRoot,              /* Buffer containing root node */
   104749   int nRoot,                      /* Size of buffer containing root node */
   104750   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
   104751 ){
   104752   int rc = SQLITE_OK;             /* Return code */
   104753   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
   104754   int nExtra = 0;                 /* Bytes to allocate segment root node */
   104755 
   104756   if( iStartLeaf==0 ){
   104757     nExtra = nRoot;
   104758   }
   104759 
   104760   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
   104761   if( !pReader ){
   104762     return SQLITE_NOMEM;
   104763   }
   104764   memset(pReader, 0, sizeof(Fts3SegReader));
   104765   pReader->iStartBlock = iStartLeaf;
   104766   pReader->iIdx = iAge;
   104767   pReader->iEndBlock = iEndBlock;
   104768 
   104769   if( nExtra ){
   104770     /* The entire segment is stored in the root node. */
   104771     pReader->aNode = (char *)&pReader[1];
   104772     pReader->nNode = nRoot;
   104773     memcpy(pReader->aNode, zRoot, nRoot);
   104774   }else{
   104775     /* If the text of the SQL statement to iterate through a contiguous
   104776     ** set of entries in the %_segments table has not yet been composed,
   104777     ** compose it now.
   104778     */
   104779     if( !p->zSelectLeaves ){
   104780       p->zSelectLeaves = sqlite3_mprintf(
   104781           "SELECT block FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ? "
   104782           "ORDER BY blockid", p->zDb, p->zName
   104783       );
   104784       if( !p->zSelectLeaves ){
   104785         rc = SQLITE_NOMEM;
   104786         goto finished;
   104787       }
   104788     }
   104789 
   104790     /* If there are no free statements in the aLeavesStmt[] array, prepare
   104791     ** a new statement now. Otherwise, reuse a prepared statement from
   104792     ** aLeavesStmt[].
   104793     */
   104794     if( p->nLeavesStmt==0 ){
   104795       if( p->nLeavesTotal==p->nLeavesAlloc ){
   104796         int nNew = p->nLeavesAlloc + 16;
   104797         sqlite3_stmt **aNew = (sqlite3_stmt **)sqlite3_realloc(
   104798             p->aLeavesStmt, nNew*sizeof(sqlite3_stmt *)
   104799         );
   104800         if( !aNew ){
   104801           rc = SQLITE_NOMEM;
   104802           goto finished;
   104803         }
   104804         p->nLeavesAlloc = nNew;
   104805         p->aLeavesStmt = aNew;
   104806       }
   104807       rc = sqlite3_prepare_v2(p->db, p->zSelectLeaves, -1, &pReader->pStmt, 0);
   104808       if( rc!=SQLITE_OK ){
   104809         goto finished;
   104810       }
   104811       p->nLeavesTotal++;
   104812     }else{
   104813       pReader->pStmt = p->aLeavesStmt[--p->nLeavesStmt];
   104814     }
   104815 
   104816     /* Bind the start and end leaf blockids to the prepared SQL statement. */
   104817     sqlite3_bind_int64(pReader->pStmt, 1, iStartLeaf);
   104818     sqlite3_bind_int64(pReader->pStmt, 2, iEndLeaf);
   104819   }
   104820   rc = fts3SegReaderNext(pReader);
   104821 
   104822  finished:
   104823   if( rc==SQLITE_OK ){
   104824     *ppReader = pReader;
   104825   }else{
   104826     sqlite3Fts3SegReaderFree(p, pReader);
   104827   }
   104828   return rc;
   104829 }
   104830 
   104831 /*
   104832 ** This is a comparison function used as a qsort() callback when sorting
   104833 ** an array of pending terms by term. This occurs as part of flushing
   104834 ** the contents of the pending-terms hash table to the database.
   104835 */
   104836 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
   104837   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
   104838   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
   104839   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
   104840   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
   104841 
   104842   int n = (n1<n2 ? n1 : n2);
   104843   int c = memcmp(z1, z2, n);
   104844   if( c==0 ){
   104845     c = n1 - n2;
   104846   }
   104847   return c;
   104848 }
   104849 
   104850 /*
   104851 ** This function is used to allocate an Fts3SegReader that iterates through
   104852 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
   104853 */
   104854 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
   104855   Fts3Table *p,                   /* Virtual table handle */
   104856   const char *zTerm,              /* Term to search for */
   104857   int nTerm,                      /* Size of buffer zTerm */
   104858   int isPrefix,                   /* True for a term-prefix query */
   104859   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
   104860 ){
   104861   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
   104862   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
   104863   int nElem = 0;                  /* Size of array at aElem */
   104864   int rc = SQLITE_OK;             /* Return Code */
   104865 
   104866   if( isPrefix ){
   104867     int nAlloc = 0;               /* Size of allocated array at aElem */
   104868     Fts3HashElem *pE = 0;         /* Iterator variable */
   104869 
   104870     for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
   104871       char *zKey = (char *)fts3HashKey(pE);
   104872       int nKey = fts3HashKeysize(pE);
   104873       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
   104874         if( nElem==nAlloc ){
   104875           Fts3HashElem **aElem2;
   104876           nAlloc += 16;
   104877           aElem2 = (Fts3HashElem **)sqlite3_realloc(
   104878               aElem, nAlloc*sizeof(Fts3HashElem *)
   104879           );
   104880           if( !aElem2 ){
   104881             rc = SQLITE_NOMEM;
   104882             nElem = 0;
   104883             break;
   104884           }
   104885           aElem = aElem2;
   104886         }
   104887         aElem[nElem++] = pE;
   104888       }
   104889     }
   104890 
   104891     /* If more than one term matches the prefix, sort the Fts3HashElem
   104892     ** objects in term order using qsort(). This uses the same comparison
   104893     ** callback as is used when flushing terms to disk.
   104894     */
   104895     if( nElem>1 ){
   104896       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
   104897     }
   104898 
   104899   }else{
   104900     Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
   104901     if( pE ){
   104902       aElem = &pE;
   104903       nElem = 1;
   104904     }
   104905   }
   104906 
   104907   if( nElem>0 ){
   104908     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
   104909     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
   104910     if( !pReader ){
   104911       rc = SQLITE_NOMEM;
   104912     }else{
   104913       memset(pReader, 0, nByte);
   104914       pReader->iIdx = 0x7FFFFFFF;
   104915       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
   104916       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
   104917       fts3SegReaderNext(pReader);
   104918     }
   104919   }
   104920 
   104921   if( isPrefix ){
   104922     sqlite3_free(aElem);
   104923   }
   104924   *ppReader = pReader;
   104925   return rc;
   104926 }
   104927 
   104928 
   104929 /*
   104930 ** The second argument to this function is expected to be a statement of
   104931 ** the form:
   104932 **
   104933 **   SELECT
   104934 **     idx,                  -- col 0
   104935 **     start_block,          -- col 1
   104936 **     leaves_end_block,     -- col 2
   104937 **     end_block,            -- col 3
   104938 **     root                  -- col 4
   104939 **   FROM %_segdir ...
   104940 **
   104941 ** This function allocates and initializes a Fts3SegReader structure to
   104942 ** iterate through the terms stored in the segment identified by the
   104943 ** current row that pStmt is pointing to.
   104944 **
   104945 ** If successful, the Fts3SegReader is left pointing to the first term
   104946 ** in the segment and SQLITE_OK is returned. Otherwise, an SQLite error
   104947 ** code is returned.
   104948 */
   104949 static int fts3SegReaderNew(
   104950   Fts3Table *p,                   /* Virtual table handle */
   104951   sqlite3_stmt *pStmt,            /* See above */
   104952   int iAge,                       /* Segment "age". */
   104953   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
   104954 ){
   104955   return sqlite3Fts3SegReaderNew(p, iAge,
   104956       sqlite3_column_int64(pStmt, 1),
   104957       sqlite3_column_int64(pStmt, 2),
   104958       sqlite3_column_int64(pStmt, 3),
   104959       sqlite3_column_blob(pStmt, 4),
   104960       sqlite3_column_bytes(pStmt, 4),
   104961       ppReader
   104962   );
   104963 }
   104964 
   104965 /*
   104966 ** Compare the entries pointed to by two Fts3SegReader structures.
   104967 ** Comparison is as follows:
   104968 **
   104969 **   1) EOF is greater than not EOF.
   104970 **
   104971 **   2) The current terms (if any) are compared using memcmp(). If one
   104972 **      term is a prefix of another, the longer term is considered the
   104973 **      larger.
   104974 **
   104975 **   3) By segment age. An older segment is considered larger.
   104976 */
   104977 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   104978   int rc;
   104979   if( pLhs->aNode && pRhs->aNode ){
   104980     int rc2 = pLhs->nTerm - pRhs->nTerm;
   104981     if( rc2<0 ){
   104982       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
   104983     }else{
   104984       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
   104985     }
   104986     if( rc==0 ){
   104987       rc = rc2;
   104988     }
   104989   }else{
   104990     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
   104991   }
   104992   if( rc==0 ){
   104993     rc = pRhs->iIdx - pLhs->iIdx;
   104994   }
   104995   assert( rc!=0 );
   104996   return rc;
   104997 }
   104998 
   104999 /*
   105000 ** A different comparison function for SegReader structures. In this
   105001 ** version, it is assumed that each SegReader points to an entry in
   105002 ** a doclist for identical terms. Comparison is made as follows:
   105003 **
   105004 **   1) EOF (end of doclist in this case) is greater than not EOF.
   105005 **
   105006 **   2) By current docid.
   105007 **
   105008 **   3) By segment age. An older segment is considered larger.
   105009 */
   105010 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   105011   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
   105012   if( rc==0 ){
   105013     if( pLhs->iDocid==pRhs->iDocid ){
   105014       rc = pRhs->iIdx - pLhs->iIdx;
   105015     }else{
   105016       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
   105017     }
   105018   }
   105019   assert( pLhs->aNode && pRhs->aNode );
   105020   return rc;
   105021 }
   105022 
   105023 /*
   105024 ** Compare the term that the Fts3SegReader object passed as the first argument
   105025 ** points to with the term specified by arguments zTerm and nTerm.
   105026 **
   105027 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
   105028 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
   105029 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
   105030 */
   105031 static int fts3SegReaderTermCmp(
   105032   Fts3SegReader *pSeg,            /* Segment reader object */
   105033   const char *zTerm,              /* Term to compare to */
   105034   int nTerm                       /* Size of term zTerm in bytes */
   105035 ){
   105036   int res = 0;
   105037   if( pSeg->aNode ){
   105038     if( pSeg->nTerm>nTerm ){
   105039       res = memcmp(pSeg->zTerm, zTerm, nTerm);
   105040     }else{
   105041       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
   105042     }
   105043     if( res==0 ){
   105044       res = pSeg->nTerm-nTerm;
   105045     }
   105046   }
   105047   return res;
   105048 }
   105049 
   105050 /*
   105051 ** Argument apSegment is an array of nSegment elements. It is known that
   105052 ** the final (nSegment-nSuspect) members are already in sorted order
   105053 ** (according to the comparison function provided). This function shuffles
   105054 ** the array around until all entries are in sorted order.
   105055 */
   105056 static void fts3SegReaderSort(
   105057   Fts3SegReader **apSegment,                     /* Array to sort entries of */
   105058   int nSegment,                                  /* Size of apSegment array */
   105059   int nSuspect,                                  /* Unsorted entry count */
   105060   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
   105061 ){
   105062   int i;                          /* Iterator variable */
   105063 
   105064   assert( nSuspect<=nSegment );
   105065 
   105066   if( nSuspect==nSegment ) nSuspect--;
   105067   for(i=nSuspect-1; i>=0; i--){
   105068     int j;
   105069     for(j=i; j<(nSegment-1); j++){
   105070       Fts3SegReader *pTmp;
   105071       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
   105072       pTmp = apSegment[j+1];
   105073       apSegment[j+1] = apSegment[j];
   105074       apSegment[j] = pTmp;
   105075     }
   105076   }
   105077 
   105078 #ifndef NDEBUG
   105079   /* Check that the list really is sorted now. */
   105080   for(i=0; i<(nSuspect-1); i++){
   105081     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
   105082   }
   105083 #endif
   105084 }
   105085 
   105086 /*
   105087 ** Insert a record into the %_segments table.
   105088 */
   105089 static int fts3WriteSegment(
   105090   Fts3Table *p,                   /* Virtual table handle */
   105091   sqlite3_int64 iBlock,           /* Block id for new block */
   105092   char *z,                        /* Pointer to buffer containing block data */
   105093   int n                           /* Size of buffer z in bytes */
   105094 ){
   105095   sqlite3_stmt *pStmt;
   105096   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
   105097   if( rc==SQLITE_OK ){
   105098     sqlite3_bind_int64(pStmt, 1, iBlock);
   105099     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
   105100     sqlite3_step(pStmt);
   105101     rc = sqlite3_reset(pStmt);
   105102   }
   105103   return rc;
   105104 }
   105105 
   105106 /*
   105107 ** Insert a record into the %_segdir table.
   105108 */
   105109 static int fts3WriteSegdir(
   105110   Fts3Table *p,                   /* Virtual table handle */
   105111   int iLevel,                     /* Value for "level" field */
   105112   int iIdx,                       /* Value for "idx" field */
   105113   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
   105114   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
   105115   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
   105116   char *zRoot,                    /* Blob value for "root" field */
   105117   int nRoot                       /* Number of bytes in buffer zRoot */
   105118 ){
   105119   sqlite3_stmt *pStmt;
   105120   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
   105121   if( rc==SQLITE_OK ){
   105122     sqlite3_bind_int(pStmt, 1, iLevel);
   105123     sqlite3_bind_int(pStmt, 2, iIdx);
   105124     sqlite3_bind_int64(pStmt, 3, iStartBlock);
   105125     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
   105126     sqlite3_bind_int64(pStmt, 5, iEndBlock);
   105127     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
   105128     sqlite3_step(pStmt);
   105129     rc = sqlite3_reset(pStmt);
   105130   }
   105131   return rc;
   105132 }
   105133 
   105134 /*
   105135 ** Return the size of the common prefix (if any) shared by zPrev and
   105136 ** zNext, in bytes. For example,
   105137 **
   105138 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
   105139 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
   105140 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
   105141 */
   105142 static int fts3PrefixCompress(
   105143   const char *zPrev,              /* Buffer containing previous term */
   105144   int nPrev,                      /* Size of buffer zPrev in bytes */
   105145   const char *zNext,              /* Buffer containing next term */
   105146   int nNext                       /* Size of buffer zNext in bytes */
   105147 ){
   105148   int n;
   105149   UNUSED_PARAMETER(nNext);
   105150   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
   105151   return n;
   105152 }
   105153 
   105154 /*
   105155 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
   105156 ** (according to memcmp) than the previous term.
   105157 */
   105158 static int fts3NodeAddTerm(
   105159   Fts3Table *p,               /* Virtual table handle */
   105160   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
   105161   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
   105162   const char *zTerm,              /* Pointer to buffer containing term */
   105163   int nTerm                       /* Size of term in bytes */
   105164 ){
   105165   SegmentNode *pTree = *ppTree;
   105166   int rc;
   105167   SegmentNode *pNew;
   105168 
   105169   /* First try to append the term to the current node. Return early if
   105170   ** this is possible.
   105171   */
   105172   if( pTree ){
   105173     int nData = pTree->nData;     /* Current size of node in bytes */
   105174     int nReq = nData;             /* Required space after adding zTerm */
   105175     int nPrefix;                  /* Number of bytes of prefix compression */
   105176     int nSuffix;                  /* Suffix length */
   105177 
   105178     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
   105179     nSuffix = nTerm-nPrefix;
   105180 
   105181     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
   105182     if( nReq<=p->nNodeSize || !pTree->zTerm ){
   105183 
   105184       if( nReq>p->nNodeSize ){
   105185         /* An unusual case: this is the first term to be added to the node
   105186         ** and the static node buffer (p->nNodeSize bytes) is not large
   105187         ** enough. Use a separately malloced buffer instead This wastes
   105188         ** p->nNodeSize bytes, but since this scenario only comes about when
   105189         ** the database contain two terms that share a prefix of almost 2KB,
   105190         ** this is not expected to be a serious problem.
   105191         */
   105192         assert( pTree->aData==(char *)&pTree[1] );
   105193         pTree->aData = (char *)sqlite3_malloc(nReq);
   105194         if( !pTree->aData ){
   105195           return SQLITE_NOMEM;
   105196         }
   105197       }
   105198 
   105199       if( pTree->zTerm ){
   105200         /* There is no prefix-length field for first term in a node */
   105201         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
   105202       }
   105203 
   105204       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
   105205       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
   105206       pTree->nData = nData + nSuffix;
   105207       pTree->nEntry++;
   105208 
   105209       if( isCopyTerm ){
   105210         if( pTree->nMalloc<nTerm ){
   105211           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
   105212           if( !zNew ){
   105213             return SQLITE_NOMEM;
   105214           }
   105215           pTree->nMalloc = nTerm*2;
   105216           pTree->zMalloc = zNew;
   105217         }
   105218         pTree->zTerm = pTree->zMalloc;
   105219         memcpy(pTree->zTerm, zTerm, nTerm);
   105220         pTree->nTerm = nTerm;
   105221       }else{
   105222         pTree->zTerm = (char *)zTerm;
   105223         pTree->nTerm = nTerm;
   105224       }
   105225       return SQLITE_OK;
   105226     }
   105227   }
   105228 
   105229   /* If control flows to here, it was not possible to append zTerm to the
   105230   ** current node. Create a new node (a right-sibling of the current node).
   105231   ** If this is the first node in the tree, the term is added to it.
   105232   **
   105233   ** Otherwise, the term is not added to the new node, it is left empty for
   105234   ** now. Instead, the term is inserted into the parent of pTree. If pTree
   105235   ** has no parent, one is created here.
   105236   */
   105237   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
   105238   if( !pNew ){
   105239     return SQLITE_NOMEM;
   105240   }
   105241   memset(pNew, 0, sizeof(SegmentNode));
   105242   pNew->nData = 1 + FTS3_VARINT_MAX;
   105243   pNew->aData = (char *)&pNew[1];
   105244 
   105245   if( pTree ){
   105246     SegmentNode *pParent = pTree->pParent;
   105247     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
   105248     if( pTree->pParent==0 ){
   105249       pTree->pParent = pParent;
   105250     }
   105251     pTree->pRight = pNew;
   105252     pNew->pLeftmost = pTree->pLeftmost;
   105253     pNew->pParent = pParent;
   105254     pNew->zMalloc = pTree->zMalloc;
   105255     pNew->nMalloc = pTree->nMalloc;
   105256     pTree->zMalloc = 0;
   105257   }else{
   105258     pNew->pLeftmost = pNew;
   105259     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
   105260   }
   105261 
   105262   *ppTree = pNew;
   105263   return rc;
   105264 }
   105265 
   105266 /*
   105267 ** Helper function for fts3NodeWrite().
   105268 */
   105269 static int fts3TreeFinishNode(
   105270   SegmentNode *pTree,
   105271   int iHeight,
   105272   sqlite3_int64 iLeftChild
   105273 ){
   105274   int nStart;
   105275   assert( iHeight>=1 && iHeight<128 );
   105276   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
   105277   pTree->aData[nStart] = (char)iHeight;
   105278   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
   105279   return nStart;
   105280 }
   105281 
   105282 /*
   105283 ** Write the buffer for the segment node pTree and all of its peers to the
   105284 ** database. Then call this function recursively to write the parent of
   105285 ** pTree and its peers to the database.
   105286 **
   105287 ** Except, if pTree is a root node, do not write it to the database. Instead,
   105288 ** set output variables *paRoot and *pnRoot to contain the root node.
   105289 **
   105290 ** If successful, SQLITE_OK is returned and output variable *piLast is
   105291 ** set to the largest blockid written to the database (or zero if no
   105292 ** blocks were written to the db). Otherwise, an SQLite error code is
   105293 ** returned.
   105294 */
   105295 static int fts3NodeWrite(
   105296   Fts3Table *p,                   /* Virtual table handle */
   105297   SegmentNode *pTree,             /* SegmentNode handle */
   105298   int iHeight,                    /* Height of this node in tree */
   105299   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
   105300   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
   105301   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
   105302   char **paRoot,                  /* OUT: Data for root node */
   105303   int *pnRoot                     /* OUT: Size of root node in bytes */
   105304 ){
   105305   int rc = SQLITE_OK;
   105306 
   105307   if( !pTree->pParent ){
   105308     /* Root node of the tree. */
   105309     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
   105310     *piLast = iFree-1;
   105311     *pnRoot = pTree->nData - nStart;
   105312     *paRoot = &pTree->aData[nStart];
   105313   }else{
   105314     SegmentNode *pIter;
   105315     sqlite3_int64 iNextFree = iFree;
   105316     sqlite3_int64 iNextLeaf = iLeaf;
   105317     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
   105318       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
   105319       int nWrite = pIter->nData - nStart;
   105320 
   105321       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
   105322       iNextFree++;
   105323       iNextLeaf += (pIter->nEntry+1);
   105324     }
   105325     if( rc==SQLITE_OK ){
   105326       assert( iNextLeaf==iFree );
   105327       rc = fts3NodeWrite(
   105328           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
   105329       );
   105330     }
   105331   }
   105332 
   105333   return rc;
   105334 }
   105335 
   105336 /*
   105337 ** Free all memory allocations associated with the tree pTree.
   105338 */
   105339 static void fts3NodeFree(SegmentNode *pTree){
   105340   if( pTree ){
   105341     SegmentNode *p = pTree->pLeftmost;
   105342     fts3NodeFree(p->pParent);
   105343     while( p ){
   105344       SegmentNode *pRight = p->pRight;
   105345       if( p->aData!=(char *)&p[1] ){
   105346         sqlite3_free(p->aData);
   105347       }
   105348       assert( pRight==0 || p->zMalloc==0 );
   105349       sqlite3_free(p->zMalloc);
   105350       sqlite3_free(p);
   105351       p = pRight;
   105352     }
   105353   }
   105354 }
   105355 
   105356 /*
   105357 ** Add a term to the segment being constructed by the SegmentWriter object
   105358 ** *ppWriter. When adding the first term to a segment, *ppWriter should
   105359 ** be passed NULL. This function will allocate a new SegmentWriter object
   105360 ** and return it via the input/output variable *ppWriter in this case.
   105361 **
   105362 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
   105363 */
   105364 static int fts3SegWriterAdd(
   105365   Fts3Table *p,                   /* Virtual table handle */
   105366   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
   105367   int isCopyTerm,                 /* True if buffer zTerm must be copied */
   105368   const char *zTerm,              /* Pointer to buffer containing term */
   105369   int nTerm,                      /* Size of term in bytes */
   105370   const char *aDoclist,           /* Pointer to buffer containing doclist */
   105371   int nDoclist                    /* Size of doclist in bytes */
   105372 ){
   105373   int nPrefix;                    /* Size of term prefix in bytes */
   105374   int nSuffix;                    /* Size of term suffix in bytes */
   105375   int nReq;                       /* Number of bytes required on leaf page */
   105376   int nData;
   105377   SegmentWriter *pWriter = *ppWriter;
   105378 
   105379   if( !pWriter ){
   105380     int rc;
   105381     sqlite3_stmt *pStmt;
   105382 
   105383     /* Allocate the SegmentWriter structure */
   105384     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
   105385     if( !pWriter ) return SQLITE_NOMEM;
   105386     memset(pWriter, 0, sizeof(SegmentWriter));
   105387     *ppWriter = pWriter;
   105388 
   105389     /* Allocate a buffer in which to accumulate data */
   105390     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
   105391     if( !pWriter->aData ) return SQLITE_NOMEM;
   105392     pWriter->nSize = p->nNodeSize;
   105393 
   105394     /* Find the next free blockid in the %_segments table */
   105395     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
   105396     if( rc!=SQLITE_OK ) return rc;
   105397     if( SQLITE_ROW==sqlite3_step(pStmt) ){
   105398       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
   105399       pWriter->iFirst = pWriter->iFree;
   105400     }
   105401     rc = sqlite3_reset(pStmt);
   105402     if( rc!=SQLITE_OK ) return rc;
   105403   }
   105404   nData = pWriter->nData;
   105405 
   105406   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
   105407   nSuffix = nTerm-nPrefix;
   105408 
   105409   /* Figure out how many bytes are required by this new entry */
   105410   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
   105411     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
   105412     nSuffix +                               /* Term suffix */
   105413     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
   105414     nDoclist;                               /* Doclist data */
   105415 
   105416   if( nData>0 && nData+nReq>p->nNodeSize ){
   105417     int rc;
   105418 
   105419     /* The current leaf node is full. Write it out to the database. */
   105420     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
   105421     if( rc!=SQLITE_OK ) return rc;
   105422 
   105423     /* Add the current term to the interior node tree. The term added to
   105424     ** the interior tree must:
   105425     **
   105426     **   a) be greater than the largest term on the leaf node just written
   105427     **      to the database (still available in pWriter->zTerm), and
   105428     **
   105429     **   b) be less than or equal to the term about to be added to the new
   105430     **      leaf node (zTerm/nTerm).
   105431     **
   105432     ** In other words, it must be the prefix of zTerm 1 byte longer than
   105433     ** the common prefix (if any) of zTerm and pWriter->zTerm.
   105434     */
   105435     assert( nPrefix<nTerm );
   105436     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
   105437     if( rc!=SQLITE_OK ) return rc;
   105438 
   105439     nData = 0;
   105440     pWriter->nTerm = 0;
   105441 
   105442     nPrefix = 0;
   105443     nSuffix = nTerm;
   105444     nReq = 1 +                              /* varint containing prefix size */
   105445       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
   105446       nTerm +                               /* Term suffix */
   105447       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
   105448       nDoclist;                             /* Doclist data */
   105449   }
   105450 
   105451   /* If the buffer currently allocated is too small for this entry, realloc
   105452   ** the buffer to make it large enough.
   105453   */
   105454   if( nReq>pWriter->nSize ){
   105455     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
   105456     if( !aNew ) return SQLITE_NOMEM;
   105457     pWriter->aData = aNew;
   105458     pWriter->nSize = nReq;
   105459   }
   105460   assert( nData+nReq<=pWriter->nSize );
   105461 
   105462   /* Append the prefix-compressed term and doclist to the buffer. */
   105463   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
   105464   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
   105465   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
   105466   nData += nSuffix;
   105467   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
   105468   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
   105469   pWriter->nData = nData + nDoclist;
   105470 
   105471   /* Save the current term so that it can be used to prefix-compress the next.
   105472   ** If the isCopyTerm parameter is true, then the buffer pointed to by
   105473   ** zTerm is transient, so take a copy of the term data. Otherwise, just
   105474   ** store a copy of the pointer.
   105475   */
   105476   if( isCopyTerm ){
   105477     if( nTerm>pWriter->nMalloc ){
   105478       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
   105479       if( !zNew ){
   105480         return SQLITE_NOMEM;
   105481       }
   105482       pWriter->nMalloc = nTerm*2;
   105483       pWriter->zMalloc = zNew;
   105484       pWriter->zTerm = zNew;
   105485     }
   105486     assert( pWriter->zTerm==pWriter->zMalloc );
   105487     memcpy(pWriter->zTerm, zTerm, nTerm);
   105488   }else{
   105489     pWriter->zTerm = (char *)zTerm;
   105490   }
   105491   pWriter->nTerm = nTerm;
   105492 
   105493   return SQLITE_OK;
   105494 }
   105495 
   105496 /*
   105497 ** Flush all data associated with the SegmentWriter object pWriter to the
   105498 ** database. This function must be called after all terms have been added
   105499 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
   105500 ** returned. Otherwise, an SQLite error code.
   105501 */
   105502 static int fts3SegWriterFlush(
   105503   Fts3Table *p,                   /* Virtual table handle */
   105504   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
   105505   int iLevel,                     /* Value for 'level' column of %_segdir */
   105506   int iIdx                        /* Value for 'idx' column of %_segdir */
   105507 ){
   105508   int rc;                         /* Return code */
   105509   if( pWriter->pTree ){
   105510     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
   105511     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
   105512     char *zRoot = NULL;           /* Pointer to buffer containing root node */
   105513     int nRoot = 0;                /* Size of buffer zRoot */
   105514 
   105515     iLastLeaf = pWriter->iFree;
   105516     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
   105517     if( rc==SQLITE_OK ){
   105518       rc = fts3NodeWrite(p, pWriter->pTree, 1,
   105519           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
   105520     }
   105521     if( rc==SQLITE_OK ){
   105522       rc = fts3WriteSegdir(
   105523           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
   105524     }
   105525   }else{
   105526     /* The entire tree fits on the root node. Write it to the segdir table. */
   105527     rc = fts3WriteSegdir(
   105528         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
   105529   }
   105530   return rc;
   105531 }
   105532 
   105533 /*
   105534 ** Release all memory held by the SegmentWriter object passed as the
   105535 ** first argument.
   105536 */
   105537 static void fts3SegWriterFree(SegmentWriter *pWriter){
   105538   if( pWriter ){
   105539     sqlite3_free(pWriter->aData);
   105540     sqlite3_free(pWriter->zMalloc);
   105541     fts3NodeFree(pWriter->pTree);
   105542     sqlite3_free(pWriter);
   105543   }
   105544 }
   105545 
   105546 /*
   105547 ** The first value in the apVal[] array is assumed to contain an integer.
   105548 ** This function tests if there exist any documents with docid values that
   105549 ** are different from that integer. i.e. if deleting the document with docid
   105550 ** apVal[0] would mean the FTS3 table were empty.
   105551 **
   105552 ** If successful, *pisEmpty is set to true if the table is empty except for
   105553 ** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
   105554 ** error occurs, an SQLite error code is returned.
   105555 */
   105556 static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
   105557   sqlite3_stmt *pStmt;
   105558   int rc;
   105559   rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
   105560   if( rc==SQLITE_OK ){
   105561     if( SQLITE_ROW==sqlite3_step(pStmt) ){
   105562       *pisEmpty = sqlite3_column_int(pStmt, 0);
   105563     }
   105564     rc = sqlite3_reset(pStmt);
   105565   }
   105566   return rc;
   105567 }
   105568 
   105569 /*
   105570 ** Set *pnSegment to the number of segments of level iLevel in the database.
   105571 **
   105572 ** Return SQLITE_OK if successful, or an SQLite error code if not.
   105573 */
   105574 static int fts3SegmentCount(Fts3Table *p, int iLevel, int *pnSegment){
   105575   sqlite3_stmt *pStmt;
   105576   int rc;
   105577 
   105578   assert( iLevel>=0 );
   105579   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_COUNT, &pStmt, 0);
   105580   if( rc!=SQLITE_OK ) return rc;
   105581   sqlite3_bind_int(pStmt, 1, iLevel);
   105582   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   105583     *pnSegment = sqlite3_column_int(pStmt, 0);
   105584   }
   105585   return sqlite3_reset(pStmt);
   105586 }
   105587 
   105588 /*
   105589 ** Set *pnSegment to the total number of segments in the database. Set
   105590 ** *pnMax to the largest segment level in the database (segment levels
   105591 ** are stored in the 'level' column of the %_segdir table).
   105592 **
   105593 ** Return SQLITE_OK if successful, or an SQLite error code if not.
   105594 */
   105595 static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
   105596   sqlite3_stmt *pStmt;
   105597   int rc;
   105598 
   105599   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
   105600   if( rc!=SQLITE_OK ) return rc;
   105601   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   105602     *pnSegment = sqlite3_column_int(pStmt, 0);
   105603     *pnMax = sqlite3_column_int(pStmt, 1);
   105604   }
   105605   return sqlite3_reset(pStmt);
   105606 }
   105607 
   105608 /*
   105609 ** This function is used after merging multiple segments into a single large
   105610 ** segment to delete the old, now redundant, segment b-trees. Specifically,
   105611 ** it:
   105612 **
   105613 **   1) Deletes all %_segments entries for the segments associated with
   105614 **      each of the SegReader objects in the array passed as the third
   105615 **      argument, and
   105616 **
   105617 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
   105618 **      entries regardless of level if (iLevel<0).
   105619 **
   105620 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
   105621 */
   105622 static int fts3DeleteSegdir(
   105623   Fts3Table *p,                   /* Virtual table handle */
   105624   int iLevel,                     /* Level of %_segdir entries to delete */
   105625   Fts3SegReader **apSegment,      /* Array of SegReader objects */
   105626   int nReader                     /* Size of array apSegment */
   105627 ){
   105628   int rc;                         /* Return Code */
   105629   int i;                          /* Iterator variable */
   105630   sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
   105631 
   105632   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
   105633   for(i=0; rc==SQLITE_OK && i<nReader; i++){
   105634     Fts3SegReader *pSegment = apSegment[i];
   105635     if( pSegment->iStartBlock ){
   105636       sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
   105637       sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
   105638       sqlite3_step(pDelete);
   105639       rc = sqlite3_reset(pDelete);
   105640     }
   105641   }
   105642   if( rc!=SQLITE_OK ){
   105643     return rc;
   105644   }
   105645 
   105646   if( iLevel>=0 ){
   105647     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
   105648     if( rc==SQLITE_OK ){
   105649       sqlite3_bind_int(pDelete, 1, iLevel);
   105650       sqlite3_step(pDelete);
   105651       rc = sqlite3_reset(pDelete);
   105652     }
   105653   }else{
   105654     rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGDIR, 0);
   105655   }
   105656 
   105657   return rc;
   105658 }
   105659 
   105660 /*
   105661 ** When this function is called, buffer *ppList (size *pnList bytes) contains
   105662 ** a position list that may (or may not) feature multiple columns. This
   105663 ** function adjusts the pointer *ppList and the length *pnList so that they
   105664 ** identify the subset of the position list that corresponds to column iCol.
   105665 **
   105666 ** If there are no entries in the input position list for column iCol, then
   105667 ** *pnList is set to zero before returning.
   105668 */
   105669 static void fts3ColumnFilter(
   105670   int iCol,                       /* Column to filter on */
   105671   char **ppList,                  /* IN/OUT: Pointer to position list */
   105672   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
   105673 ){
   105674   char *pList = *ppList;
   105675   int nList = *pnList;
   105676   char *pEnd = &pList[nList];
   105677   int iCurrent = 0;
   105678   char *p = pList;
   105679 
   105680   assert( iCol>=0 );
   105681   while( 1 ){
   105682     char c = 0;
   105683     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
   105684 
   105685     if( iCol==iCurrent ){
   105686       nList = (int)(p - pList);
   105687       break;
   105688     }
   105689 
   105690     nList -= (int)(p - pList);
   105691     pList = p;
   105692     if( nList==0 ){
   105693       break;
   105694     }
   105695     p = &pList[1];
   105696     p += sqlite3Fts3GetVarint32(p, &iCurrent);
   105697   }
   105698 
   105699   *ppList = pList;
   105700   *pnList = nList;
   105701 }
   105702 
   105703 /*
   105704 ** sqlite3Fts3SegReaderIterate() callback used when merging multiple
   105705 ** segments to create a single, larger segment.
   105706 */
   105707 static int fts3MergeCallback(
   105708   Fts3Table *p,                   /* FTS3 Virtual table handle */
   105709   void *pContext,                 /* Pointer to SegmentWriter* to write with */
   105710   char *zTerm,                    /* Term to write to the db */
   105711   int nTerm,                      /* Number of bytes in zTerm */
   105712   char *aDoclist,                 /* Doclist associated with zTerm */
   105713   int nDoclist                    /* Number of bytes in doclist */
   105714 ){
   105715   SegmentWriter **ppW = (SegmentWriter **)pContext;
   105716   return fts3SegWriterAdd(p, ppW, 1, zTerm, nTerm, aDoclist, nDoclist);
   105717 }
   105718 
   105719 /*
   105720 ** sqlite3Fts3SegReaderIterate() callback used when flushing the contents
   105721 ** of the pending-terms hash table to the database.
   105722 */
   105723 static int fts3FlushCallback(
   105724   Fts3Table *p,                   /* FTS3 Virtual table handle */
   105725   void *pContext,                 /* Pointer to SegmentWriter* to write with */
   105726   char *zTerm,                    /* Term to write to the db */
   105727   int nTerm,                      /* Number of bytes in zTerm */
   105728   char *aDoclist,                 /* Doclist associated with zTerm */
   105729   int nDoclist                    /* Number of bytes in doclist */
   105730 ){
   105731   SegmentWriter **ppW = (SegmentWriter **)pContext;
   105732   return fts3SegWriterAdd(p, ppW, 0, zTerm, nTerm, aDoclist, nDoclist);
   105733 }
   105734 
   105735 /*
   105736 ** This function is used to iterate through a contiguous set of terms
   105737 ** stored in the full-text index. It merges data contained in one or
   105738 ** more segments to support this.
   105739 **
   105740 ** The second argument is passed an array of pointers to SegReader objects
   105741 ** allocated with sqlite3Fts3SegReaderNew(). This function merges the range
   105742 ** of terms selected by each SegReader. If a single term is present in
   105743 ** more than one segment, the associated doclists are merged. For each
   105744 ** term and (possibly merged) doclist in the merged range, the callback
   105745 ** function xFunc is invoked with its arguments set as follows.
   105746 **
   105747 **   arg 0: Copy of 'p' parameter passed to this function
   105748 **   arg 1: Copy of 'pContext' parameter passed to this function
   105749 **   arg 2: Pointer to buffer containing term
   105750 **   arg 3: Size of arg 2 buffer in bytes
   105751 **   arg 4: Pointer to buffer containing doclist
   105752 **   arg 5: Size of arg 2 buffer in bytes
   105753 **
   105754 ** The 4th argument to this function is a pointer to a structure of type
   105755 ** Fts3SegFilter, defined in fts3Int.h. The contents of this structure
   105756 ** further restrict the range of terms that callbacks are made for and
   105757 ** modify the behaviour of this function. See comments above structure
   105758 ** definition for details.
   105759 */
   105760 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
   105761   Fts3Table *p,                   /* Virtual table handle */
   105762   Fts3SegReader **apSegment,      /* Array of Fts3SegReader objects */
   105763   int nSegment,                   /* Size of apSegment array */
   105764   Fts3SegFilter *pFilter,         /* Restrictions on range of iteration */
   105765   int (*xFunc)(Fts3Table *, void *, char *, int, char *, int),  /* Callback */
   105766   void *pContext                  /* Callback context (2nd argument) */
   105767 ){
   105768   int i;                          /* Iterator variable */
   105769   char *aBuffer = 0;              /* Buffer to merge doclists in */
   105770   int nAlloc = 0;                 /* Allocated size of aBuffer buffer */
   105771   int rc = SQLITE_OK;             /* Return code */
   105772 
   105773   int isIgnoreEmpty =  (pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
   105774   int isRequirePos =   (pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
   105775   int isColFilter =    (pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
   105776   int isPrefix =       (pFilter->flags & FTS3_SEGMENT_PREFIX);
   105777 
   105778   /* If there are zero segments, this function is a no-op. This scenario
   105779   ** comes about only when reading from an empty database.
   105780   */
   105781   if( nSegment==0 ) goto finished;
   105782 
   105783   /* If the Fts3SegFilter defines a specific term (or term prefix) to search
   105784   ** for, then advance each segment iterator until it points to a term of
   105785   ** equal or greater value than the specified term. This prevents many
   105786   ** unnecessary merge/sort operations for the case where single segment
   105787   ** b-tree leaf nodes contain more than one term.
   105788   */
   105789   if( pFilter->zTerm ){
   105790     int nTerm = pFilter->nTerm;
   105791     const char *zTerm = pFilter->zTerm;
   105792     for(i=0; i<nSegment; i++){
   105793       Fts3SegReader *pSeg = apSegment[i];
   105794       while( fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 ){
   105795         rc = fts3SegReaderNext(pSeg);
   105796         if( rc!=SQLITE_OK ) goto finished; }
   105797     }
   105798   }
   105799 
   105800   fts3SegReaderSort(apSegment, nSegment, nSegment, fts3SegReaderCmp);
   105801   while( apSegment[0]->aNode ){
   105802     int nTerm = apSegment[0]->nTerm;
   105803     char *zTerm = apSegment[0]->zTerm;
   105804     int nMerge = 1;
   105805 
   105806     /* If this is a prefix-search, and if the term that apSegment[0] points
   105807     ** to does not share a suffix with pFilter->zTerm/nTerm, then all
   105808     ** required callbacks have been made. In this case exit early.
   105809     **
   105810     ** Similarly, if this is a search for an exact match, and the first term
   105811     ** of segment apSegment[0] is not a match, exit early.
   105812     */
   105813     if( pFilter->zTerm ){
   105814       if( nTerm<pFilter->nTerm
   105815        || (!isPrefix && nTerm>pFilter->nTerm)
   105816        || memcmp(zTerm, pFilter->zTerm, pFilter->nTerm)
   105817     ){
   105818         goto finished;
   105819       }
   105820     }
   105821 
   105822     while( nMerge<nSegment
   105823         && apSegment[nMerge]->aNode
   105824         && apSegment[nMerge]->nTerm==nTerm
   105825         && 0==memcmp(zTerm, apSegment[nMerge]->zTerm, nTerm)
   105826     ){
   105827       nMerge++;
   105828     }
   105829 
   105830     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
   105831     if( nMerge==1 && !isIgnoreEmpty ){
   105832       Fts3SegReader *p0 = apSegment[0];
   105833       rc = xFunc(p, pContext, zTerm, nTerm, p0->aDoclist, p0->nDoclist);
   105834       if( rc!=SQLITE_OK ) goto finished;
   105835     }else{
   105836       int nDoclist = 0;           /* Size of doclist */
   105837       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
   105838 
   105839       /* The current term of the first nMerge entries in the array
   105840       ** of Fts3SegReader objects is the same. The doclists must be merged
   105841       ** and a single term added to the new segment.
   105842       */
   105843       for(i=0; i<nMerge; i++){
   105844         fts3SegReaderFirstDocid(apSegment[i]);
   105845       }
   105846       fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
   105847       while( apSegment[0]->pOffsetList ){
   105848         int j;                    /* Number of segments that share a docid */
   105849         char *pList;
   105850         int nList;
   105851         int nByte;
   105852         sqlite3_int64 iDocid = apSegment[0]->iDocid;
   105853         fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
   105854         j = 1;
   105855         while( j<nMerge
   105856             && apSegment[j]->pOffsetList
   105857             && apSegment[j]->iDocid==iDocid
   105858         ){
   105859           fts3SegReaderNextDocid(apSegment[j], 0, 0);
   105860           j++;
   105861         }
   105862 
   105863         if( isColFilter ){
   105864           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
   105865         }
   105866 
   105867         if( !isIgnoreEmpty || nList>0 ){
   105868           nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
   105869           if( nDoclist+nByte>nAlloc ){
   105870             char *aNew;
   105871             nAlloc = nDoclist+nByte*2;
   105872             aNew = sqlite3_realloc(aBuffer, nAlloc);
   105873             if( !aNew ){
   105874               rc = SQLITE_NOMEM;
   105875               goto finished;
   105876             }
   105877             aBuffer = aNew;
   105878           }
   105879           nDoclist += sqlite3Fts3PutVarint(&aBuffer[nDoclist], iDocid-iPrev);
   105880           iPrev = iDocid;
   105881           if( isRequirePos ){
   105882             memcpy(&aBuffer[nDoclist], pList, nList);
   105883             nDoclist += nList;
   105884             aBuffer[nDoclist++] = '\0';
   105885           }
   105886         }
   105887 
   105888         fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
   105889       }
   105890 
   105891       if( nDoclist>0 ){
   105892         rc = xFunc(p, pContext, zTerm, nTerm, aBuffer, nDoclist);
   105893         if( rc!=SQLITE_OK ) goto finished;
   105894       }
   105895     }
   105896 
   105897     /* If there is a term specified to filter on, and this is not a prefix
   105898     ** search, return now. The callback that corresponds to the required
   105899     ** term (if such a term exists in the index) has already been made.
   105900     */
   105901     if( pFilter->zTerm && !isPrefix ){
   105902       goto finished;
   105903     }
   105904 
   105905     for(i=0; i<nMerge; i++){
   105906       rc = fts3SegReaderNext(apSegment[i]);
   105907       if( rc!=SQLITE_OK ) goto finished;
   105908     }
   105909     fts3SegReaderSort(apSegment, nSegment, nMerge, fts3SegReaderCmp);
   105910   }
   105911 
   105912  finished:
   105913   sqlite3_free(aBuffer);
   105914   return rc;
   105915 }
   105916 
   105917 /*
   105918 ** Merge all level iLevel segments in the database into a single
   105919 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
   105920 ** single segment with a level equal to the numerically largest level
   105921 ** currently present in the database.
   105922 **
   105923 ** If this function is called with iLevel<0, but there is only one
   105924 ** segment in the database, SQLITE_DONE is returned immediately.
   105925 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
   105926 ** an SQLite error code is returned.
   105927 */
   105928 static int fts3SegmentMerge(Fts3Table *p, int iLevel){
   105929   int i;                          /* Iterator variable */
   105930   int rc;                         /* Return code */
   105931   int iIdx;                       /* Index of new segment */
   105932   int iNewLevel;                  /* Level to create new segment at */
   105933   sqlite3_stmt *pStmt = 0;
   105934   SegmentWriter *pWriter = 0;
   105935   int nSegment = 0;               /* Number of segments being merged */
   105936   Fts3SegReader **apSegment = 0;  /* Array of Segment iterators */
   105937   Fts3SegReader *pPending = 0;    /* Iterator for pending-terms */
   105938   Fts3SegFilter filter;           /* Segment term filter condition */
   105939 
   105940   if( iLevel<0 ){
   105941     /* This call is to merge all segments in the database to a single
   105942     ** segment. The level of the new segment is equal to the the numerically
   105943     ** greatest segment level currently present in the database. The index
   105944     ** of the new segment is always 0.
   105945     */
   105946     iIdx = 0;
   105947     rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pPending);
   105948     if( rc!=SQLITE_OK ) goto finished;
   105949     rc = fts3SegmentCountMax(p, &nSegment, &iNewLevel);
   105950     if( rc!=SQLITE_OK ) goto finished;
   105951     nSegment += (pPending!=0);
   105952     if( nSegment<=1 ){
   105953       return SQLITE_DONE;
   105954     }
   105955   }else{
   105956     /* This call is to merge all segments at level iLevel. Find the next
   105957     ** available segment index at level iLevel+1. The call to
   105958     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
   105959     ** a single iLevel+2 segment if necessary.
   105960     */
   105961     iNewLevel = iLevel+1;
   105962     rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
   105963     if( rc!=SQLITE_OK ) goto finished;
   105964     rc = fts3SegmentCount(p, iLevel, &nSegment);
   105965     if( rc!=SQLITE_OK ) goto finished;
   105966   }
   105967   assert( nSegment>0 );
   105968   assert( iNewLevel>=0 );
   105969 
   105970   /* Allocate space for an array of pointers to segment iterators. */
   105971   apSegment = (Fts3SegReader**)sqlite3_malloc(sizeof(Fts3SegReader *)*nSegment);
   105972   if( !apSegment ){
   105973     rc = SQLITE_NOMEM;
   105974     goto finished;
   105975   }
   105976   memset(apSegment, 0, sizeof(Fts3SegReader *)*nSegment);
   105977 
   105978   /* Allocate a Fts3SegReader structure for each segment being merged. A
   105979   ** Fts3SegReader stores the state data required to iterate through all
   105980   ** entries on all leaves of a single segment.
   105981   */
   105982   assert( SQL_SELECT_LEVEL+1==SQL_SELECT_ALL_LEVEL);
   105983   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL+(iLevel<0), &pStmt, 0);
   105984   if( rc!=SQLITE_OK ) goto finished;
   105985   sqlite3_bind_int(pStmt, 1, iLevel);
   105986   for(i=0; SQLITE_ROW==(sqlite3_step(pStmt)); i++){
   105987     rc = fts3SegReaderNew(p, pStmt, i, &apSegment[i]);
   105988     if( rc!=SQLITE_OK ){
   105989       goto finished;
   105990     }
   105991   }
   105992   rc = sqlite3_reset(pStmt);
   105993   if( pPending ){
   105994     apSegment[i] = pPending;
   105995     pPending = 0;
   105996   }
   105997   pStmt = 0;
   105998   if( rc!=SQLITE_OK ) goto finished;
   105999 
   106000   memset(&filter, 0, sizeof(Fts3SegFilter));
   106001   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
   106002   filter.flags |= (iLevel<0 ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
   106003   rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment,
   106004       &filter, fts3MergeCallback, (void *)&pWriter
   106005   );
   106006   if( rc!=SQLITE_OK ) goto finished;
   106007 
   106008   rc = fts3DeleteSegdir(p, iLevel, apSegment, nSegment);
   106009   if( rc==SQLITE_OK ){
   106010     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
   106011   }
   106012 
   106013  finished:
   106014   fts3SegWriterFree(pWriter);
   106015   if( apSegment ){
   106016     for(i=0; i<nSegment; i++){
   106017       sqlite3Fts3SegReaderFree(p, apSegment[i]);
   106018     }
   106019     sqlite3_free(apSegment);
   106020   }
   106021   sqlite3Fts3SegReaderFree(p, pPending);
   106022   sqlite3_reset(pStmt);
   106023   return rc;
   106024 }
   106025 
   106026 
   106027 /*
   106028 ** Flush the contents of pendingTerms to a level 0 segment.
   106029 */
   106030 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
   106031   int rc;                         /* Return Code */
   106032   int idx;                        /* Index of new segment created */
   106033   SegmentWriter *pWriter = 0;     /* Used to write the segment */
   106034   Fts3SegReader *pReader = 0;     /* Used to iterate through the hash table */
   106035 
   106036   /* Allocate a SegReader object to iterate through the contents of the
   106037   ** pending-terms table. If an error occurs, or if there are no terms
   106038   ** in the pending-terms table, return immediately.
   106039   */
   106040   rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pReader);
   106041   if( rc!=SQLITE_OK || pReader==0 ){
   106042     return rc;
   106043   }
   106044 
   106045   /* Determine the next index at level 0. If level 0 is already full, this
   106046   ** call may merge all existing level 0 segments into a single level 1
   106047   ** segment.
   106048   */
   106049   rc = fts3AllocateSegdirIdx(p, 0, &idx);
   106050 
   106051   /* If no errors have occured, iterate through the contents of the
   106052   ** pending-terms hash table using the Fts3SegReader iterator. The callback
   106053   ** writes each term (along with its doclist) to the database via the
   106054   ** SegmentWriter handle pWriter.
   106055   */
   106056   if( rc==SQLITE_OK ){
   106057     void *c = (void *)&pWriter;   /* SegReaderIterate() callback context */
   106058     Fts3SegFilter f;              /* SegReaderIterate() parameters */
   106059 
   106060     memset(&f, 0, sizeof(Fts3SegFilter));
   106061     f.flags = FTS3_SEGMENT_REQUIRE_POS;
   106062     rc = sqlite3Fts3SegReaderIterate(p, &pReader, 1, &f, fts3FlushCallback, c);
   106063   }
   106064   assert( pWriter || rc!=SQLITE_OK );
   106065 
   106066   /* If no errors have occured, flush the SegmentWriter object to the
   106067   ** database. Then delete the SegmentWriter and Fts3SegReader objects
   106068   ** allocated by this function.
   106069   */
   106070   if( rc==SQLITE_OK ){
   106071     rc = fts3SegWriterFlush(p, pWriter, 0, idx);
   106072   }
   106073   fts3SegWriterFree(pWriter);
   106074   sqlite3Fts3SegReaderFree(p, pReader);
   106075 
   106076   if( rc==SQLITE_OK ){
   106077     sqlite3Fts3PendingTermsClear(p);
   106078   }
   106079   return rc;
   106080 }
   106081 
   106082 /*
   106083 ** Handle a 'special' INSERT of the form:
   106084 **
   106085 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
   106086 **
   106087 ** Argument pVal contains the result of <expr>. Currently the only
   106088 ** meaningful value to insert is the text 'optimize'.
   106089 */
   106090 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
   106091   int rc;                         /* Return Code */
   106092   const char *zVal = (const char *)sqlite3_value_text(pVal);
   106093   int nVal = sqlite3_value_bytes(pVal);
   106094 
   106095   if( !zVal ){
   106096     return SQLITE_NOMEM;
   106097   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
   106098     rc = fts3SegmentMerge(p, -1);
   106099     if( rc==SQLITE_DONE ){
   106100       rc = SQLITE_OK;
   106101     }else{
   106102       sqlite3Fts3PendingTermsClear(p);
   106103     }
   106104 #ifdef SQLITE_TEST
   106105   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
   106106     p->nNodeSize = atoi(&zVal[9]);
   106107     rc = SQLITE_OK;
   106108   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
   106109     p->nMaxPendingData = atoi(&zVal[11]);
   106110     rc = SQLITE_OK;
   106111 #endif
   106112   }else{
   106113     rc = SQLITE_ERROR;
   106114   }
   106115 
   106116   return rc;
   106117 }
   106118 
   106119 /*
   106120 ** This function does the work for the xUpdate method of FTS3 virtual
   106121 ** tables.
   106122 */
   106123 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
   106124   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
   106125   int nArg,                       /* Size of argument array */
   106126   sqlite3_value **apVal,          /* Array of arguments */
   106127   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
   106128 ){
   106129   Fts3Table *p = (Fts3Table *)pVtab;
   106130   int rc = SQLITE_OK;             /* Return Code */
   106131   int isRemove = 0;               /* True for an UPDATE or DELETE */
   106132   sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
   106133 
   106134 
   106135   /* If this is a DELETE or UPDATE operation, remove the old record. */
   106136   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
   106137     int isEmpty;
   106138     rc = fts3IsEmpty(p, apVal, &isEmpty);
   106139     if( rc==SQLITE_OK ){
   106140       if( isEmpty ){
   106141         /* Deleting this row means the whole table is empty. In this case
   106142         ** delete the contents of all three tables and throw away any
   106143         ** data in the pendingTerms hash table.
   106144         */
   106145         rc = fts3DeleteAll(p);
   106146       }else{
   106147         isRemove = 1;
   106148         iRemove = sqlite3_value_int64(apVal[0]);
   106149         rc = fts3PendingTermsDocid(p, iRemove);
   106150         if( rc==SQLITE_OK ){
   106151           rc = fts3DeleteTerms(p, apVal);
   106152           if( rc==SQLITE_OK ){
   106153             rc = fts3SqlExec(p, SQL_DELETE_CONTENT, apVal);
   106154           }
   106155         }
   106156       }
   106157     }
   106158   }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
   106159     return fts3SpecialInsert(p, apVal[p->nColumn+2]);
   106160   }
   106161 
   106162   /* If this is an INSERT or UPDATE operation, insert the new record. */
   106163   if( nArg>1 && rc==SQLITE_OK ){
   106164     rc = fts3InsertData(p, apVal, pRowid);
   106165     if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
   106166       rc = fts3PendingTermsDocid(p, *pRowid);
   106167     }
   106168     if( rc==SQLITE_OK ){
   106169       rc = fts3InsertTerms(p, apVal);
   106170     }
   106171   }
   106172 
   106173   return rc;
   106174 }
   106175 
   106176 /*
   106177 ** Flush any data in the pending-terms hash table to disk. If successful,
   106178 ** merge all segments in the database (including the new segment, if
   106179 ** there was any data to flush) into a single segment.
   106180 */
   106181 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
   106182   int rc;
   106183   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
   106184   if( rc==SQLITE_OK ){
   106185     rc = fts3SegmentMerge(p, -1);
   106186     if( rc==SQLITE_OK ){
   106187       rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
   106188       if( rc==SQLITE_OK ){
   106189         sqlite3Fts3PendingTermsClear(p);
   106190       }
   106191     }else{
   106192       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
   106193       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
   106194     }
   106195   }
   106196   return rc;
   106197 }
   106198 
   106199 #endif
   106200 
   106201 /************** End of fts3_write.c ******************************************/
   106202 /************** Begin file fts3_snippet.c ************************************/
   106203 /*
   106204 ** 2009 Oct 23
   106205 **
   106206 ** The author disclaims copyright to this source code.  In place of
   106207 ** a legal notice, here is a blessing:
   106208 **
   106209 **    May you do good and not evil.
   106210 **    May you find forgiveness for yourself and forgive others.
   106211 **    May you share freely, never taking more than you give.
   106212 **
   106213 ******************************************************************************
   106214 */
   106215 
   106216 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   106217 
   106218 
   106219 typedef struct Snippet Snippet;
   106220 
   106221 /*
   106222 ** An instance of the following structure keeps track of generated
   106223 ** matching-word offset information and snippets.
   106224 */
   106225 struct Snippet {
   106226   int nMatch;                     /* Total number of matches */
   106227   int nAlloc;                     /* Space allocated for aMatch[] */
   106228   struct snippetMatch {  /* One entry for each matching term */
   106229     char snStatus;       /* Status flag for use while constructing snippets */
   106230     short int nByte;     /* Number of bytes in the term */
   106231     short int iCol;      /* The column that contains the match */
   106232     short int iTerm;     /* The index in Query.pTerms[] of the matching term */
   106233     int iToken;          /* The index of the matching document token */
   106234     int iStart;          /* The offset to the first character of the term */
   106235   } *aMatch;                      /* Points to space obtained from malloc */
   106236   char *zOffset;                  /* Text rendering of aMatch[] */
   106237   int nOffset;                    /* strlen(zOffset) */
   106238   char *zSnippet;                 /* Snippet text */
   106239   int nSnippet;                   /* strlen(zSnippet) */
   106240 };
   106241 
   106242 
   106243 /* It is not safe to call isspace(), tolower(), or isalnum() on
   106244 ** hi-bit-set characters.  This is the same solution used in the
   106245 ** tokenizer.
   106246 */
   106247 static int fts3snippetIsspace(char c){
   106248   return (c&0x80)==0 ? isspace(c) : 0;
   106249 }
   106250 
   106251 
   106252 /*
   106253 ** A StringBuffer object holds a zero-terminated string that grows
   106254 ** arbitrarily by appending.  Space to hold the string is obtained
   106255 ** from sqlite3_malloc().  After any memory allocation failure,
   106256 ** StringBuffer.z is set to NULL and no further allocation is attempted.
   106257 */
   106258 typedef struct StringBuffer {
   106259   char *z;         /* Text of the string.  Space from malloc. */
   106260   int nUsed;       /* Number bytes of z[] used, not counting \000 terminator */
   106261   int nAlloc;      /* Bytes allocated for z[] */
   106262 } StringBuffer;
   106263 
   106264 
   106265 /*
   106266 ** Initialize a new StringBuffer.
   106267 */
   106268 static void fts3SnippetSbInit(StringBuffer *p){
   106269   p->nAlloc = 100;
   106270   p->nUsed = 0;
   106271   p->z = sqlite3_malloc( p->nAlloc );
   106272 }
   106273 
   106274 /*
   106275 ** Append text to the string buffer.
   106276 */
   106277 static void fts3SnippetAppend(StringBuffer *p, const char *zNew, int nNew){
   106278   if( p->z==0 ) return;
   106279   if( nNew<0 ) nNew = (int)strlen(zNew);
   106280   if( p->nUsed + nNew >= p->nAlloc ){
   106281     int nAlloc;
   106282     char *zNew;
   106283 
   106284     nAlloc = p->nUsed + nNew + p->nAlloc;
   106285     zNew = sqlite3_realloc(p->z, nAlloc);
   106286     if( zNew==0 ){
   106287       sqlite3_free(p->z);
   106288       p->z = 0;
   106289       return;
   106290     }
   106291     p->z = zNew;
   106292     p->nAlloc = nAlloc;
   106293   }
   106294   memcpy(&p->z[p->nUsed], zNew, nNew);
   106295   p->nUsed += nNew;
   106296   p->z[p->nUsed] = 0;
   106297 }
   106298 
   106299 /* If the StringBuffer ends in something other than white space, add a
   106300 ** single space character to the end.
   106301 */
   106302 static void fts3SnippetAppendWhiteSpace(StringBuffer *p){
   106303   if( p->z && p->nUsed && !fts3snippetIsspace(p->z[p->nUsed-1]) ){
   106304     fts3SnippetAppend(p, " ", 1);
   106305   }
   106306 }
   106307 
   106308 /* Remove white space from the end of the StringBuffer */
   106309 static void fts3SnippetTrimWhiteSpace(StringBuffer *p){
   106310   if( p->z ){
   106311     while( p->nUsed && fts3snippetIsspace(p->z[p->nUsed-1]) ){
   106312       p->nUsed--;
   106313     }
   106314     p->z[p->nUsed] = 0;
   106315   }
   106316 }
   106317 
   106318 /*
   106319 ** Release all memory associated with the Snippet structure passed as
   106320 ** an argument.
   106321 */
   106322 static void fts3SnippetFree(Snippet *p){
   106323   if( p ){
   106324     sqlite3_free(p->aMatch);
   106325     sqlite3_free(p->zOffset);
   106326     sqlite3_free(p->zSnippet);
   106327     sqlite3_free(p);
   106328   }
   106329 }
   106330 
   106331 /*
   106332 ** Append a single entry to the p->aMatch[] log.
   106333 */
   106334 static int snippetAppendMatch(
   106335   Snippet *p,               /* Append the entry to this snippet */
   106336   int iCol, int iTerm,      /* The column and query term */
   106337   int iToken,               /* Matching token in document */
   106338   int iStart, int nByte     /* Offset and size of the match */
   106339 ){
   106340   int i;
   106341   struct snippetMatch *pMatch;
   106342   if( p->nMatch+1>=p->nAlloc ){
   106343     struct snippetMatch *pNew;
   106344     p->nAlloc = p->nAlloc*2 + 10;
   106345     pNew = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
   106346     if( pNew==0 ){
   106347       p->aMatch = 0;
   106348       p->nMatch = 0;
   106349       p->nAlloc = 0;
   106350       return SQLITE_NOMEM;
   106351     }
   106352     p->aMatch = pNew;
   106353   }
   106354   i = p->nMatch++;
   106355   pMatch = &p->aMatch[i];
   106356   pMatch->iCol = (short)iCol;
   106357   pMatch->iTerm = (short)iTerm;
   106358   pMatch->iToken = iToken;
   106359   pMatch->iStart = iStart;
   106360   pMatch->nByte = (short)nByte;
   106361   return SQLITE_OK;
   106362 }
   106363 
   106364 /*
   106365 ** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
   106366 */
   106367 #define FTS3_ROTOR_SZ   (32)
   106368 #define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
   106369 
   106370 /*
   106371 ** Function to iterate through the tokens of a compiled expression.
   106372 **
   106373 ** Except, skip all tokens on the right-hand side of a NOT operator.
   106374 ** This function is used to find tokens as part of snippet and offset
   106375 ** generation and we do nt want snippets and offsets to report matches
   106376 ** for tokens on the RHS of a NOT.
   106377 */
   106378 static int fts3NextExprToken(Fts3Expr **ppExpr, int *piToken){
   106379   Fts3Expr *p = *ppExpr;
   106380   int iToken = *piToken;
   106381   if( iToken<0 ){
   106382     /* In this case the expression p is the root of an expression tree.
   106383     ** Move to the first token in the expression tree.
   106384     */
   106385     while( p->pLeft ){
   106386       p = p->pLeft;
   106387     }
   106388     iToken = 0;
   106389   }else{
   106390     assert(p && p->eType==FTSQUERY_PHRASE );
   106391     if( iToken<(p->pPhrase->nToken-1) ){
   106392       iToken++;
   106393     }else{
   106394       iToken = 0;
   106395       while( p->pParent && p->pParent->pLeft!=p ){
   106396         assert( p->pParent->pRight==p );
   106397         p = p->pParent;
   106398       }
   106399       p = p->pParent;
   106400       if( p ){
   106401         assert( p->pRight!=0 );
   106402         p = p->pRight;
   106403         while( p->pLeft ){
   106404           p = p->pLeft;
   106405         }
   106406       }
   106407     }
   106408   }
   106409 
   106410   *ppExpr = p;
   106411   *piToken = iToken;
   106412   return p?1:0;
   106413 }
   106414 
   106415 /*
   106416 ** Return TRUE if the expression node pExpr is located beneath the
   106417 ** RHS of a NOT operator.
   106418 */
   106419 static int fts3ExprBeneathNot(Fts3Expr *p){
   106420   Fts3Expr *pParent;
   106421   while( p ){
   106422     pParent = p->pParent;
   106423     if( pParent && pParent->eType==FTSQUERY_NOT && pParent->pRight==p ){
   106424       return 1;
   106425     }
   106426     p = pParent;
   106427   }
   106428   return 0;
   106429 }
   106430 
   106431 /*
   106432 ** Add entries to pSnippet->aMatch[] for every match that occurs against
   106433 ** document zDoc[0..nDoc-1] which is stored in column iColumn.
   106434 */
   106435 static int snippetOffsetsOfColumn(
   106436   Fts3Cursor *pCur,         /* The fulltest search cursor */
   106437   Snippet *pSnippet,             /* The Snippet object to be filled in */
   106438   int iColumn,                   /* Index of fulltext table column */
   106439   const char *zDoc,              /* Text of the fulltext table column */
   106440   int nDoc                       /* Length of zDoc in bytes */
   106441 ){
   106442   const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
   106443   sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
   106444   sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
   106445   Fts3Table *pVtab;                /* The full text index */
   106446   int nColumn;                         /* Number of columns in the index */
   106447   int i, j;                            /* Loop counters */
   106448   int rc;                              /* Return code */
   106449   unsigned int match, prevMatch;       /* Phrase search bitmasks */
   106450   const char *zToken;                  /* Next token from the tokenizer */
   106451   int nToken;                          /* Size of zToken */
   106452   int iBegin, iEnd, iPos;              /* Offsets of beginning and end */
   106453 
   106454   /* The following variables keep a circular buffer of the last
   106455   ** few tokens */
   106456   unsigned int iRotor = 0;             /* Index of current token */
   106457   int iRotorBegin[FTS3_ROTOR_SZ];      /* Beginning offset of token */
   106458   int iRotorLen[FTS3_ROTOR_SZ];        /* Length of token */
   106459 
   106460   pVtab =  (Fts3Table *)pCur->base.pVtab;
   106461   nColumn = pVtab->nColumn;
   106462   pTokenizer = pVtab->pTokenizer;
   106463   pTModule = pTokenizer->pModule;
   106464   rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
   106465   if( rc ) return rc;
   106466   pTCursor->pTokenizer = pTokenizer;
   106467 
   106468   prevMatch = 0;
   106469   while( (rc = pTModule->xNext(pTCursor, &zToken, &nToken,
   106470                                &iBegin, &iEnd, &iPos))==SQLITE_OK ){
   106471     Fts3Expr *pIter = pCur->pExpr;
   106472     int iIter = -1;
   106473     iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
   106474     iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
   106475     match = 0;
   106476     for(i=0; i<(FTS3_ROTOR_SZ-1) && fts3NextExprToken(&pIter, &iIter); i++){
   106477       int nPhrase;                    /* Number of tokens in current phrase */
   106478       struct PhraseToken *pToken;     /* Current token */
   106479       int iCol;                       /* Column index */
   106480 
   106481       if( fts3ExprBeneathNot(pIter) ) continue;
   106482       nPhrase = pIter->pPhrase->nToken;
   106483       pToken = &pIter->pPhrase->aToken[iIter];
   106484       iCol = pIter->pPhrase->iColumn;
   106485       if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
   106486       if( pToken->n>nToken ) continue;
   106487       if( !pToken->isPrefix && pToken->n<nToken ) continue;
   106488       assert( pToken->n<=nToken );
   106489       if( memcmp(pToken->z, zToken, pToken->n) ) continue;
   106490       if( iIter>0 && (prevMatch & (1<<i))==0 ) continue;
   106491       match |= 1<<i;
   106492       if( i==(FTS3_ROTOR_SZ-2) || nPhrase==iIter+1 ){
   106493         for(j=nPhrase-1; j>=0; j--){
   106494           int k = (iRotor-j) & FTS3_ROTOR_MASK;
   106495           rc = snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
   106496                                   iRotorBegin[k], iRotorLen[k]);
   106497           if( rc ) goto end_offsets_of_column;
   106498         }
   106499       }
   106500     }
   106501     prevMatch = match<<1;
   106502     iRotor++;
   106503   }
   106504 end_offsets_of_column:
   106505   pTModule->xClose(pTCursor);
   106506   return rc==SQLITE_DONE ? SQLITE_OK : rc;
   106507 }
   106508 
   106509 /*
   106510 ** Remove entries from the pSnippet structure to account for the NEAR
   106511 ** operator. When this is called, pSnippet contains the list of token
   106512 ** offsets produced by treating all NEAR operators as AND operators.
   106513 ** This function removes any entries that should not be present after
   106514 ** accounting for the NEAR restriction. For example, if the queried
   106515 ** document is:
   106516 **
   106517 **     "A B C D E A"
   106518 **
   106519 ** and the query is:
   106520 **
   106521 **     A NEAR/0 E
   106522 **
   106523 ** then when this function is called the Snippet contains token offsets
   106524 ** 0, 4 and 5. This function removes the "0" entry (because the first A
   106525 ** is not near enough to an E).
   106526 **
   106527 ** When this function is called, the value pointed to by parameter piLeft is
   106528 ** the integer id of the left-most token in the expression tree headed by
   106529 ** pExpr. This function increments *piLeft by the total number of tokens
   106530 ** in the expression tree headed by pExpr.
   106531 **
   106532 ** Return 1 if any trimming occurs.  Return 0 if no trimming is required.
   106533 */
   106534 static int trimSnippetOffsets(
   106535   Fts3Expr *pExpr,      /* The search expression */
   106536   Snippet *pSnippet,    /* The set of snippet offsets to be trimmed */
   106537   int *piLeft           /* Index of left-most token in pExpr */
   106538 ){
   106539   if( pExpr ){
   106540     if( trimSnippetOffsets(pExpr->pLeft, pSnippet, piLeft) ){
   106541       return 1;
   106542     }
   106543 
   106544     switch( pExpr->eType ){
   106545       case FTSQUERY_PHRASE:
   106546         *piLeft += pExpr->pPhrase->nToken;
   106547         break;
   106548       case FTSQUERY_NEAR: {
   106549         /* The right-hand-side of a NEAR operator is always a phrase. The
   106550         ** left-hand-side is either a phrase or an expression tree that is
   106551         ** itself headed by a NEAR operator. The following initializations
   106552         ** set local variable iLeft to the token number of the left-most
   106553         ** token in the right-hand phrase, and iRight to the right most
   106554         ** token in the same phrase. For example, if we had:
   106555         **
   106556         **     <col> MATCH '"abc def" NEAR/2 "ghi jkl"'
   106557         **
   106558         ** then iLeft will be set to 2 (token number of ghi) and nToken will
   106559         ** be set to 4.
   106560         */
   106561         Fts3Expr *pLeft = pExpr->pLeft;
   106562         Fts3Expr *pRight = pExpr->pRight;
   106563         int iLeft = *piLeft;
   106564         int nNear = pExpr->nNear;
   106565         int nToken = pRight->pPhrase->nToken;
   106566         int jj, ii;
   106567         if( pLeft->eType==FTSQUERY_NEAR ){
   106568           pLeft = pLeft->pRight;
   106569         }
   106570         assert( pRight->eType==FTSQUERY_PHRASE );
   106571         assert( pLeft->eType==FTSQUERY_PHRASE );
   106572         nToken += pLeft->pPhrase->nToken;
   106573 
   106574         for(ii=0; ii<pSnippet->nMatch; ii++){
   106575           struct snippetMatch *p = &pSnippet->aMatch[ii];
   106576           if( p->iTerm==iLeft ){
   106577             int isOk = 0;
   106578             /* Snippet ii is an occurence of query term iLeft in the document.
   106579             ** It occurs at position (p->iToken) of the document. We now
   106580             ** search for an instance of token (iLeft-1) somewhere in the
   106581             ** range (p->iToken - nNear)...(p->iToken + nNear + nToken) within
   106582             ** the set of snippetMatch structures. If one is found, proceed.
   106583             ** If one cannot be found, then remove snippets ii..(ii+N-1)
   106584             ** from the matching snippets, where N is the number of tokens
   106585             ** in phrase pRight->pPhrase.
   106586             */
   106587             for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
   106588               struct snippetMatch *p2 = &pSnippet->aMatch[jj];
   106589               if( p2->iTerm==(iLeft-1) ){
   106590                 if( p2->iToken>=(p->iToken-nNear-1)
   106591                  && p2->iToken<(p->iToken+nNear+nToken)
   106592                 ){
   106593                   isOk = 1;
   106594                 }
   106595               }
   106596             }
   106597             if( !isOk ){
   106598               int kk;
   106599               for(kk=0; kk<pRight->pPhrase->nToken; kk++){
   106600                 pSnippet->aMatch[kk+ii].iTerm = -2;
   106601               }
   106602               return 1;
   106603             }
   106604           }
   106605           if( p->iTerm==(iLeft-1) ){
   106606             int isOk = 0;
   106607             for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
   106608               struct snippetMatch *p2 = &pSnippet->aMatch[jj];
   106609               if( p2->iTerm==iLeft ){
   106610                 if( p2->iToken<=(p->iToken+nNear+1)
   106611                  && p2->iToken>(p->iToken-nNear-nToken)
   106612                 ){
   106613                   isOk = 1;
   106614                 }
   106615               }
   106616             }
   106617             if( !isOk ){
   106618               int kk;
   106619               for(kk=0; kk<pLeft->pPhrase->nToken; kk++){
   106620                 pSnippet->aMatch[ii-kk].iTerm = -2;
   106621               }
   106622               return 1;
   106623             }
   106624           }
   106625         }
   106626         break;
   106627       }
   106628     }
   106629 
   106630     if( trimSnippetOffsets(pExpr->pRight, pSnippet, piLeft) ){
   106631       return 1;
   106632     }
   106633   }
   106634   return 0;
   106635 }
   106636 
   106637 /*
   106638 ** Compute all offsets for the current row of the query.
   106639 ** If the offsets have already been computed, this routine is a no-op.
   106640 */
   106641 static int snippetAllOffsets(Fts3Cursor *pCsr, Snippet **ppSnippet){
   106642   Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;  /* The FTS3 virtual table */
   106643   int nColumn;           /* Number of columns.  Docid does count */
   106644   int iColumn;           /* Index of of a column */
   106645   int i;                 /* Loop index */
   106646   int iFirst;            /* First column to search */
   106647   int iLast;             /* Last coumn to search */
   106648   int iTerm = 0;
   106649   Snippet *pSnippet;
   106650   int rc = SQLITE_OK;
   106651 
   106652   if( pCsr->pExpr==0 ){
   106653     return SQLITE_OK;
   106654   }
   106655 
   106656   pSnippet = (Snippet *)sqlite3_malloc(sizeof(Snippet));
   106657   *ppSnippet = pSnippet;
   106658   if( !pSnippet ){
   106659     return SQLITE_NOMEM;
   106660   }
   106661   memset(pSnippet, 0, sizeof(Snippet));
   106662 
   106663   nColumn = p->nColumn;
   106664   iColumn = (pCsr->eSearch - 2);
   106665   if( iColumn<0 || iColumn>=nColumn ){
   106666     /* Look for matches over all columns of the full-text index */
   106667     iFirst = 0;
   106668     iLast = nColumn-1;
   106669   }else{
   106670     /* Look for matches in the iColumn-th column of the index only */
   106671     iFirst = iColumn;
   106672     iLast = iColumn;
   106673   }
   106674   for(i=iFirst; rc==SQLITE_OK && i<=iLast; i++){
   106675     const char *zDoc;
   106676     int nDoc;
   106677     zDoc = (const char*)sqlite3_column_text(pCsr->pStmt, i+1);
   106678     nDoc = sqlite3_column_bytes(pCsr->pStmt, i+1);
   106679     if( zDoc==0 && sqlite3_column_type(pCsr->pStmt, i+1)!=SQLITE_NULL ){
   106680       rc = SQLITE_NOMEM;
   106681     }else{
   106682       rc = snippetOffsetsOfColumn(pCsr, pSnippet, i, zDoc, nDoc);
   106683     }
   106684   }
   106685 
   106686   while( trimSnippetOffsets(pCsr->pExpr, pSnippet, &iTerm) ){
   106687     iTerm = 0;
   106688   }
   106689 
   106690   return rc;
   106691 }
   106692 
   106693 /*
   106694 ** Convert the information in the aMatch[] array of the snippet
   106695 ** into the string zOffset[0..nOffset-1]. This string is used as
   106696 ** the return of the SQL offsets() function.
   106697 */
   106698 static void snippetOffsetText(Snippet *p){
   106699   int i;
   106700   int cnt = 0;
   106701   StringBuffer sb;
   106702   char zBuf[200];
   106703   if( p->zOffset ) return;
   106704   fts3SnippetSbInit(&sb);
   106705   for(i=0; i<p->nMatch; i++){
   106706     struct snippetMatch *pMatch = &p->aMatch[i];
   106707     if( pMatch->iTerm>=0 ){
   106708       /* If snippetMatch.iTerm is less than 0, then the match was
   106709       ** discarded as part of processing the NEAR operator (see the
   106710       ** trimSnippetOffsetsForNear() function for details). Ignore
   106711       ** it in this case
   106712       */
   106713       zBuf[0] = ' ';
   106714       sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
   106715           pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
   106716       fts3SnippetAppend(&sb, zBuf, -1);
   106717       cnt++;
   106718     }
   106719   }
   106720   p->zOffset = sb.z;
   106721   p->nOffset = sb.z ? sb.nUsed : 0;
   106722 }
   106723 
   106724 /*
   106725 ** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
   106726 ** of matching words some of which might be in zDoc.  zDoc is column
   106727 ** number iCol.
   106728 **
   106729 ** iBreak is suggested spot in zDoc where we could begin or end an
   106730 ** excerpt.  Return a value similar to iBreak but possibly adjusted
   106731 ** to be a little left or right so that the break point is better.
   106732 */
   106733 static int wordBoundary(
   106734   int iBreak,                   /* The suggested break point */
   106735   const char *zDoc,             /* Document text */
   106736   int nDoc,                     /* Number of bytes in zDoc[] */
   106737   struct snippetMatch *aMatch,  /* Matching words */
   106738   int nMatch,                   /* Number of entries in aMatch[] */
   106739   int iCol                      /* The column number for zDoc[] */
   106740 ){
   106741   int i;
   106742   if( iBreak<=10 ){
   106743     return 0;
   106744   }
   106745   if( iBreak>=nDoc-10 ){
   106746     return nDoc;
   106747   }
   106748   for(i=0; ALWAYS(i<nMatch) && aMatch[i].iCol<iCol; i++){}
   106749   while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
   106750   if( i<nMatch ){
   106751     if( aMatch[i].iStart<iBreak+10 ){
   106752       return aMatch[i].iStart;
   106753     }
   106754     if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
   106755       return aMatch[i-1].iStart;
   106756     }
   106757   }
   106758   for(i=1; i<=10; i++){
   106759     if( fts3snippetIsspace(zDoc[iBreak-i]) ){
   106760       return iBreak - i + 1;
   106761     }
   106762     if( fts3snippetIsspace(zDoc[iBreak+i]) ){
   106763       return iBreak + i + 1;
   106764     }
   106765   }
   106766   return iBreak;
   106767 }
   106768 
   106769 
   106770 
   106771 /*
   106772 ** Allowed values for Snippet.aMatch[].snStatus
   106773 */
   106774 #define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
   106775 #define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */
   106776 
   106777 /*
   106778 ** Generate the text of a snippet.
   106779 */
   106780 static void snippetText(
   106781   Fts3Cursor *pCursor,   /* The cursor we need the snippet for */
   106782   Snippet *pSnippet,
   106783   const char *zStartMark,     /* Markup to appear before each match */
   106784   const char *zEndMark,       /* Markup to appear after each match */
   106785   const char *zEllipsis       /* Ellipsis mark */
   106786 ){
   106787   int i, j;
   106788   struct snippetMatch *aMatch;
   106789   int nMatch;
   106790   int nDesired;
   106791   StringBuffer sb;
   106792   int tailCol;
   106793   int tailOffset;
   106794   int iCol;
   106795   int nDoc;
   106796   const char *zDoc;
   106797   int iStart, iEnd;
   106798   int tailEllipsis = 0;
   106799   int iMatch;
   106800 
   106801 
   106802   sqlite3_free(pSnippet->zSnippet);
   106803   pSnippet->zSnippet = 0;
   106804   aMatch = pSnippet->aMatch;
   106805   nMatch = pSnippet->nMatch;
   106806   fts3SnippetSbInit(&sb);
   106807 
   106808   for(i=0; i<nMatch; i++){
   106809     aMatch[i].snStatus = SNIPPET_IGNORE;
   106810   }
   106811   nDesired = 0;
   106812   for(i=0; i<FTS3_ROTOR_SZ; i++){
   106813     for(j=0; j<nMatch; j++){
   106814       if( aMatch[j].iTerm==i ){
   106815         aMatch[j].snStatus = SNIPPET_DESIRED;
   106816         nDesired++;
   106817         break;
   106818       }
   106819     }
   106820   }
   106821 
   106822   iMatch = 0;
   106823   tailCol = -1;
   106824   tailOffset = 0;
   106825   for(i=0; i<nMatch && nDesired>0; i++){
   106826     if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
   106827     nDesired--;
   106828     iCol = aMatch[i].iCol;
   106829     zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
   106830     nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
   106831     iStart = aMatch[i].iStart - 40;
   106832     iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
   106833     if( iStart<=10 ){
   106834       iStart = 0;
   106835     }
   106836     if( iCol==tailCol && iStart<=tailOffset+20 ){
   106837       iStart = tailOffset;
   106838     }
   106839     if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
   106840       fts3SnippetTrimWhiteSpace(&sb);
   106841       fts3SnippetAppendWhiteSpace(&sb);
   106842       fts3SnippetAppend(&sb, zEllipsis, -1);
   106843       fts3SnippetAppendWhiteSpace(&sb);
   106844     }
   106845     iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
   106846     iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
   106847     if( iEnd>=nDoc-10 ){
   106848       iEnd = nDoc;
   106849       tailEllipsis = 0;
   106850     }else{
   106851       tailEllipsis = 1;
   106852     }
   106853     while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
   106854     while( iStart<iEnd ){
   106855       while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
   106856              && aMatch[iMatch].iCol<=iCol ){
   106857         iMatch++;
   106858       }
   106859       if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
   106860              && aMatch[iMatch].iCol==iCol ){
   106861         fts3SnippetAppend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
   106862         iStart = aMatch[iMatch].iStart;
   106863         fts3SnippetAppend(&sb, zStartMark, -1);
   106864         fts3SnippetAppend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
   106865         fts3SnippetAppend(&sb, zEndMark, -1);
   106866         iStart += aMatch[iMatch].nByte;
   106867         for(j=iMatch+1; j<nMatch; j++){
   106868           if( aMatch[j].iTerm==aMatch[iMatch].iTerm
   106869               && aMatch[j].snStatus==SNIPPET_DESIRED ){
   106870             nDesired--;
   106871             aMatch[j].snStatus = SNIPPET_IGNORE;
   106872           }
   106873         }
   106874       }else{
   106875         fts3SnippetAppend(&sb, &zDoc[iStart], iEnd - iStart);
   106876         iStart = iEnd;
   106877       }
   106878     }
   106879     tailCol = iCol;
   106880     tailOffset = iEnd;
   106881   }
   106882   fts3SnippetTrimWhiteSpace(&sb);
   106883   if( tailEllipsis ){
   106884     fts3SnippetAppendWhiteSpace(&sb);
   106885     fts3SnippetAppend(&sb, zEllipsis, -1);
   106886   }
   106887   pSnippet->zSnippet = sb.z;
   106888   pSnippet->nSnippet = sb.z ? sb.nUsed : 0;
   106889 }
   106890 
   106891 SQLITE_PRIVATE void sqlite3Fts3Offsets(
   106892   sqlite3_context *pCtx,          /* SQLite function call context */
   106893   Fts3Cursor *pCsr                /* Cursor object */
   106894 ){
   106895   Snippet *p;                     /* Snippet structure */
   106896   int rc = snippetAllOffsets(pCsr, &p);
   106897   if( rc==SQLITE_OK ){
   106898     snippetOffsetText(p);
   106899     if( p->zOffset ){
   106900       sqlite3_result_text(pCtx, p->zOffset, p->nOffset, SQLITE_TRANSIENT);
   106901     }else{
   106902       sqlite3_result_error_nomem(pCtx);
   106903     }
   106904   }else{
   106905     sqlite3_result_error_nomem(pCtx);
   106906   }
   106907   fts3SnippetFree(p);
   106908 }
   106909 
   106910 SQLITE_PRIVATE void sqlite3Fts3Snippet(
   106911   sqlite3_context *pCtx,          /* SQLite function call context */
   106912   Fts3Cursor *pCsr,               /* Cursor object */
   106913   const char *zStart,             /* Snippet start text - "<b>" */
   106914   const char *zEnd,               /* Snippet end text - "</b>" */
   106915   const char *zEllipsis           /* Snippet ellipsis text - "<b>...</b>" */
   106916 ){
   106917   Snippet *p;                     /* Snippet structure */
   106918   int rc = snippetAllOffsets(pCsr, &p);
   106919   if( rc==SQLITE_OK ){
   106920     snippetText(pCsr, p, zStart, zEnd, zEllipsis);
   106921     if( p->zSnippet ){
   106922       sqlite3_result_text(pCtx, p->zSnippet, p->nSnippet, SQLITE_TRANSIENT);
   106923     }else{
   106924       sqlite3_result_error_nomem(pCtx);
   106925     }
   106926   }else{
   106927     sqlite3_result_error_nomem(pCtx);
   106928   }
   106929   fts3SnippetFree(p);
   106930 }
   106931 
   106932 /*************************************************************************
   106933 ** Below this point is the alternative, experimental snippet() implementation.
   106934 */
   106935 
   106936 #define SNIPPET_BUFFER_CHUNK  64
   106937 #define SNIPPET_BUFFER_SIZE   SNIPPET_BUFFER_CHUNK*4
   106938 #define SNIPPET_BUFFER_MASK   (SNIPPET_BUFFER_SIZE-1)
   106939 
   106940 static void fts3GetDeltaPosition(char **pp, int *piPos){
   106941   int iVal;
   106942   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
   106943   *piPos += (iVal-2);
   106944 }
   106945 
   106946 /*
   106947 ** Iterate through all phrase nodes in an FTS3 query, except those that
   106948 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
   106949 ** For each phrase node found, the supplied callback function is invoked.
   106950 **
   106951 ** If the callback function returns anything other than SQLITE_OK,
   106952 ** the iteration is abandoned and the error code returned immediately.
   106953 ** Otherwise, SQLITE_OK is returned after a callback has been made for
   106954 ** all eligible phrase nodes.
   106955 */
   106956 static int fts3ExprIterate(
   106957   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
   106958   int (*x)(Fts3Expr *, void *),   /* Callback function to invoke for phrases */
   106959   void *pCtx                      /* Second argument to pass to callback */
   106960 ){
   106961   int rc;
   106962   int eType = pExpr->eType;
   106963   if( eType==FTSQUERY_NOT ){
   106964     rc = SQLITE_OK;
   106965   }else if( eType!=FTSQUERY_PHRASE ){
   106966     assert( pExpr->pLeft && pExpr->pRight );
   106967     rc = fts3ExprIterate(pExpr->pLeft, x, pCtx);
   106968     if( rc==SQLITE_OK ){
   106969       rc = fts3ExprIterate(pExpr->pRight, x, pCtx);
   106970     }
   106971   }else{
   106972     rc = x(pExpr, pCtx);
   106973   }
   106974   return rc;
   106975 }
   106976 
   106977 typedef struct LoadDoclistCtx LoadDoclistCtx;
   106978 struct LoadDoclistCtx {
   106979   Fts3Table *pTab;                /* FTS3 Table */
   106980   int nPhrase;                    /* Number of phrases so far */
   106981 };
   106982 
   106983 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, void *ctx){
   106984   int rc = SQLITE_OK;
   106985   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
   106986   p->nPhrase++;
   106987   if( pExpr->isLoaded==0 ){
   106988     rc = sqlite3Fts3ExprLoadDoclist(p->pTab, pExpr);
   106989     pExpr->isLoaded = 1;
   106990     if( rc==SQLITE_OK && pExpr->aDoclist ){
   106991       pExpr->pCurrent = pExpr->aDoclist;
   106992       pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent,&pExpr->iCurrent);
   106993     }
   106994   }
   106995   return rc;
   106996 }
   106997 
   106998 static int fts3ExprLoadDoclists(Fts3Cursor *pCsr, int *pnPhrase){
   106999   int rc;
   107000   LoadDoclistCtx sCtx = {0, 0};
   107001   sCtx.pTab = (Fts3Table *)pCsr->base.pVtab;
   107002   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
   107003   *pnPhrase = sCtx.nPhrase;
   107004   return rc;
   107005 }
   107006 
   107007 /*
   107008 ** Each call to this function populates a chunk of a snippet-buffer
   107009 ** SNIPPET_BUFFER_CHUNK bytes in size.
   107010 **
   107011 ** Return true if the end of the data has been reached (and all subsequent
   107012 ** calls to fts3LoadSnippetBuffer() with the same arguments will be no-ops),
   107013 ** or false otherwise.
   107014 */
   107015 static int fts3LoadSnippetBuffer(
   107016   int iPos,                       /* Document token offset to load data for */
   107017   u8 *aBuffer,                    /* Circular snippet buffer to populate */
   107018   int nList,                      /* Number of position lists in appList */
   107019   char **apList,                  /* IN/OUT: nList position list pointers */
   107020   int *aiPrev                     /* IN/OUT: Previous positions read */
   107021 ){
   107022   int i;
   107023   int nFin = 0;
   107024 
   107025   assert( (iPos&(SNIPPET_BUFFER_CHUNK-1))==0 );
   107026 
   107027   memset(&aBuffer[iPos&SNIPPET_BUFFER_MASK], 0, SNIPPET_BUFFER_CHUNK);
   107028 
   107029   for(i=0; i<nList; i++){
   107030     int iPrev = aiPrev[i];
   107031     char *pList = apList[i];
   107032 
   107033     if( !pList ){
   107034       nFin++;
   107035       continue;
   107036     }
   107037 
   107038     while( iPrev<(iPos+SNIPPET_BUFFER_CHUNK) ){
   107039       if( iPrev>=iPos ){
   107040         aBuffer[iPrev&SNIPPET_BUFFER_MASK] = (u8)(i+1);
   107041       }
   107042       if( 0==((*pList)&0xFE) ){
   107043         nFin++;
   107044         break;
   107045       }
   107046       fts3GetDeltaPosition(&pList, &iPrev);
   107047     }
   107048 
   107049     aiPrev[i] = iPrev;
   107050     apList[i] = pList;
   107051   }
   107052 
   107053   return (nFin==nList);
   107054 }
   107055 
   107056 typedef struct SnippetCtx SnippetCtx;
   107057 struct SnippetCtx {
   107058   Fts3Cursor *pCsr;
   107059   int iCol;
   107060   int iPhrase;
   107061   int *aiPrev;
   107062   int *anToken;
   107063   char **apList;
   107064 };
   107065 
   107066 static int fts3SnippetFindPositions(Fts3Expr *pExpr, void *ctx){
   107067   SnippetCtx *p = (SnippetCtx *)ctx;
   107068   int iPhrase = p->iPhrase++;
   107069   char *pCsr;
   107070 
   107071   p->anToken[iPhrase] = pExpr->pPhrase->nToken;
   107072   pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
   107073 
   107074   if( pCsr ){
   107075     int iVal;
   107076     pCsr += sqlite3Fts3GetVarint32(pCsr, &iVal);
   107077     p->apList[iPhrase] = pCsr;
   107078     p->aiPrev[iPhrase] = iVal-2;
   107079   }
   107080   return SQLITE_OK;
   107081 }
   107082 
   107083 static void fts3SnippetCnt(
   107084   int iIdx,
   107085   int nSnippet,
   107086   int *anCnt,
   107087   u8 *aBuffer,
   107088   int *anToken,
   107089   u64 *pHlmask
   107090 ){
   107091   int iSub =  (iIdx-1)&SNIPPET_BUFFER_MASK;
   107092   int iAdd =  (iIdx+nSnippet-1)&SNIPPET_BUFFER_MASK;
   107093   int iSub2 = (iIdx+(nSnippet/3)-1)&SNIPPET_BUFFER_MASK;
   107094   int iAdd2 = (iIdx+(nSnippet*2/3)-1)&SNIPPET_BUFFER_MASK;
   107095 
   107096   u64 h = *pHlmask;
   107097 
   107098   anCnt[ aBuffer[iSub]  ]--;
   107099   anCnt[ aBuffer[iSub2] ]--;
   107100   anCnt[ aBuffer[iAdd]  ]++;
   107101   anCnt[ aBuffer[iAdd2] ]++;
   107102 
   107103   h = h >> 1;
   107104   if( aBuffer[iAdd] ){
   107105     int j;
   107106     for(j=anToken[aBuffer[iAdd]-1]; j>=1; j--){
   107107       h |= (u64)1 << (nSnippet-j);
   107108     }
   107109   }
   107110   *pHlmask = h;
   107111 }
   107112 
   107113 static int fts3SnippetScore(int n, int *anCnt){
   107114   int j;
   107115   int iScore = 0;
   107116   for(j=1; j<=n; j++){
   107117     int nCnt = anCnt[j];
   107118     iScore += nCnt + (nCnt ? 1000 : 0);
   107119   }
   107120   return iScore;
   107121 }
   107122 
   107123 static int fts3BestSnippet(
   107124   int nSnippet,                   /* Desired snippet length */
   107125   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
   107126   int iCol,                       /* Index of column to create snippet from */
   107127   int *piPos,                     /* OUT: Starting token for best snippet */
   107128   u64 *pHlmask                    /* OUT: Highlight mask for best snippet */
   107129 ){
   107130   int rc;                         /* Return Code */
   107131   u8 aBuffer[SNIPPET_BUFFER_SIZE];/* Circular snippet buffer */
   107132   int *aiPrev;                    /* Used by fts3LoadSnippetBuffer() */
   107133   int *anToken;                   /* Number of tokens in each phrase */
   107134   char **apList;                  /* Array of position lists */
   107135   int *anCnt;                     /* Running totals of phrase occurences */
   107136   int nList;
   107137 
   107138   int i;
   107139 
   107140   u64 hlmask = 0;                 /* Current mask of highlighted terms */
   107141   u64 besthlmask = 0;             /* Mask of highlighted terms for iBestPos */
   107142   int iBestPos = 0;               /* Starting position of 'best' snippet */
   107143   int iBestScore = 0;             /* Score of best snippet higher->better */
   107144   SnippetCtx sCtx;
   107145 
   107146   /* Iterate through the phrases in the expression to count them. The same
   107147   ** callback makes sure the doclists are loaded for each phrase.
   107148   */
   107149   rc = fts3ExprLoadDoclists(pCsr, &nList);
   107150   if( rc!=SQLITE_OK ){
   107151     return rc;
   107152   }
   107153 
   107154   /* Now that it is known how many phrases there are, allocate and zero
   107155   ** the required arrays using malloc().
   107156   */
   107157   apList = sqlite3_malloc(
   107158       sizeof(u8*)*nList +         /* apList */
   107159       sizeof(int)*(nList) +       /* anToken */
   107160       sizeof(int)*nList +         /* aiPrev */
   107161       sizeof(int)*(nList+1)       /* anCnt */
   107162   );
   107163   if( !apList ){
   107164     return SQLITE_NOMEM;
   107165   }
   107166   memset(apList, 0, sizeof(u8*)*nList+sizeof(int)*nList+sizeof(int)*nList);
   107167   anToken = (int *)&apList[nList];
   107168   aiPrev = &anToken[nList];
   107169   anCnt = &aiPrev[nList];
   107170 
   107171   /* Initialize the contents of the aiPrev and aiList arrays. */
   107172   sCtx.pCsr = pCsr;
   107173   sCtx.iCol = iCol;
   107174   sCtx.apList = apList;
   107175   sCtx.aiPrev = aiPrev;
   107176   sCtx.anToken = anToken;
   107177   sCtx.iPhrase = 0;
   107178   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sCtx);
   107179 
   107180   /* Load the first two chunks of data into the buffer. */
   107181   memset(aBuffer, 0, SNIPPET_BUFFER_SIZE);
   107182   fts3LoadSnippetBuffer(0, aBuffer, nList, apList, aiPrev);
   107183   fts3LoadSnippetBuffer(SNIPPET_BUFFER_CHUNK, aBuffer, nList, apList, aiPrev);
   107184 
   107185   /* Set the initial contents of the highlight-mask and anCnt[] array. */
   107186   for(i=1-nSnippet; i<=0; i++){
   107187     fts3SnippetCnt(i, nSnippet, anCnt, aBuffer, anToken, &hlmask);
   107188   }
   107189   iBestScore = fts3SnippetScore(nList, anCnt);
   107190   besthlmask = hlmask;
   107191   iBestPos = 0;
   107192 
   107193   for(i=1; 1; i++){
   107194     int iScore;
   107195 
   107196     if( 0==(i&(SNIPPET_BUFFER_CHUNK-1)) ){
   107197       int iLoad = i + SNIPPET_BUFFER_CHUNK;
   107198       if( fts3LoadSnippetBuffer(iLoad, aBuffer, nList, apList, aiPrev) ) break;
   107199     }
   107200 
   107201     /* Figure out how highly a snippet starting at token offset i scores
   107202     ** according to fts3SnippetScore(). If it is higher than any previously
   107203     ** considered position, save the current position, score and hlmask as
   107204     ** the best snippet candidate found so far.
   107205     */
   107206     fts3SnippetCnt(i, nSnippet, anCnt, aBuffer, anToken, &hlmask);
   107207     iScore = fts3SnippetScore(nList, anCnt);
   107208     if( iScore>iBestScore ){
   107209       iBestPos = i;
   107210       iBestScore = iScore;
   107211       besthlmask = hlmask;
   107212     }
   107213   }
   107214 
   107215   sqlite3_free(apList);
   107216   *piPos = iBestPos;
   107217   *pHlmask = besthlmask;
   107218   return SQLITE_OK;
   107219 }
   107220 
   107221 typedef struct StrBuffer StrBuffer;
   107222 struct StrBuffer {
   107223   char *z;
   107224   int n;
   107225   int nAlloc;
   107226 };
   107227 
   107228 static int fts3StringAppend(
   107229   StrBuffer *pStr,
   107230   const char *zAppend,
   107231   int nAppend
   107232 ){
   107233   if( nAppend<0 ){
   107234     nAppend = (int)strlen(zAppend);
   107235   }
   107236 
   107237   if( pStr->n+nAppend+1>=pStr->nAlloc ){
   107238     int nAlloc = pStr->nAlloc+nAppend+100;
   107239     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
   107240     if( !zNew ){
   107241       return SQLITE_NOMEM;
   107242     }
   107243     pStr->z = zNew;
   107244     pStr->nAlloc = nAlloc;
   107245   }
   107246 
   107247   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
   107248   pStr->n += nAppend;
   107249   pStr->z[pStr->n] = '\0';
   107250 
   107251   return SQLITE_OK;
   107252 }
   107253 
   107254 static int fts3SnippetText(
   107255   Fts3Cursor *pCsr,               /* FTS3 Cursor */
   107256   const char *zDoc,               /* Document to extract snippet from */
   107257   int nDoc,                       /* Size of zDoc in bytes */
   107258   int nSnippet,                   /* Number of tokens in extracted snippet */
   107259   int iPos,                       /* Index of first document token in snippet */
   107260   u64 hlmask,                     /* Bitmask of terms to highlight in snippet */
   107261   const char *zOpen,              /* String inserted before highlighted term */
   107262   const char *zClose,             /* String inserted after highlighted term */
   107263   const char *zEllipsis,
   107264   char **pzSnippet                /* OUT: Snippet text */
   107265 ){
   107266   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   107267   int rc;                         /* Return code */
   107268   int iCurrent = 0;
   107269   int iStart = 0;
   107270   int iEnd;
   107271 
   107272   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
   107273   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
   107274   const char *ZDUMMY;             /* Dummy arguments used with tokenizer */
   107275   int DUMMY1, DUMMY2, DUMMY3;     /* Dummy arguments used with tokenizer */
   107276 
   107277   StrBuffer res = {0, 0, 0};   /* Result string */
   107278 
   107279   /* Open a token cursor on the document. Read all tokens up to and
   107280   ** including token iPos (the first token of the snippet). Set variable
   107281   ** iStart to the byte offset in zDoc of the start of token iPos.
   107282   */
   107283   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
   107284   rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
   107285   while( rc==SQLITE_OK && iCurrent<iPos ){
   107286     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iStart, &DUMMY2, &iCurrent);
   107287   }
   107288   iEnd = iStart;
   107289 
   107290   if( rc==SQLITE_OK && iStart>0 ){
   107291     rc = fts3StringAppend(&res, zEllipsis, -1);
   107292   }
   107293 
   107294   while( rc==SQLITE_OK ){
   107295     int iBegin;
   107296     int iFin;
   107297     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
   107298 
   107299     if( rc==SQLITE_OK ){
   107300       if( iCurrent>=(iPos+nSnippet) ){
   107301         rc = SQLITE_DONE;
   107302       }else{
   107303         iEnd = iFin;
   107304         if( hlmask & ((u64)1 << (iCurrent-iPos)) ){
   107305           if( fts3StringAppend(&res, &zDoc[iStart], iBegin-iStart)
   107306            || fts3StringAppend(&res, zOpen, -1)
   107307            || fts3StringAppend(&res, &zDoc[iBegin], iEnd-iBegin)
   107308            || fts3StringAppend(&res, zClose, -1)
   107309           ){
   107310             rc = SQLITE_NOMEM;
   107311           }
   107312           iStart = iEnd;
   107313         }
   107314       }
   107315     }
   107316   }
   107317   assert( rc!=SQLITE_OK );
   107318   if( rc==SQLITE_DONE ){
   107319     rc = fts3StringAppend(&res, &zDoc[iStart], iEnd-iStart);
   107320     if( rc==SQLITE_OK ){
   107321       rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
   107322       if( rc==SQLITE_OK ){
   107323         rc = fts3StringAppend(&res, zEllipsis, -1);
   107324       }else if( rc==SQLITE_DONE ){
   107325         rc = fts3StringAppend(&res, &zDoc[iEnd], -1);
   107326       }
   107327     }
   107328   }
   107329 
   107330   pMod->xClose(pC);
   107331   if( rc!=SQLITE_OK ){
   107332     sqlite3_free(res.z);
   107333   }else{
   107334     *pzSnippet = res.z;
   107335   }
   107336   return rc;
   107337 }
   107338 
   107339 
   107340 /*
   107341 ** An instance of this structure is used to collect the 'global' part of
   107342 ** the matchinfo statistics. The 'global' part consists of the following:
   107343 **
   107344 **   1. The number of phrases in the query (nPhrase).
   107345 **
   107346 **   2. The number of columns in the FTS3 table (nCol).
   107347 **
   107348 **   3. A matrix of (nPhrase*nCol) integers containing the sum of the
   107349 **      number of hits for each phrase in each column across all rows
   107350 **      of the table.
   107351 **
   107352 ** The total size of the global matchinfo array, assuming the number of
   107353 ** columns is N and the number of phrases is P is:
   107354 **
   107355 **   2 + P*(N+1)
   107356 **
   107357 ** The number of hits for the 3rd phrase in the second column is found
   107358 ** using the expression:
   107359 **
   107360 **   aGlobal[2 + P*(1+2) + 1]
   107361 */
   107362 typedef struct MatchInfo MatchInfo;
   107363 struct MatchInfo {
   107364   Fts3Table *pTab;                /* FTS3 Table */
   107365   Fts3Cursor *pCursor;            /* FTS3 Cursor */
   107366   int iPhrase;                    /* Number of phrases so far */
   107367   int nCol;                       /* Number of columns in table */
   107368   u32 *aGlobal;                   /* Pre-allocated buffer */
   107369 };
   107370 
   107371 /*
   107372 ** This function is used to count the entries in a column-list (delta-encoded
   107373 ** list of term offsets within a single column of a single row).
   107374 */
   107375 static int fts3ColumnlistCount(char **ppCollist){
   107376   char *pEnd = *ppCollist;
   107377   char c = 0;
   107378   int nEntry = 0;
   107379 
   107380   /* A column-list is terminated by either a 0x01 or 0x00. */
   107381   while( 0xFE & (*pEnd | c) ){
   107382     c = *pEnd++ & 0x80;
   107383     if( !c ) nEntry++;
   107384   }
   107385 
   107386   *ppCollist = pEnd;
   107387   return nEntry;
   107388 }
   107389 
   107390 static void fts3LoadColumnlistCounts(char **pp, u32 *aOut){
   107391   char *pCsr = *pp;
   107392   while( *pCsr ){
   107393     sqlite3_int64 iCol = 0;
   107394     if( *pCsr==0x01 ){
   107395       pCsr++;
   107396       pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
   107397     }
   107398     aOut[iCol] += fts3ColumnlistCount(&pCsr);
   107399   }
   107400   pCsr++;
   107401   *pp = pCsr;
   107402 }
   107403 
   107404 /*
   107405 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
   107406 ** for a single query.
   107407 */
   107408 static int fts3ExprGlobalMatchinfoCb(
   107409   Fts3Expr *pExpr,                /* Phrase expression node */
   107410   void *pCtx                      /* Pointer to MatchInfo structure */
   107411 ){
   107412   MatchInfo *p = (MatchInfo *)pCtx;
   107413   char *pCsr;
   107414   char *pEnd;
   107415   const int iStart = 2 + p->nCol*p->iPhrase;
   107416 
   107417   assert( pExpr->isLoaded );
   107418 
   107419   /* Fill in the global hit count matrix row for this phrase. */
   107420   pCsr = pExpr->aDoclist;
   107421   pEnd = &pExpr->aDoclist[pExpr->nDoclist];
   107422   while( pCsr<pEnd ){
   107423     while( *pCsr++ & 0x80 );
   107424     fts3LoadColumnlistCounts(&pCsr, &p->aGlobal[iStart]);
   107425   }
   107426 
   107427   p->iPhrase++;
   107428   return SQLITE_OK;
   107429 }
   107430 
   107431 static int fts3ExprLocalMatchinfoCb(
   107432   Fts3Expr *pExpr,                /* Phrase expression node */
   107433   void *pCtx                      /* Pointer to MatchInfo structure */
   107434 ){
   107435   MatchInfo *p = (MatchInfo *)pCtx;
   107436   int iPhrase = p->iPhrase++;
   107437 
   107438   if( pExpr->aDoclist ){
   107439     char *pCsr;
   107440     int iOffset = 2 + p->nCol*(p->aGlobal[0]+iPhrase);
   107441 
   107442     memset(&p->aGlobal[iOffset], 0, p->nCol*sizeof(u32));
   107443     pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
   107444     if( pCsr ) fts3LoadColumnlistCounts(&pCsr, &p->aGlobal[iOffset]);
   107445   }
   107446 
   107447   return SQLITE_OK;
   107448 }
   107449 
   107450 /*
   107451 ** Populate pCsr->aMatchinfo[] with data for the current row. The 'matchinfo'
   107452 ** data is an array of 32-bit unsigned integers (C type u32).
   107453 */
   107454 static int fts3GetMatchinfo(Fts3Cursor *pCsr){
   107455   MatchInfo g;
   107456   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   107457   if( pCsr->aMatchinfo==0 ){
   107458     int rc;
   107459     int nPhrase;
   107460     int nMatchinfo;
   107461 
   107462     g.pTab = pTab;
   107463     g.nCol = pTab->nColumn;
   107464     g.iPhrase = 0;
   107465     rc = fts3ExprLoadDoclists(pCsr, &nPhrase);
   107466     if( rc!=SQLITE_OK ){
   107467       return rc;
   107468     }
   107469 
   107470     nMatchinfo = 2 + 2*g.nCol*nPhrase;
   107471 
   107472     g.iPhrase = 0;
   107473     g.aGlobal = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo);
   107474     if( !g.aGlobal ){
   107475       return SQLITE_NOMEM;
   107476     }
   107477     memset(g.aGlobal, 0, sizeof(u32)*nMatchinfo);
   107478 
   107479     g.aGlobal[0] = nPhrase;
   107480     g.aGlobal[1] = g.nCol;
   107481     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprGlobalMatchinfoCb, (void *)&g);
   107482 
   107483     pCsr->aMatchinfo = g.aGlobal;
   107484   }
   107485 
   107486   g.pTab = pTab;
   107487   g.pCursor = pCsr;
   107488   g.nCol = pTab->nColumn;
   107489   g.iPhrase = 0;
   107490   g.aGlobal = pCsr->aMatchinfo;
   107491 
   107492   if( pCsr->isMatchinfoOk ){
   107493     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLocalMatchinfoCb, (void *)&g);
   107494     pCsr->isMatchinfoOk = 0;
   107495   }
   107496 
   107497   return SQLITE_OK;
   107498 }
   107499 
   107500 SQLITE_PRIVATE void sqlite3Fts3Snippet2(
   107501   sqlite3_context *pCtx,          /* SQLite function call context */
   107502   Fts3Cursor *pCsr,               /* Cursor object */
   107503   const char *zStart,             /* Snippet start text - "<b>" */
   107504   const char *zEnd,               /* Snippet end text - "</b>" */
   107505   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
   107506   int iCol,                       /* Extract snippet from this column */
   107507   int nToken                      /* Approximate number of tokens in snippet */
   107508 ){
   107509   int rc;
   107510   int iPos = 0;
   107511   u64 hlmask = 0;
   107512   char *z = 0;
   107513   int nDoc;
   107514   const char *zDoc;
   107515 
   107516   rc = fts3BestSnippet(nToken, pCsr, iCol, &iPos, &hlmask);
   107517 
   107518   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
   107519   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
   107520 
   107521   if( rc==SQLITE_OK ){
   107522     rc = fts3SnippetText(
   107523         pCsr, zDoc, nDoc, nToken, iPos, hlmask, zStart, zEnd, zEllipsis, &z);
   107524   }
   107525   if( rc!=SQLITE_OK ){
   107526     sqlite3_result_error_code(pCtx, rc);
   107527   }else{
   107528     sqlite3_result_text(pCtx, z, -1, sqlite3_free);
   107529   }
   107530 }
   107531 
   107532 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *pContext, Fts3Cursor *pCsr){
   107533   int rc = fts3GetMatchinfo(pCsr);
   107534   if( rc!=SQLITE_OK ){
   107535     sqlite3_result_error_code(pContext, rc);
   107536   }else{
   107537     int n = sizeof(u32)*(2+pCsr->aMatchinfo[0]*pCsr->aMatchinfo[1]*2);
   107538     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
   107539   }
   107540 }
   107541 
   107542 #endif
   107543 
   107544 /************** End of fts3_snippet.c ****************************************/
   107545 /************** Begin file rtree.c *******************************************/
   107546 /*
   107547 ** 2001 September 15
   107548 **
   107549 ** The author disclaims copyright to this source code.  In place of
   107550 ** a legal notice, here is a blessing:
   107551 **
   107552 **    May you do good and not evil.
   107553 **    May you find forgiveness for yourself and forgive others.
   107554 **    May you share freely, never taking more than you give.
   107555 **
   107556 *************************************************************************
   107557 ** This file contains code for implementations of the r-tree and r*-tree
   107558 ** algorithms packaged as an SQLite virtual table module.
   107559 */
   107560 
   107561 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
   107562 
   107563 /*
   107564 ** This file contains an implementation of a couple of different variants
   107565 ** of the r-tree algorithm. See the README file for further details. The
   107566 ** same data-structure is used for all, but the algorithms for insert and
   107567 ** delete operations vary. The variants used are selected at compile time
   107568 ** by defining the following symbols:
   107569 */
   107570 
   107571 /* Either, both or none of the following may be set to activate
   107572 ** r*tree variant algorithms.
   107573 */
   107574 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
   107575 #define VARIANT_RSTARTREE_REINSERT      1
   107576 
   107577 /*
   107578 ** Exactly one of the following must be set to 1.
   107579 */
   107580 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
   107581 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
   107582 #define VARIANT_RSTARTREE_SPLIT         1
   107583 
   107584 #define VARIANT_GUTTMAN_SPLIT \
   107585         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
   107586 
   107587 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
   107588   #define PickNext QuadraticPickNext
   107589   #define PickSeeds QuadraticPickSeeds
   107590   #define AssignCells splitNodeGuttman
   107591 #endif
   107592 #if VARIANT_GUTTMAN_LINEAR_SPLIT
   107593   #define PickNext LinearPickNext
   107594   #define PickSeeds LinearPickSeeds
   107595   #define AssignCells splitNodeGuttman
   107596 #endif
   107597 #if VARIANT_RSTARTREE_SPLIT
   107598   #define AssignCells splitNodeStartree
   107599 #endif
   107600 
   107601 
   107602 #ifndef SQLITE_CORE
   107603   SQLITE_EXTENSION_INIT1
   107604 #else
   107605 #endif
   107606 
   107607 
   107608 #ifndef SQLITE_AMALGAMATION
   107609 typedef sqlite3_int64 i64;
   107610 typedef unsigned char u8;
   107611 typedef unsigned int u32;
   107612 #endif
   107613 
   107614 typedef struct Rtree Rtree;
   107615 typedef struct RtreeCursor RtreeCursor;
   107616 typedef struct RtreeNode RtreeNode;
   107617 typedef struct RtreeCell RtreeCell;
   107618 typedef struct RtreeConstraint RtreeConstraint;
   107619 typedef union RtreeCoord RtreeCoord;
   107620 
   107621 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
   107622 #define RTREE_MAX_DIMENSIONS 5
   107623 
   107624 /* Size of hash table Rtree.aHash. This hash table is not expected to
   107625 ** ever contain very many entries, so a fixed number of buckets is
   107626 ** used.
   107627 */
   107628 #define HASHSIZE 128
   107629 
   107630 /*
   107631 ** An rtree virtual-table object.
   107632 */
   107633 struct Rtree {
   107634   sqlite3_vtab base;
   107635   sqlite3 *db;                /* Host database connection */
   107636   int iNodeSize;              /* Size in bytes of each node in the node table */
   107637   int nDim;                   /* Number of dimensions */
   107638   int nBytesPerCell;          /* Bytes consumed per cell */
   107639   int iDepth;                 /* Current depth of the r-tree structure */
   107640   char *zDb;                  /* Name of database containing r-tree table */
   107641   char *zName;                /* Name of r-tree table */
   107642   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
   107643   int nBusy;                  /* Current number of users of this structure */
   107644 
   107645   /* List of nodes removed during a CondenseTree operation. List is
   107646   ** linked together via the pointer normally used for hash chains -
   107647   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
   107648   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
   107649   */
   107650   RtreeNode *pDeleted;
   107651   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
   107652 
   107653   /* Statements to read/write/delete a record from xxx_node */
   107654   sqlite3_stmt *pReadNode;
   107655   sqlite3_stmt *pWriteNode;
   107656   sqlite3_stmt *pDeleteNode;
   107657 
   107658   /* Statements to read/write/delete a record from xxx_rowid */
   107659   sqlite3_stmt *pReadRowid;
   107660   sqlite3_stmt *pWriteRowid;
   107661   sqlite3_stmt *pDeleteRowid;
   107662 
   107663   /* Statements to read/write/delete a record from xxx_parent */
   107664   sqlite3_stmt *pReadParent;
   107665   sqlite3_stmt *pWriteParent;
   107666   sqlite3_stmt *pDeleteParent;
   107667 
   107668   int eCoordType;
   107669 };
   107670 
   107671 /* Possible values for eCoordType: */
   107672 #define RTREE_COORD_REAL32 0
   107673 #define RTREE_COORD_INT32  1
   107674 
   107675 /*
   107676 ** The minimum number of cells allowed for a node is a third of the
   107677 ** maximum. In Gutman's notation:
   107678 **
   107679 **     m = M/3
   107680 **
   107681 ** If an R*-tree "Reinsert" operation is required, the same number of
   107682 ** cells are removed from the overfull node and reinserted into the tree.
   107683 */
   107684 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
   107685 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
   107686 #define RTREE_MAXCELLS 51
   107687 
   107688 /*
   107689 ** An rtree cursor object.
   107690 */
   107691 struct RtreeCursor {
   107692   sqlite3_vtab_cursor base;
   107693   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
   107694   int iCell;                        /* Index of current cell in pNode */
   107695   int iStrategy;                    /* Copy of idxNum search parameter */
   107696   int nConstraint;                  /* Number of entries in aConstraint */
   107697   RtreeConstraint *aConstraint;     /* Search constraints. */
   107698 };
   107699 
   107700 union RtreeCoord {
   107701   float f;
   107702   int i;
   107703 };
   107704 
   107705 /*
   107706 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
   107707 ** formatted as a double. This macro assumes that local variable pRtree points
   107708 ** to the Rtree structure associated with the RtreeCoord.
   107709 */
   107710 #define DCOORD(coord) (                           \
   107711   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
   107712     ((double)coord.f) :                           \
   107713     ((double)coord.i)                             \
   107714 )
   107715 
   107716 /*
   107717 ** A search constraint.
   107718 */
   107719 struct RtreeConstraint {
   107720   int iCoord;                       /* Index of constrained coordinate */
   107721   int op;                           /* Constraining operation */
   107722   double rValue;                    /* Constraint value. */
   107723 };
   107724 
   107725 /* Possible values for RtreeConstraint.op */
   107726 #define RTREE_EQ 0x41
   107727 #define RTREE_LE 0x42
   107728 #define RTREE_LT 0x43
   107729 #define RTREE_GE 0x44
   107730 #define RTREE_GT 0x45
   107731 
   107732 /*
   107733 ** An rtree structure node.
   107734 **
   107735 ** Data format (RtreeNode.zData):
   107736 **
   107737 **   1. If the node is the root node (node 1), then the first 2 bytes
   107738 **      of the node contain the tree depth as a big-endian integer.
   107739 **      For non-root nodes, the first 2 bytes are left unused.
   107740 **
   107741 **   2. The next 2 bytes contain the number of entries currently
   107742 **      stored in the node.
   107743 **
   107744 **   3. The remainder of the node contains the node entries. Each entry
   107745 **      consists of a single 8-byte integer followed by an even number
   107746 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
   107747 **      of a record. For internal nodes it is the node number of a
   107748 **      child page.
   107749 */
   107750 struct RtreeNode {
   107751   RtreeNode *pParent;               /* Parent node */
   107752   i64 iNode;
   107753   int nRef;
   107754   int isDirty;
   107755   u8 *zData;
   107756   RtreeNode *pNext;                 /* Next node in this hash chain */
   107757 };
   107758 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
   107759 
   107760 /*
   107761 ** Structure to store a deserialized rtree record.
   107762 */
   107763 struct RtreeCell {
   107764   i64 iRowid;
   107765   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
   107766 };
   107767 
   107768 #ifndef MAX
   107769 # define MAX(x,y) ((x) < (y) ? (y) : (x))
   107770 #endif
   107771 #ifndef MIN
   107772 # define MIN(x,y) ((x) > (y) ? (y) : (x))
   107773 #endif
   107774 
   107775 /*
   107776 ** Functions to deserialize a 16 bit integer, 32 bit real number and
   107777 ** 64 bit integer. The deserialized value is returned.
   107778 */
   107779 static int readInt16(u8 *p){
   107780   return (p[0]<<8) + p[1];
   107781 }
   107782 static void readCoord(u8 *p, RtreeCoord *pCoord){
   107783   u32 i = (
   107784     (((u32)p[0]) << 24) +
   107785     (((u32)p[1]) << 16) +
   107786     (((u32)p[2]) <<  8) +
   107787     (((u32)p[3]) <<  0)
   107788   );
   107789   *(u32 *)pCoord = i;
   107790 }
   107791 static i64 readInt64(u8 *p){
   107792   return (
   107793     (((i64)p[0]) << 56) +
   107794     (((i64)p[1]) << 48) +
   107795     (((i64)p[2]) << 40) +
   107796     (((i64)p[3]) << 32) +
   107797     (((i64)p[4]) << 24) +
   107798     (((i64)p[5]) << 16) +
   107799     (((i64)p[6]) <<  8) +
   107800     (((i64)p[7]) <<  0)
   107801   );
   107802 }
   107803 
   107804 /*
   107805 ** Functions to serialize a 16 bit integer, 32 bit real number and
   107806 ** 64 bit integer. The value returned is the number of bytes written
   107807 ** to the argument buffer (always 2, 4 and 8 respectively).
   107808 */
   107809 static int writeInt16(u8 *p, int i){
   107810   p[0] = (i>> 8)&0xFF;
   107811   p[1] = (i>> 0)&0xFF;
   107812   return 2;
   107813 }
   107814 static int writeCoord(u8 *p, RtreeCoord *pCoord){
   107815   u32 i;
   107816   assert( sizeof(RtreeCoord)==4 );
   107817   assert( sizeof(u32)==4 );
   107818   i = *(u32 *)pCoord;
   107819   p[0] = (i>>24)&0xFF;
   107820   p[1] = (i>>16)&0xFF;
   107821   p[2] = (i>> 8)&0xFF;
   107822   p[3] = (i>> 0)&0xFF;
   107823   return 4;
   107824 }
   107825 static int writeInt64(u8 *p, i64 i){
   107826   p[0] = (i>>56)&0xFF;
   107827   p[1] = (i>>48)&0xFF;
   107828   p[2] = (i>>40)&0xFF;
   107829   p[3] = (i>>32)&0xFF;
   107830   p[4] = (i>>24)&0xFF;
   107831   p[5] = (i>>16)&0xFF;
   107832   p[6] = (i>> 8)&0xFF;
   107833   p[7] = (i>> 0)&0xFF;
   107834   return 8;
   107835 }
   107836 
   107837 /*
   107838 ** Increment the reference count of node p.
   107839 */
   107840 static void nodeReference(RtreeNode *p){
   107841   if( p ){
   107842     p->nRef++;
   107843   }
   107844 }
   107845 
   107846 /*
   107847 ** Clear the content of node p (set all bytes to 0x00).
   107848 */
   107849 static void nodeZero(Rtree *pRtree, RtreeNode *p){
   107850   if( p ){
   107851     memset(&p->zData[2], 0, pRtree->iNodeSize-2);
   107852     p->isDirty = 1;
   107853   }
   107854 }
   107855 
   107856 /*
   107857 ** Given a node number iNode, return the corresponding key to use
   107858 ** in the Rtree.aHash table.
   107859 */
   107860 static int nodeHash(i64 iNode){
   107861   return (
   107862     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
   107863     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
   107864   ) % HASHSIZE;
   107865 }
   107866 
   107867 /*
   107868 ** Search the node hash table for node iNode. If found, return a pointer
   107869 ** to it. Otherwise, return 0.
   107870 */
   107871 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
   107872   RtreeNode *p;
   107873   assert( iNode!=0 );
   107874   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
   107875   return p;
   107876 }
   107877 
   107878 /*
   107879 ** Add node pNode to the node hash table.
   107880 */
   107881 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
   107882   if( pNode ){
   107883     int iHash;
   107884     assert( pNode->pNext==0 );
   107885     iHash = nodeHash(pNode->iNode);
   107886     pNode->pNext = pRtree->aHash[iHash];
   107887     pRtree->aHash[iHash] = pNode;
   107888   }
   107889 }
   107890 
   107891 /*
   107892 ** Remove node pNode from the node hash table.
   107893 */
   107894 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
   107895   RtreeNode **pp;
   107896   if( pNode->iNode!=0 ){
   107897     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
   107898     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
   107899     *pp = pNode->pNext;
   107900     pNode->pNext = 0;
   107901   }
   107902 }
   107903 
   107904 /*
   107905 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
   107906 ** indicating that node has not yet been assigned a node number. It is
   107907 ** assigned a node number when nodeWrite() is called to write the
   107908 ** node contents out to the database.
   107909 */
   107910 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
   107911   RtreeNode *pNode;
   107912   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
   107913   if( pNode ){
   107914     memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
   107915     pNode->zData = (u8 *)&pNode[1];
   107916     pNode->nRef = 1;
   107917     pNode->pParent = pParent;
   107918     pNode->isDirty = 1;
   107919     nodeReference(pParent);
   107920   }
   107921   return pNode;
   107922 }
   107923 
   107924 /*
   107925 ** Obtain a reference to an r-tree node.
   107926 */
   107927 static int
   107928 nodeAcquire(
   107929   Rtree *pRtree,             /* R-tree structure */
   107930   i64 iNode,                 /* Node number to load */
   107931   RtreeNode *pParent,        /* Either the parent node or NULL */
   107932   RtreeNode **ppNode         /* OUT: Acquired node */
   107933 ){
   107934   int rc;
   107935   RtreeNode *pNode;
   107936 
   107937   /* Check if the requested node is already in the hash table. If so,
   107938   ** increase its reference count and return it.
   107939   */
   107940   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
   107941     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
   107942     if( pParent && !pNode->pParent ){
   107943       nodeReference(pParent);
   107944       pNode->pParent = pParent;
   107945     }
   107946     pNode->nRef++;
   107947     *ppNode = pNode;
   107948     return SQLITE_OK;
   107949   }
   107950 
   107951   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
   107952   if( !pNode ){
   107953     *ppNode = 0;
   107954     return SQLITE_NOMEM;
   107955   }
   107956   pNode->pParent = pParent;
   107957   pNode->zData = (u8 *)&pNode[1];
   107958   pNode->nRef = 1;
   107959   pNode->iNode = iNode;
   107960   pNode->isDirty = 0;
   107961   pNode->pNext = 0;
   107962 
   107963   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
   107964   rc = sqlite3_step(pRtree->pReadNode);
   107965   if( rc==SQLITE_ROW ){
   107966     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
   107967     memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
   107968     nodeReference(pParent);
   107969   }else{
   107970     sqlite3_free(pNode);
   107971     pNode = 0;
   107972   }
   107973 
   107974   *ppNode = pNode;
   107975   rc = sqlite3_reset(pRtree->pReadNode);
   107976 
   107977   if( rc==SQLITE_OK && iNode==1 ){
   107978     pRtree->iDepth = readInt16(pNode->zData);
   107979   }
   107980 
   107981   assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
   107982   nodeHashInsert(pRtree, pNode);
   107983 
   107984   return rc;
   107985 }
   107986 
   107987 /*
   107988 ** Overwrite cell iCell of node pNode with the contents of pCell.
   107989 */
   107990 static void nodeOverwriteCell(
   107991   Rtree *pRtree,
   107992   RtreeNode *pNode,
   107993   RtreeCell *pCell,
   107994   int iCell
   107995 ){
   107996   int ii;
   107997   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
   107998   p += writeInt64(p, pCell->iRowid);
   107999   for(ii=0; ii<(pRtree->nDim*2); ii++){
   108000     p += writeCoord(p, &pCell->aCoord[ii]);
   108001   }
   108002   pNode->isDirty = 1;
   108003 }
   108004 
   108005 /*
   108006 ** Remove cell the cell with index iCell from node pNode.
   108007 */
   108008 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
   108009   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
   108010   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
   108011   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
   108012   memmove(pDst, pSrc, nByte);
   108013   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
   108014   pNode->isDirty = 1;
   108015 }
   108016 
   108017 /*
   108018 ** Insert the contents of cell pCell into node pNode. If the insert
   108019 ** is successful, return SQLITE_OK.
   108020 **
   108021 ** If there is not enough free space in pNode, return SQLITE_FULL.
   108022 */
   108023 static int
   108024 nodeInsertCell(
   108025   Rtree *pRtree,
   108026   RtreeNode *pNode,
   108027   RtreeCell *pCell
   108028 ){
   108029   int nCell;                    /* Current number of cells in pNode */
   108030   int nMaxCell;                 /* Maximum number of cells for pNode */
   108031 
   108032   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
   108033   nCell = NCELL(pNode);
   108034 
   108035   assert(nCell<=nMaxCell);
   108036 
   108037   if( nCell<nMaxCell ){
   108038     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
   108039     writeInt16(&pNode->zData[2], nCell+1);
   108040     pNode->isDirty = 1;
   108041   }
   108042 
   108043   return (nCell==nMaxCell);
   108044 }
   108045 
   108046 /*
   108047 ** If the node is dirty, write it out to the database.
   108048 */
   108049 static int
   108050 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
   108051   int rc = SQLITE_OK;
   108052   if( pNode->isDirty ){
   108053     sqlite3_stmt *p = pRtree->pWriteNode;
   108054     if( pNode->iNode ){
   108055       sqlite3_bind_int64(p, 1, pNode->iNode);
   108056     }else{
   108057       sqlite3_bind_null(p, 1);
   108058     }
   108059     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
   108060     sqlite3_step(p);
   108061     pNode->isDirty = 0;
   108062     rc = sqlite3_reset(p);
   108063     if( pNode->iNode==0 && rc==SQLITE_OK ){
   108064       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
   108065       nodeHashInsert(pRtree, pNode);
   108066     }
   108067   }
   108068   return rc;
   108069 }
   108070 
   108071 /*
   108072 ** Release a reference to a node. If the node is dirty and the reference
   108073 ** count drops to zero, the node data is written to the database.
   108074 */
   108075 static int
   108076 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
   108077   int rc = SQLITE_OK;
   108078   if( pNode ){
   108079     assert( pNode->nRef>0 );
   108080     pNode->nRef--;
   108081     if( pNode->nRef==0 ){
   108082       if( pNode->iNode==1 ){
   108083         pRtree->iDepth = -1;
   108084       }
   108085       if( pNode->pParent ){
   108086         rc = nodeRelease(pRtree, pNode->pParent);
   108087       }
   108088       if( rc==SQLITE_OK ){
   108089         rc = nodeWrite(pRtree, pNode);
   108090       }
   108091       nodeHashDelete(pRtree, pNode);
   108092       sqlite3_free(pNode);
   108093     }
   108094   }
   108095   return rc;
   108096 }
   108097 
   108098 /*
   108099 ** Return the 64-bit integer value associated with cell iCell of
   108100 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
   108101 ** an internal node, then the 64-bit integer is a child page number.
   108102 */
   108103 static i64 nodeGetRowid(
   108104   Rtree *pRtree,
   108105   RtreeNode *pNode,
   108106   int iCell
   108107 ){
   108108   assert( iCell<NCELL(pNode) );
   108109   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
   108110 }
   108111 
   108112 /*
   108113 ** Return coordinate iCoord from cell iCell in node pNode.
   108114 */
   108115 static void nodeGetCoord(
   108116   Rtree *pRtree,
   108117   RtreeNode *pNode,
   108118   int iCell,
   108119   int iCoord,
   108120   RtreeCoord *pCoord           /* Space to write result to */
   108121 ){
   108122   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
   108123 }
   108124 
   108125 /*
   108126 ** Deserialize cell iCell of node pNode. Populate the structure pointed
   108127 ** to by pCell with the results.
   108128 */
   108129 static void nodeGetCell(
   108130   Rtree *pRtree,
   108131   RtreeNode *pNode,
   108132   int iCell,
   108133   RtreeCell *pCell
   108134 ){
   108135   int ii;
   108136   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
   108137   for(ii=0; ii<pRtree->nDim*2; ii++){
   108138     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
   108139   }
   108140 }
   108141 
   108142 
   108143 /* Forward declaration for the function that does the work of
   108144 ** the virtual table module xCreate() and xConnect() methods.
   108145 */
   108146 static int rtreeInit(
   108147   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
   108148 );
   108149 
   108150 /*
   108151 ** Rtree virtual table module xCreate method.
   108152 */
   108153 static int rtreeCreate(
   108154   sqlite3 *db,
   108155   void *pAux,
   108156   int argc, const char *const*argv,
   108157   sqlite3_vtab **ppVtab,
   108158   char **pzErr
   108159 ){
   108160   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
   108161 }
   108162 
   108163 /*
   108164 ** Rtree virtual table module xConnect method.
   108165 */
   108166 static int rtreeConnect(
   108167   sqlite3 *db,
   108168   void *pAux,
   108169   int argc, const char *const*argv,
   108170   sqlite3_vtab **ppVtab,
   108171   char **pzErr
   108172 ){
   108173   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
   108174 }
   108175 
   108176 /*
   108177 ** Increment the r-tree reference count.
   108178 */
   108179 static void rtreeReference(Rtree *pRtree){
   108180   pRtree->nBusy++;
   108181 }
   108182 
   108183 /*
   108184 ** Decrement the r-tree reference count. When the reference count reaches
   108185 ** zero the structure is deleted.
   108186 */
   108187 static void rtreeRelease(Rtree *pRtree){
   108188   pRtree->nBusy--;
   108189   if( pRtree->nBusy==0 ){
   108190     sqlite3_finalize(pRtree->pReadNode);
   108191     sqlite3_finalize(pRtree->pWriteNode);
   108192     sqlite3_finalize(pRtree->pDeleteNode);
   108193     sqlite3_finalize(pRtree->pReadRowid);
   108194     sqlite3_finalize(pRtree->pWriteRowid);
   108195     sqlite3_finalize(pRtree->pDeleteRowid);
   108196     sqlite3_finalize(pRtree->pReadParent);
   108197     sqlite3_finalize(pRtree->pWriteParent);
   108198     sqlite3_finalize(pRtree->pDeleteParent);
   108199     sqlite3_free(pRtree);
   108200   }
   108201 }
   108202 
   108203 /*
   108204 ** Rtree virtual table module xDisconnect method.
   108205 */
   108206 static int rtreeDisconnect(sqlite3_vtab *pVtab){
   108207   rtreeRelease((Rtree *)pVtab);
   108208   return SQLITE_OK;
   108209 }
   108210 
   108211 /*
   108212 ** Rtree virtual table module xDestroy method.
   108213 */
   108214 static int rtreeDestroy(sqlite3_vtab *pVtab){
   108215   Rtree *pRtree = (Rtree *)pVtab;
   108216   int rc;
   108217   char *zCreate = sqlite3_mprintf(
   108218     "DROP TABLE '%q'.'%q_node';"
   108219     "DROP TABLE '%q'.'%q_rowid';"
   108220     "DROP TABLE '%q'.'%q_parent';",
   108221     pRtree->zDb, pRtree->zName,
   108222     pRtree->zDb, pRtree->zName,
   108223     pRtree->zDb, pRtree->zName
   108224   );
   108225   if( !zCreate ){
   108226     rc = SQLITE_NOMEM;
   108227   }else{
   108228     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
   108229     sqlite3_free(zCreate);
   108230   }
   108231   if( rc==SQLITE_OK ){
   108232     rtreeRelease(pRtree);
   108233   }
   108234 
   108235   return rc;
   108236 }
   108237 
   108238 /*
   108239 ** Rtree virtual table module xOpen method.
   108240 */
   108241 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
   108242   int rc = SQLITE_NOMEM;
   108243   RtreeCursor *pCsr;
   108244 
   108245   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
   108246   if( pCsr ){
   108247     memset(pCsr, 0, sizeof(RtreeCursor));
   108248     pCsr->base.pVtab = pVTab;
   108249     rc = SQLITE_OK;
   108250   }
   108251   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
   108252 
   108253   return rc;
   108254 }
   108255 
   108256 /*
   108257 ** Rtree virtual table module xClose method.
   108258 */
   108259 static int rtreeClose(sqlite3_vtab_cursor *cur){
   108260   Rtree *pRtree = (Rtree *)(cur->pVtab);
   108261   int rc;
   108262   RtreeCursor *pCsr = (RtreeCursor *)cur;
   108263   sqlite3_free(pCsr->aConstraint);
   108264   rc = nodeRelease(pRtree, pCsr->pNode);
   108265   sqlite3_free(pCsr);
   108266   return rc;
   108267 }
   108268 
   108269 /*
   108270 ** Rtree virtual table module xEof method.
   108271 **
   108272 ** Return non-zero if the cursor does not currently point to a valid
   108273 ** record (i.e if the scan has finished), or zero otherwise.
   108274 */
   108275 static int rtreeEof(sqlite3_vtab_cursor *cur){
   108276   RtreeCursor *pCsr = (RtreeCursor *)cur;
   108277   return (pCsr->pNode==0);
   108278 }
   108279 
   108280 /*
   108281 ** Cursor pCursor currently points to a cell in a non-leaf page.
   108282 ** Return true if the sub-tree headed by the cell is filtered
   108283 ** (excluded) by the constraints in the pCursor->aConstraint[]
   108284 ** array, or false otherwise.
   108285 */
   108286 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
   108287   RtreeCell cell;
   108288   int ii;
   108289   int bRes = 0;
   108290 
   108291   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
   108292   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
   108293     RtreeConstraint *p = &pCursor->aConstraint[ii];
   108294     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
   108295     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
   108296 
   108297     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
   108298         || p->op==RTREE_GT || p->op==RTREE_EQ
   108299     );
   108300 
   108301     switch( p->op ){
   108302       case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
   108303       case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
   108304       case RTREE_EQ:
   108305         bRes = (p->rValue>cell_max || p->rValue<cell_min);
   108306         break;
   108307     }
   108308   }
   108309 
   108310   return bRes;
   108311 }
   108312 
   108313 /*
   108314 ** Return true if the cell that cursor pCursor currently points to
   108315 ** would be filtered (excluded) by the constraints in the
   108316 ** pCursor->aConstraint[] array, or false otherwise.
   108317 **
   108318 ** This function assumes that the cell is part of a leaf node.
   108319 */
   108320 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
   108321   RtreeCell cell;
   108322   int ii;
   108323 
   108324   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
   108325   for(ii=0; ii<pCursor->nConstraint; ii++){
   108326     RtreeConstraint *p = &pCursor->aConstraint[ii];
   108327     double coord = DCOORD(cell.aCoord[p->iCoord]);
   108328     int res;
   108329     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
   108330         || p->op==RTREE_GT || p->op==RTREE_EQ
   108331     );
   108332     switch( p->op ){
   108333       case RTREE_LE: res = (coord<=p->rValue); break;
   108334       case RTREE_LT: res = (coord<p->rValue);  break;
   108335       case RTREE_GE: res = (coord>=p->rValue); break;
   108336       case RTREE_GT: res = (coord>p->rValue);  break;
   108337       case RTREE_EQ: res = (coord==p->rValue); break;
   108338     }
   108339 
   108340     if( !res ) return 1;
   108341   }
   108342 
   108343   return 0;
   108344 }
   108345 
   108346 /*
   108347 ** Cursor pCursor currently points at a node that heads a sub-tree of
   108348 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
   108349 ** to point to the left-most cell of the sub-tree that matches the
   108350 ** configured constraints.
   108351 */
   108352 static int descendToCell(
   108353   Rtree *pRtree,
   108354   RtreeCursor *pCursor,
   108355   int iHeight,
   108356   int *pEof                 /* OUT: Set to true if cannot descend */
   108357 ){
   108358   int isEof;
   108359   int rc;
   108360   int ii;
   108361   RtreeNode *pChild;
   108362   sqlite3_int64 iRowid;
   108363 
   108364   RtreeNode *pSavedNode = pCursor->pNode;
   108365   int iSavedCell = pCursor->iCell;
   108366 
   108367   assert( iHeight>=0 );
   108368 
   108369   if( iHeight==0 ){
   108370     isEof = testRtreeEntry(pRtree, pCursor);
   108371   }else{
   108372     isEof = testRtreeCell(pRtree, pCursor);
   108373   }
   108374   if( isEof || iHeight==0 ){
   108375     *pEof = isEof;
   108376     return SQLITE_OK;
   108377   }
   108378 
   108379   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
   108380   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
   108381   if( rc!=SQLITE_OK ){
   108382     return rc;
   108383   }
   108384 
   108385   nodeRelease(pRtree, pCursor->pNode);
   108386   pCursor->pNode = pChild;
   108387   isEof = 1;
   108388   for(ii=0; isEof && ii<NCELL(pChild); ii++){
   108389     pCursor->iCell = ii;
   108390     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
   108391     if( rc!=SQLITE_OK ){
   108392       return rc;
   108393     }
   108394   }
   108395 
   108396   if( isEof ){
   108397     assert( pCursor->pNode==pChild );
   108398     nodeReference(pSavedNode);
   108399     nodeRelease(pRtree, pChild);
   108400     pCursor->pNode = pSavedNode;
   108401     pCursor->iCell = iSavedCell;
   108402   }
   108403 
   108404   *pEof = isEof;
   108405   return SQLITE_OK;
   108406 }
   108407 
   108408 /*
   108409 ** One of the cells in node pNode is guaranteed to have a 64-bit
   108410 ** integer value equal to iRowid. Return the index of this cell.
   108411 */
   108412 static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
   108413   int ii;
   108414   for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
   108415     assert( ii<(NCELL(pNode)-1) );
   108416   }
   108417   return ii;
   108418 }
   108419 
   108420 /*
   108421 ** Return the index of the cell containing a pointer to node pNode
   108422 ** in its parent. If pNode is the root node, return -1.
   108423 */
   108424 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
   108425   RtreeNode *pParent = pNode->pParent;
   108426   if( pParent ){
   108427     return nodeRowidIndex(pRtree, pParent, pNode->iNode);
   108428   }
   108429   return -1;
   108430 }
   108431 
   108432 /*
   108433 ** Rtree virtual table module xNext method.
   108434 */
   108435 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
   108436   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
   108437   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   108438   int rc = SQLITE_OK;
   108439 
   108440   if( pCsr->iStrategy==1 ){
   108441     /* This "scan" is a direct lookup by rowid. There is no next entry. */
   108442     nodeRelease(pRtree, pCsr->pNode);
   108443     pCsr->pNode = 0;
   108444   }
   108445 
   108446   else if( pCsr->pNode ){
   108447     /* Move to the next entry that matches the configured constraints. */
   108448     int iHeight = 0;
   108449     while( pCsr->pNode ){
   108450       RtreeNode *pNode = pCsr->pNode;
   108451       int nCell = NCELL(pNode);
   108452       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
   108453         int isEof;
   108454         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
   108455         if( rc!=SQLITE_OK || !isEof ){
   108456           return rc;
   108457         }
   108458       }
   108459       pCsr->pNode = pNode->pParent;
   108460       pCsr->iCell = nodeParentIndex(pRtree, pNode);
   108461       nodeReference(pCsr->pNode);
   108462       nodeRelease(pRtree, pNode);
   108463       iHeight++;
   108464     }
   108465   }
   108466 
   108467   return rc;
   108468 }
   108469 
   108470 /*
   108471 ** Rtree virtual table module xRowid method.
   108472 */
   108473 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
   108474   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
   108475   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   108476 
   108477   assert(pCsr->pNode);
   108478   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
   108479 
   108480   return SQLITE_OK;
   108481 }
   108482 
   108483 /*
   108484 ** Rtree virtual table module xColumn method.
   108485 */
   108486 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
   108487   Rtree *pRtree = (Rtree *)cur->pVtab;
   108488   RtreeCursor *pCsr = (RtreeCursor *)cur;
   108489 
   108490   if( i==0 ){
   108491     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
   108492     sqlite3_result_int64(ctx, iRowid);
   108493   }else{
   108494     RtreeCoord c;
   108495     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
   108496     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   108497       sqlite3_result_double(ctx, c.f);
   108498     }else{
   108499       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
   108500       sqlite3_result_int(ctx, c.i);
   108501     }
   108502   }
   108503 
   108504   return SQLITE_OK;
   108505 }
   108506 
   108507 /*
   108508 ** Use nodeAcquire() to obtain the leaf node containing the record with
   108509 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
   108510 ** return SQLITE_OK. If there is no such record in the table, set
   108511 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
   108512 ** to zero and return an SQLite error code.
   108513 */
   108514 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
   108515   int rc;
   108516   *ppLeaf = 0;
   108517   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
   108518   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
   108519     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
   108520     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
   108521     sqlite3_reset(pRtree->pReadRowid);
   108522   }else{
   108523     rc = sqlite3_reset(pRtree->pReadRowid);
   108524   }
   108525   return rc;
   108526 }
   108527 
   108528 
   108529 /*
   108530 ** Rtree virtual table module xFilter method.
   108531 */
   108532 static int rtreeFilter(
   108533   sqlite3_vtab_cursor *pVtabCursor,
   108534   int idxNum, const char *idxStr,
   108535   int argc, sqlite3_value **argv
   108536 ){
   108537   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
   108538   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   108539 
   108540   RtreeNode *pRoot = 0;
   108541   int ii;
   108542   int rc = SQLITE_OK;
   108543 
   108544   rtreeReference(pRtree);
   108545 
   108546   sqlite3_free(pCsr->aConstraint);
   108547   pCsr->aConstraint = 0;
   108548   pCsr->iStrategy = idxNum;
   108549 
   108550   if( idxNum==1 ){
   108551     /* Special case - lookup by rowid. */
   108552     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
   108553     i64 iRowid = sqlite3_value_int64(argv[0]);
   108554     rc = findLeafNode(pRtree, iRowid, &pLeaf);
   108555     pCsr->pNode = pLeaf;
   108556     if( pLeaf && rc==SQLITE_OK ){
   108557       pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
   108558     }
   108559   }else{
   108560     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
   108561     ** with the configured constraints.
   108562     */
   108563     if( argc>0 ){
   108564       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
   108565       pCsr->nConstraint = argc;
   108566       if( !pCsr->aConstraint ){
   108567         rc = SQLITE_NOMEM;
   108568       }else{
   108569         assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
   108570         for(ii=0; ii<argc; ii++){
   108571           RtreeConstraint *p = &pCsr->aConstraint[ii];
   108572           p->op = idxStr[ii*2];
   108573           p->iCoord = idxStr[ii*2+1]-'a';
   108574           p->rValue = sqlite3_value_double(argv[ii]);
   108575         }
   108576       }
   108577     }
   108578 
   108579     if( rc==SQLITE_OK ){
   108580       pCsr->pNode = 0;
   108581       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
   108582     }
   108583     if( rc==SQLITE_OK ){
   108584       int isEof = 1;
   108585       int nCell = NCELL(pRoot);
   108586       pCsr->pNode = pRoot;
   108587       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
   108588         assert( pCsr->pNode==pRoot );
   108589         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
   108590         if( !isEof ){
   108591           break;
   108592         }
   108593       }
   108594       if( rc==SQLITE_OK && isEof ){
   108595         assert( pCsr->pNode==pRoot );
   108596         nodeRelease(pRtree, pRoot);
   108597         pCsr->pNode = 0;
   108598       }
   108599       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
   108600     }
   108601   }
   108602 
   108603   rtreeRelease(pRtree);
   108604   return rc;
   108605 }
   108606 
   108607 /*
   108608 ** Rtree virtual table module xBestIndex method. There are three
   108609 ** table scan strategies to choose from (in order from most to
   108610 ** least desirable):
   108611 **
   108612 **   idxNum     idxStr        Strategy
   108613 **   ------------------------------------------------
   108614 **     1        Unused        Direct lookup by rowid.
   108615 **     2        See below     R-tree query.
   108616 **     3        Unused        Full table scan.
   108617 **   ------------------------------------------------
   108618 **
   108619 ** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
   108620 ** 2 is used, idxStr is formatted to contain 2 bytes for each
   108621 ** constraint used. The first two bytes of idxStr correspond to
   108622 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
   108623 ** (argvIndex==1) etc.
   108624 **
   108625 ** The first of each pair of bytes in idxStr identifies the constraint
   108626 ** operator as follows:
   108627 **
   108628 **   Operator    Byte Value
   108629 **   ----------------------
   108630 **      =        0x41 ('A')
   108631 **     <=        0x42 ('B')
   108632 **      <        0x43 ('C')
   108633 **     >=        0x44 ('D')
   108634 **      >        0x45 ('E')
   108635 **   ----------------------
   108636 **
   108637 ** The second of each pair of bytes identifies the coordinate column
   108638 ** to which the constraint applies. The leftmost coordinate column
   108639 ** is 'a', the second from the left 'b' etc.
   108640 */
   108641 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
   108642   int rc = SQLITE_OK;
   108643   int ii, cCol;
   108644 
   108645   int iIdx = 0;
   108646   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
   108647   memset(zIdxStr, 0, sizeof(zIdxStr));
   108648 
   108649   assert( pIdxInfo->idxStr==0 );
   108650   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
   108651     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
   108652 
   108653     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
   108654       /* We have an equality constraint on the rowid. Use strategy 1. */
   108655       int jj;
   108656       for(jj=0; jj<ii; jj++){
   108657         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
   108658         pIdxInfo->aConstraintUsage[jj].omit = 0;
   108659       }
   108660       pIdxInfo->idxNum = 1;
   108661       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
   108662       pIdxInfo->aConstraintUsage[jj].omit = 1;
   108663 
   108664       /* This strategy involves a two rowid lookups on an B-Tree structures
   108665       ** and then a linear search of an R-Tree node. This should be
   108666       ** considered almost as quick as a direct rowid lookup (for which
   108667       ** sqlite uses an internal cost of 0.0).
   108668       */
   108669       pIdxInfo->estimatedCost = 10.0;
   108670       return SQLITE_OK;
   108671     }
   108672 
   108673     if( p->usable && p->iColumn>0 ){
   108674       u8 op = 0;
   108675       switch( p->op ){
   108676         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
   108677         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
   108678         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
   108679         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
   108680         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
   108681       }
   108682       if( op ){
   108683         /* Make sure this particular constraint has not been used before.
   108684         ** If it has been used before, ignore it.
   108685         **
   108686         ** A <= or < can be used if there is a prior >= or >.
   108687         ** A >= or > can be used if there is a prior < or <=.
   108688         ** A <= or < is disqualified if there is a prior <=, <, or ==.
   108689         ** A >= or > is disqualified if there is a prior >=, >, or ==.
   108690         ** A == is disqualifed if there is any prior constraint.
   108691         */
   108692         int j, opmsk;
   108693         static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
   108694         assert( compatible[RTREE_EQ & 7]==0 );
   108695         assert( compatible[RTREE_LT & 7]==1 );
   108696         assert( compatible[RTREE_LE & 7]==1 );
   108697         assert( compatible[RTREE_GT & 7]==2 );
   108698         assert( compatible[RTREE_GE & 7]==2 );
   108699         cCol = p->iColumn - 1 + 'a';
   108700         opmsk = compatible[op & 7];
   108701         for(j=0; j<iIdx; j+=2){
   108702           if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
   108703             op = 0;
   108704             break;
   108705           }
   108706         }
   108707       }
   108708       if( op ){
   108709         assert( iIdx<sizeof(zIdxStr)-1 );
   108710         zIdxStr[iIdx++] = op;
   108711         zIdxStr[iIdx++] = cCol;
   108712         pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
   108713         pIdxInfo->aConstraintUsage[ii].omit = 1;
   108714       }
   108715     }
   108716   }
   108717 
   108718   pIdxInfo->idxNum = 2;
   108719   pIdxInfo->needToFreeIdxStr = 1;
   108720   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
   108721     return SQLITE_NOMEM;
   108722   }
   108723   assert( iIdx>=0 );
   108724   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
   108725   return rc;
   108726 }
   108727 
   108728 /*
   108729 ** Return the N-dimensional volumn of the cell stored in *p.
   108730 */
   108731 static float cellArea(Rtree *pRtree, RtreeCell *p){
   108732   float area = 1.0;
   108733   int ii;
   108734   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   108735     area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
   108736   }
   108737   return area;
   108738 }
   108739 
   108740 /*
   108741 ** Return the margin length of cell p. The margin length is the sum
   108742 ** of the objects size in each dimension.
   108743 */
   108744 static float cellMargin(Rtree *pRtree, RtreeCell *p){
   108745   float margin = 0.0;
   108746   int ii;
   108747   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   108748     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
   108749   }
   108750   return margin;
   108751 }
   108752 
   108753 /*
   108754 ** Store the union of cells p1 and p2 in p1.
   108755 */
   108756 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
   108757   int ii;
   108758   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   108759     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   108760       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
   108761       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
   108762     }
   108763   }else{
   108764     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   108765       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
   108766       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
   108767     }
   108768   }
   108769 }
   108770 
   108771 /*
   108772 ** Return true if the area covered by p2 is a subset of the area covered
   108773 ** by p1. False otherwise.
   108774 */
   108775 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
   108776   int ii;
   108777   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
   108778   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   108779     RtreeCoord *a1 = &p1->aCoord[ii];
   108780     RtreeCoord *a2 = &p2->aCoord[ii];
   108781     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
   108782      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
   108783     ){
   108784       return 0;
   108785     }
   108786   }
   108787   return 1;
   108788 }
   108789 
   108790 /*
   108791 ** Return the amount cell p would grow by if it were unioned with pCell.
   108792 */
   108793 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
   108794   float area;
   108795   RtreeCell cell;
   108796   memcpy(&cell, p, sizeof(RtreeCell));
   108797   area = cellArea(pRtree, &cell);
   108798   cellUnion(pRtree, &cell, pCell);
   108799   return (cellArea(pRtree, &cell)-area);
   108800 }
   108801 
   108802 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
   108803 static float cellOverlap(
   108804   Rtree *pRtree,
   108805   RtreeCell *p,
   108806   RtreeCell *aCell,
   108807   int nCell,
   108808   int iExclude
   108809 ){
   108810   int ii;
   108811   float overlap = 0.0;
   108812   for(ii=0; ii<nCell; ii++){
   108813     if( ii!=iExclude ){
   108814       int jj;
   108815       float o = 1.0;
   108816       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
   108817         double x1;
   108818         double x2;
   108819 
   108820         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
   108821         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
   108822 
   108823         if( x2<x1 ){
   108824           o = 0.0;
   108825           break;
   108826         }else{
   108827           o = o * (x2-x1);
   108828         }
   108829       }
   108830       overlap += o;
   108831     }
   108832   }
   108833   return overlap;
   108834 }
   108835 #endif
   108836 
   108837 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   108838 static float cellOverlapEnlargement(
   108839   Rtree *pRtree,
   108840   RtreeCell *p,
   108841   RtreeCell *pInsert,
   108842   RtreeCell *aCell,
   108843   int nCell,
   108844   int iExclude
   108845 ){
   108846   float before;
   108847   float after;
   108848   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
   108849   cellUnion(pRtree, p, pInsert);
   108850   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
   108851   return after-before;
   108852 }
   108853 #endif
   108854 
   108855 
   108856 /*
   108857 ** This function implements the ChooseLeaf algorithm from Gutman[84].
   108858 ** ChooseSubTree in r*tree terminology.
   108859 */
   108860 static int ChooseLeaf(
   108861   Rtree *pRtree,               /* Rtree table */
   108862   RtreeCell *pCell,            /* Cell to insert into rtree */
   108863   int iHeight,                 /* Height of sub-tree rooted at pCell */
   108864   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
   108865 ){
   108866   int rc;
   108867   int ii;
   108868   RtreeNode *pNode;
   108869   rc = nodeAcquire(pRtree, 1, 0, &pNode);
   108870 
   108871   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
   108872     int iCell;
   108873     sqlite3_int64 iBest;
   108874 
   108875     float fMinGrowth;
   108876     float fMinArea;
   108877     float fMinOverlap;
   108878 
   108879     int nCell = NCELL(pNode);
   108880     RtreeCell cell;
   108881     RtreeNode *pChild;
   108882 
   108883     RtreeCell *aCell = 0;
   108884 
   108885 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   108886     if( ii==(pRtree->iDepth-1) ){
   108887       int jj;
   108888       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
   108889       if( !aCell ){
   108890         rc = SQLITE_NOMEM;
   108891         nodeRelease(pRtree, pNode);
   108892         pNode = 0;
   108893         continue;
   108894       }
   108895       for(jj=0; jj<nCell; jj++){
   108896         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
   108897       }
   108898     }
   108899 #endif
   108900 
   108901     /* Select the child node which will be enlarged the least if pCell
   108902     ** is inserted into it. Resolve ties by choosing the entry with
   108903     ** the smallest area.
   108904     */
   108905     for(iCell=0; iCell<nCell; iCell++){
   108906       float growth;
   108907       float area;
   108908       float overlap = 0.0;
   108909       nodeGetCell(pRtree, pNode, iCell, &cell);
   108910       growth = cellGrowth(pRtree, &cell, pCell);
   108911       area = cellArea(pRtree, &cell);
   108912 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   108913       if( ii==(pRtree->iDepth-1) ){
   108914         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
   108915       }
   108916 #endif
   108917       if( (iCell==0)
   108918        || (overlap<fMinOverlap)
   108919        || (overlap==fMinOverlap && growth<fMinGrowth)
   108920        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
   108921       ){
   108922         fMinOverlap = overlap;
   108923         fMinGrowth = growth;
   108924         fMinArea = area;
   108925         iBest = cell.iRowid;
   108926       }
   108927     }
   108928 
   108929     sqlite3_free(aCell);
   108930     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
   108931     nodeRelease(pRtree, pNode);
   108932     pNode = pChild;
   108933   }
   108934 
   108935   *ppLeaf = pNode;
   108936   return rc;
   108937 }
   108938 
   108939 /*
   108940 ** A cell with the same content as pCell has just been inserted into
   108941 ** the node pNode. This function updates the bounding box cells in
   108942 ** all ancestor elements.
   108943 */
   108944 static void AdjustTree(
   108945   Rtree *pRtree,                    /* Rtree table */
   108946   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
   108947   RtreeCell *pCell                  /* This cell was just inserted */
   108948 ){
   108949   RtreeNode *p = pNode;
   108950   while( p->pParent ){
   108951     RtreeCell cell;
   108952     RtreeNode *pParent = p->pParent;
   108953     int iCell = nodeParentIndex(pRtree, p);
   108954 
   108955     nodeGetCell(pRtree, pParent, iCell, &cell);
   108956     if( !cellContains(pRtree, &cell, pCell) ){
   108957       cellUnion(pRtree, &cell, pCell);
   108958       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
   108959     }
   108960 
   108961     p = pParent;
   108962   }
   108963 }
   108964 
   108965 /*
   108966 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
   108967 */
   108968 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
   108969   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
   108970   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
   108971   sqlite3_step(pRtree->pWriteRowid);
   108972   return sqlite3_reset(pRtree->pWriteRowid);
   108973 }
   108974 
   108975 /*
   108976 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
   108977 */
   108978 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
   108979   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
   108980   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
   108981   sqlite3_step(pRtree->pWriteParent);
   108982   return sqlite3_reset(pRtree->pWriteParent);
   108983 }
   108984 
   108985 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
   108986 
   108987 #if VARIANT_GUTTMAN_LINEAR_SPLIT
   108988 /*
   108989 ** Implementation of the linear variant of the PickNext() function from
   108990 ** Guttman[84].
   108991 */
   108992 static RtreeCell *LinearPickNext(
   108993   Rtree *pRtree,
   108994   RtreeCell *aCell,
   108995   int nCell,
   108996   RtreeCell *pLeftBox,
   108997   RtreeCell *pRightBox,
   108998   int *aiUsed
   108999 ){
   109000   int ii;
   109001   for(ii=0; aiUsed[ii]; ii++);
   109002   aiUsed[ii] = 1;
   109003   return &aCell[ii];
   109004 }
   109005 
   109006 /*
   109007 ** Implementation of the linear variant of the PickSeeds() function from
   109008 ** Guttman[84].
   109009 */
   109010 static void LinearPickSeeds(
   109011   Rtree *pRtree,
   109012   RtreeCell *aCell,
   109013   int nCell,
   109014   int *piLeftSeed,
   109015   int *piRightSeed
   109016 ){
   109017   int i;
   109018   int iLeftSeed = 0;
   109019   int iRightSeed = 1;
   109020   float maxNormalInnerWidth = 0.0;
   109021 
   109022   /* Pick two "seed" cells from the array of cells. The algorithm used
   109023   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
   109024   ** indices of the two seed cells in the array are stored in local
   109025   ** variables iLeftSeek and iRightSeed.
   109026   */
   109027   for(i=0; i<pRtree->nDim; i++){
   109028     float x1 = DCOORD(aCell[0].aCoord[i*2]);
   109029     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
   109030     float x3 = x1;
   109031     float x4 = x2;
   109032     int jj;
   109033 
   109034     int iCellLeft = 0;
   109035     int iCellRight = 0;
   109036 
   109037     for(jj=1; jj<nCell; jj++){
   109038       float left = DCOORD(aCell[jj].aCoord[i*2]);
   109039       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
   109040 
   109041       if( left<x1 ) x1 = left;
   109042       if( right>x4 ) x4 = right;
   109043       if( left>x3 ){
   109044         x3 = left;
   109045         iCellRight = jj;
   109046       }
   109047       if( right<x2 ){
   109048         x2 = right;
   109049         iCellLeft = jj;
   109050       }
   109051     }
   109052 
   109053     if( x4!=x1 ){
   109054       float normalwidth = (x3 - x2) / (x4 - x1);
   109055       if( normalwidth>maxNormalInnerWidth ){
   109056         iLeftSeed = iCellLeft;
   109057         iRightSeed = iCellRight;
   109058       }
   109059     }
   109060   }
   109061 
   109062   *piLeftSeed = iLeftSeed;
   109063   *piRightSeed = iRightSeed;
   109064 }
   109065 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
   109066 
   109067 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
   109068 /*
   109069 ** Implementation of the quadratic variant of the PickNext() function from
   109070 ** Guttman[84].
   109071 */
   109072 static RtreeCell *QuadraticPickNext(
   109073   Rtree *pRtree,
   109074   RtreeCell *aCell,
   109075   int nCell,
   109076   RtreeCell *pLeftBox,
   109077   RtreeCell *pRightBox,
   109078   int *aiUsed
   109079 ){
   109080   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
   109081 
   109082   int iSelect = -1;
   109083   float fDiff;
   109084   int ii;
   109085   for(ii=0; ii<nCell; ii++){
   109086     if( aiUsed[ii]==0 ){
   109087       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
   109088       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
   109089       float diff = FABS(right-left);
   109090       if( iSelect<0 || diff>fDiff ){
   109091         fDiff = diff;
   109092         iSelect = ii;
   109093       }
   109094     }
   109095   }
   109096   aiUsed[iSelect] = 1;
   109097   return &aCell[iSelect];
   109098 }
   109099 
   109100 /*
   109101 ** Implementation of the quadratic variant of the PickSeeds() function from
   109102 ** Guttman[84].
   109103 */
   109104 static void QuadraticPickSeeds(
   109105   Rtree *pRtree,
   109106   RtreeCell *aCell,
   109107   int nCell,
   109108   int *piLeftSeed,
   109109   int *piRightSeed
   109110 ){
   109111   int ii;
   109112   int jj;
   109113 
   109114   int iLeftSeed = 0;
   109115   int iRightSeed = 1;
   109116   float fWaste = 0.0;
   109117 
   109118   for(ii=0; ii<nCell; ii++){
   109119     for(jj=ii+1; jj<nCell; jj++){
   109120       float right = cellArea(pRtree, &aCell[jj]);
   109121       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
   109122       float waste = growth - right;
   109123 
   109124       if( waste>fWaste ){
   109125         iLeftSeed = ii;
   109126         iRightSeed = jj;
   109127         fWaste = waste;
   109128       }
   109129     }
   109130   }
   109131 
   109132   *piLeftSeed = iLeftSeed;
   109133   *piRightSeed = iRightSeed;
   109134 }
   109135 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
   109136 
   109137 /*
   109138 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
   109139 ** nIdx. The aIdx array contains the set of integers from 0 to
   109140 ** (nIdx-1) in no particular order. This function sorts the values
   109141 ** in aIdx according to the indexed values in aDistance. For
   109142 ** example, assuming the inputs:
   109143 **
   109144 **   aIdx      = { 0,   1,   2,   3 }
   109145 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
   109146 **
   109147 ** this function sets the aIdx array to contain:
   109148 **
   109149 **   aIdx      = { 0,   1,   2,   3 }
   109150 **
   109151 ** The aSpare array is used as temporary working space by the
   109152 ** sorting algorithm.
   109153 */
   109154 static void SortByDistance(
   109155   int *aIdx,
   109156   int nIdx,
   109157   float *aDistance,
   109158   int *aSpare
   109159 ){
   109160   if( nIdx>1 ){
   109161     int iLeft = 0;
   109162     int iRight = 0;
   109163 
   109164     int nLeft = nIdx/2;
   109165     int nRight = nIdx-nLeft;
   109166     int *aLeft = aIdx;
   109167     int *aRight = &aIdx[nLeft];
   109168 
   109169     SortByDistance(aLeft, nLeft, aDistance, aSpare);
   109170     SortByDistance(aRight, nRight, aDistance, aSpare);
   109171 
   109172     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
   109173     aLeft = aSpare;
   109174 
   109175     while( iLeft<nLeft || iRight<nRight ){
   109176       if( iLeft==nLeft ){
   109177         aIdx[iLeft+iRight] = aRight[iRight];
   109178         iRight++;
   109179       }else if( iRight==nRight ){
   109180         aIdx[iLeft+iRight] = aLeft[iLeft];
   109181         iLeft++;
   109182       }else{
   109183         float fLeft = aDistance[aLeft[iLeft]];
   109184         float fRight = aDistance[aRight[iRight]];
   109185         if( fLeft<fRight ){
   109186           aIdx[iLeft+iRight] = aLeft[iLeft];
   109187           iLeft++;
   109188         }else{
   109189           aIdx[iLeft+iRight] = aRight[iRight];
   109190           iRight++;
   109191         }
   109192       }
   109193     }
   109194 
   109195 #if 0
   109196     /* Check that the sort worked */
   109197     {
   109198       int jj;
   109199       for(jj=1; jj<nIdx; jj++){
   109200         float left = aDistance[aIdx[jj-1]];
   109201         float right = aDistance[aIdx[jj]];
   109202         assert( left<=right );
   109203       }
   109204     }
   109205 #endif
   109206   }
   109207 }
   109208 
   109209 /*
   109210 ** Arguments aIdx, aCell and aSpare all point to arrays of size
   109211 ** nIdx. The aIdx array contains the set of integers from 0 to
   109212 ** (nIdx-1) in no particular order. This function sorts the values
   109213 ** in aIdx according to dimension iDim of the cells in aCell. The
   109214 ** minimum value of dimension iDim is considered first, the
   109215 ** maximum used to break ties.
   109216 **
   109217 ** The aSpare array is used as temporary working space by the
   109218 ** sorting algorithm.
   109219 */
   109220 static void SortByDimension(
   109221   Rtree *pRtree,
   109222   int *aIdx,
   109223   int nIdx,
   109224   int iDim,
   109225   RtreeCell *aCell,
   109226   int *aSpare
   109227 ){
   109228   if( nIdx>1 ){
   109229 
   109230     int iLeft = 0;
   109231     int iRight = 0;
   109232 
   109233     int nLeft = nIdx/2;
   109234     int nRight = nIdx-nLeft;
   109235     int *aLeft = aIdx;
   109236     int *aRight = &aIdx[nLeft];
   109237 
   109238     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
   109239     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
   109240 
   109241     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
   109242     aLeft = aSpare;
   109243     while( iLeft<nLeft || iRight<nRight ){
   109244       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
   109245       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
   109246       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
   109247       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
   109248       if( (iLeft!=nLeft) && ((iRight==nRight)
   109249        || (xleft1<xright1)
   109250        || (xleft1==xright1 && xleft2<xright2)
   109251       )){
   109252         aIdx[iLeft+iRight] = aLeft[iLeft];
   109253         iLeft++;
   109254       }else{
   109255         aIdx[iLeft+iRight] = aRight[iRight];
   109256         iRight++;
   109257       }
   109258     }
   109259 
   109260 #if 0
   109261     /* Check that the sort worked */
   109262     {
   109263       int jj;
   109264       for(jj=1; jj<nIdx; jj++){
   109265         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
   109266         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
   109267         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
   109268         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
   109269         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
   109270       }
   109271     }
   109272 #endif
   109273   }
   109274 }
   109275 
   109276 #if VARIANT_RSTARTREE_SPLIT
   109277 /*
   109278 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
   109279 */
   109280 static int splitNodeStartree(
   109281   Rtree *pRtree,
   109282   RtreeCell *aCell,
   109283   int nCell,
   109284   RtreeNode *pLeft,
   109285   RtreeNode *pRight,
   109286   RtreeCell *pBboxLeft,
   109287   RtreeCell *pBboxRight
   109288 ){
   109289   int **aaSorted;
   109290   int *aSpare;
   109291   int ii;
   109292 
   109293   int iBestDim;
   109294   int iBestSplit;
   109295   float fBestMargin;
   109296 
   109297   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
   109298 
   109299   aaSorted = (int **)sqlite3_malloc(nByte);
   109300   if( !aaSorted ){
   109301     return SQLITE_NOMEM;
   109302   }
   109303 
   109304   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
   109305   memset(aaSorted, 0, nByte);
   109306   for(ii=0; ii<pRtree->nDim; ii++){
   109307     int jj;
   109308     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
   109309     for(jj=0; jj<nCell; jj++){
   109310       aaSorted[ii][jj] = jj;
   109311     }
   109312     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
   109313   }
   109314 
   109315   for(ii=0; ii<pRtree->nDim; ii++){
   109316     float margin = 0.0;
   109317     float fBestOverlap;
   109318     float fBestArea;
   109319     int iBestLeft;
   109320     int nLeft;
   109321 
   109322     for(
   109323       nLeft=RTREE_MINCELLS(pRtree);
   109324       nLeft<=(nCell-RTREE_MINCELLS(pRtree));
   109325       nLeft++
   109326     ){
   109327       RtreeCell left;
   109328       RtreeCell right;
   109329       int kk;
   109330       float overlap;
   109331       float area;
   109332 
   109333       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
   109334       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
   109335       for(kk=1; kk<(nCell-1); kk++){
   109336         if( kk<nLeft ){
   109337           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
   109338         }else{
   109339           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
   109340         }
   109341       }
   109342       margin += cellMargin(pRtree, &left);
   109343       margin += cellMargin(pRtree, &right);
   109344       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
   109345       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
   109346       if( (nLeft==RTREE_MINCELLS(pRtree))
   109347        || (overlap<fBestOverlap)
   109348        || (overlap==fBestOverlap && area<fBestArea)
   109349       ){
   109350         iBestLeft = nLeft;
   109351         fBestOverlap = overlap;
   109352         fBestArea = area;
   109353       }
   109354     }
   109355 
   109356     if( ii==0 || margin<fBestMargin ){
   109357       iBestDim = ii;
   109358       fBestMargin = margin;
   109359       iBestSplit = iBestLeft;
   109360     }
   109361   }
   109362 
   109363   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
   109364   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
   109365   for(ii=0; ii<nCell; ii++){
   109366     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
   109367     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
   109368     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
   109369     nodeInsertCell(pRtree, pTarget, pCell);
   109370     cellUnion(pRtree, pBbox, pCell);
   109371   }
   109372 
   109373   sqlite3_free(aaSorted);
   109374   return SQLITE_OK;
   109375 }
   109376 #endif
   109377 
   109378 #if VARIANT_GUTTMAN_SPLIT
   109379 /*
   109380 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
   109381 */
   109382 static int splitNodeGuttman(
   109383   Rtree *pRtree,
   109384   RtreeCell *aCell,
   109385   int nCell,
   109386   RtreeNode *pLeft,
   109387   RtreeNode *pRight,
   109388   RtreeCell *pBboxLeft,
   109389   RtreeCell *pBboxRight
   109390 ){
   109391   int iLeftSeed = 0;
   109392   int iRightSeed = 1;
   109393   int *aiUsed;
   109394   int i;
   109395 
   109396   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
   109397   if( !aiUsed ){
   109398     return SQLITE_NOMEM;
   109399   }
   109400   memset(aiUsed, 0, sizeof(int)*nCell);
   109401 
   109402   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
   109403 
   109404   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
   109405   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
   109406   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
   109407   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
   109408   aiUsed[iLeftSeed] = 1;
   109409   aiUsed[iRightSeed] = 1;
   109410 
   109411   for(i=nCell-2; i>0; i--){
   109412     RtreeCell *pNext;
   109413     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
   109414     float diff =
   109415       cellGrowth(pRtree, pBboxLeft, pNext) -
   109416       cellGrowth(pRtree, pBboxRight, pNext)
   109417     ;
   109418     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
   109419      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
   109420     ){
   109421       nodeInsertCell(pRtree, pRight, pNext);
   109422       cellUnion(pRtree, pBboxRight, pNext);
   109423     }else{
   109424       nodeInsertCell(pRtree, pLeft, pNext);
   109425       cellUnion(pRtree, pBboxLeft, pNext);
   109426     }
   109427   }
   109428 
   109429   sqlite3_free(aiUsed);
   109430   return SQLITE_OK;
   109431 }
   109432 #endif
   109433 
   109434 static int updateMapping(
   109435   Rtree *pRtree,
   109436   i64 iRowid,
   109437   RtreeNode *pNode,
   109438   int iHeight
   109439 ){
   109440   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
   109441   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
   109442   if( iHeight>0 ){
   109443     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
   109444     if( pChild ){
   109445       nodeRelease(pRtree, pChild->pParent);
   109446       nodeReference(pNode);
   109447       pChild->pParent = pNode;
   109448     }
   109449   }
   109450   return xSetMapping(pRtree, iRowid, pNode->iNode);
   109451 }
   109452 
   109453 static int SplitNode(
   109454   Rtree *pRtree,
   109455   RtreeNode *pNode,
   109456   RtreeCell *pCell,
   109457   int iHeight
   109458 ){
   109459   int i;
   109460   int newCellIsRight = 0;
   109461 
   109462   int rc = SQLITE_OK;
   109463   int nCell = NCELL(pNode);
   109464   RtreeCell *aCell;
   109465   int *aiUsed;
   109466 
   109467   RtreeNode *pLeft = 0;
   109468   RtreeNode *pRight = 0;
   109469 
   109470   RtreeCell leftbbox;
   109471   RtreeCell rightbbox;
   109472 
   109473   /* Allocate an array and populate it with a copy of pCell and
   109474   ** all cells from node pLeft. Then zero the original node.
   109475   */
   109476   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
   109477   if( !aCell ){
   109478     rc = SQLITE_NOMEM;
   109479     goto splitnode_out;
   109480   }
   109481   aiUsed = (int *)&aCell[nCell+1];
   109482   memset(aiUsed, 0, sizeof(int)*(nCell+1));
   109483   for(i=0; i<nCell; i++){
   109484     nodeGetCell(pRtree, pNode, i, &aCell[i]);
   109485   }
   109486   nodeZero(pRtree, pNode);
   109487   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
   109488   nCell++;
   109489 
   109490   if( pNode->iNode==1 ){
   109491     pRight = nodeNew(pRtree, pNode, 1);
   109492     pLeft = nodeNew(pRtree, pNode, 1);
   109493     pRtree->iDepth++;
   109494     pNode->isDirty = 1;
   109495     writeInt16(pNode->zData, pRtree->iDepth);
   109496   }else{
   109497     pLeft = pNode;
   109498     pRight = nodeNew(pRtree, pLeft->pParent, 1);
   109499     nodeReference(pLeft);
   109500   }
   109501 
   109502   if( !pLeft || !pRight ){
   109503     rc = SQLITE_NOMEM;
   109504     goto splitnode_out;
   109505   }
   109506 
   109507   memset(pLeft->zData, 0, pRtree->iNodeSize);
   109508   memset(pRight->zData, 0, pRtree->iNodeSize);
   109509 
   109510   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
   109511   if( rc!=SQLITE_OK ){
   109512     goto splitnode_out;
   109513   }
   109514 
   109515   /* Ensure both child nodes have node numbers assigned to them. */
   109516   if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
   109517    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
   109518   ){
   109519     goto splitnode_out;
   109520   }
   109521 
   109522   rightbbox.iRowid = pRight->iNode;
   109523   leftbbox.iRowid = pLeft->iNode;
   109524 
   109525   if( pNode->iNode==1 ){
   109526     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
   109527     if( rc!=SQLITE_OK ){
   109528       goto splitnode_out;
   109529     }
   109530   }else{
   109531     RtreeNode *pParent = pLeft->pParent;
   109532     int iCell = nodeParentIndex(pRtree, pLeft);
   109533     nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
   109534     AdjustTree(pRtree, pParent, &leftbbox);
   109535   }
   109536   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
   109537     goto splitnode_out;
   109538   }
   109539 
   109540   for(i=0; i<NCELL(pRight); i++){
   109541     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
   109542     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
   109543     if( iRowid==pCell->iRowid ){
   109544       newCellIsRight = 1;
   109545     }
   109546     if( rc!=SQLITE_OK ){
   109547       goto splitnode_out;
   109548     }
   109549   }
   109550   if( pNode->iNode==1 ){
   109551     for(i=0; i<NCELL(pLeft); i++){
   109552       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
   109553       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
   109554       if( rc!=SQLITE_OK ){
   109555         goto splitnode_out;
   109556       }
   109557     }
   109558   }else if( newCellIsRight==0 ){
   109559     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
   109560   }
   109561 
   109562   if( rc==SQLITE_OK ){
   109563     rc = nodeRelease(pRtree, pRight);
   109564     pRight = 0;
   109565   }
   109566   if( rc==SQLITE_OK ){
   109567     rc = nodeRelease(pRtree, pLeft);
   109568     pLeft = 0;
   109569   }
   109570 
   109571 splitnode_out:
   109572   nodeRelease(pRtree, pRight);
   109573   nodeRelease(pRtree, pLeft);
   109574   sqlite3_free(aCell);
   109575   return rc;
   109576 }
   109577 
   109578 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
   109579   int rc = SQLITE_OK;
   109580   if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
   109581     sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
   109582     if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
   109583       i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
   109584       rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
   109585     }else{
   109586       rc = SQLITE_ERROR;
   109587     }
   109588     sqlite3_reset(pRtree->pReadParent);
   109589     if( rc==SQLITE_OK ){
   109590       rc = fixLeafParent(pRtree, pLeaf->pParent);
   109591     }
   109592   }
   109593   return rc;
   109594 }
   109595 
   109596 static int deleteCell(Rtree *, RtreeNode *, int, int);
   109597 
   109598 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
   109599   int rc;
   109600   RtreeNode *pParent;
   109601   int iCell;
   109602 
   109603   assert( pNode->nRef==1 );
   109604 
   109605   /* Remove the entry in the parent cell. */
   109606   iCell = nodeParentIndex(pRtree, pNode);
   109607   pParent = pNode->pParent;
   109608   pNode->pParent = 0;
   109609   if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1))
   109610    || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
   109611   ){
   109612     return rc;
   109613   }
   109614 
   109615   /* Remove the xxx_node entry. */
   109616   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
   109617   sqlite3_step(pRtree->pDeleteNode);
   109618   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
   109619     return rc;
   109620   }
   109621 
   109622   /* Remove the xxx_parent entry. */
   109623   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
   109624   sqlite3_step(pRtree->pDeleteParent);
   109625   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
   109626     return rc;
   109627   }
   109628 
   109629   /* Remove the node from the in-memory hash table and link it into
   109630   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
   109631   */
   109632   nodeHashDelete(pRtree, pNode);
   109633   pNode->iNode = iHeight;
   109634   pNode->pNext = pRtree->pDeleted;
   109635   pNode->nRef++;
   109636   pRtree->pDeleted = pNode;
   109637 
   109638   return SQLITE_OK;
   109639 }
   109640 
   109641 static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
   109642   RtreeNode *pParent = pNode->pParent;
   109643   if( pParent ){
   109644     int ii;
   109645     int nCell = NCELL(pNode);
   109646     RtreeCell box;                            /* Bounding box for pNode */
   109647     nodeGetCell(pRtree, pNode, 0, &box);
   109648     for(ii=1; ii<nCell; ii++){
   109649       RtreeCell cell;
   109650       nodeGetCell(pRtree, pNode, ii, &cell);
   109651       cellUnion(pRtree, &box, &cell);
   109652     }
   109653     box.iRowid = pNode->iNode;
   109654     ii = nodeParentIndex(pRtree, pNode);
   109655     nodeOverwriteCell(pRtree, pParent, &box, ii);
   109656     fixBoundingBox(pRtree, pParent);
   109657   }
   109658 }
   109659 
   109660 /*
   109661 ** Delete the cell at index iCell of node pNode. After removing the
   109662 ** cell, adjust the r-tree data structure if required.
   109663 */
   109664 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
   109665   int rc;
   109666 
   109667   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
   109668     return rc;
   109669   }
   109670 
   109671   /* Remove the cell from the node. This call just moves bytes around
   109672   ** the in-memory node image, so it cannot fail.
   109673   */
   109674   nodeDeleteCell(pRtree, pNode, iCell);
   109675 
   109676   /* If the node is not the tree root and now has less than the minimum
   109677   ** number of cells, remove it from the tree. Otherwise, update the
   109678   ** cell in the parent node so that it tightly contains the updated
   109679   ** node.
   109680   */
   109681   if( pNode->iNode!=1 ){
   109682     RtreeNode *pParent = pNode->pParent;
   109683     if( (pParent->iNode!=1 || NCELL(pParent)!=1)
   109684      && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
   109685     ){
   109686       rc = removeNode(pRtree, pNode, iHeight);
   109687     }else{
   109688       fixBoundingBox(pRtree, pNode);
   109689     }
   109690   }
   109691 
   109692   return rc;
   109693 }
   109694 
   109695 static int Reinsert(
   109696   Rtree *pRtree,
   109697   RtreeNode *pNode,
   109698   RtreeCell *pCell,
   109699   int iHeight
   109700 ){
   109701   int *aOrder;
   109702   int *aSpare;
   109703   RtreeCell *aCell;
   109704   float *aDistance;
   109705   int nCell;
   109706   float aCenterCoord[RTREE_MAX_DIMENSIONS];
   109707   int iDim;
   109708   int ii;
   109709   int rc = SQLITE_OK;
   109710 
   109711   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
   109712 
   109713   nCell = NCELL(pNode)+1;
   109714 
   109715   /* Allocate the buffers used by this operation. The allocation is
   109716   ** relinquished before this function returns.
   109717   */
   109718   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
   109719     sizeof(RtreeCell) +         /* aCell array */
   109720     sizeof(int)       +         /* aOrder array */
   109721     sizeof(int)       +         /* aSpare array */
   109722     sizeof(float)               /* aDistance array */
   109723   ));
   109724   if( !aCell ){
   109725     return SQLITE_NOMEM;
   109726   }
   109727   aOrder    = (int *)&aCell[nCell];
   109728   aSpare    = (int *)&aOrder[nCell];
   109729   aDistance = (float *)&aSpare[nCell];
   109730 
   109731   for(ii=0; ii<nCell; ii++){
   109732     if( ii==(nCell-1) ){
   109733       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
   109734     }else{
   109735       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
   109736     }
   109737     aOrder[ii] = ii;
   109738     for(iDim=0; iDim<pRtree->nDim; iDim++){
   109739       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
   109740       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
   109741     }
   109742   }
   109743   for(iDim=0; iDim<pRtree->nDim; iDim++){
   109744     aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
   109745   }
   109746 
   109747   for(ii=0; ii<nCell; ii++){
   109748     aDistance[ii] = 0.0;
   109749     for(iDim=0; iDim<pRtree->nDim; iDim++){
   109750       float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) -
   109751           DCOORD(aCell[ii].aCoord[iDim*2]);
   109752       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
   109753     }
   109754   }
   109755 
   109756   SortByDistance(aOrder, nCell, aDistance, aSpare);
   109757   nodeZero(pRtree, pNode);
   109758 
   109759   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
   109760     RtreeCell *p = &aCell[aOrder[ii]];
   109761     nodeInsertCell(pRtree, pNode, p);
   109762     if( p->iRowid==pCell->iRowid ){
   109763       if( iHeight==0 ){
   109764         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
   109765       }else{
   109766         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
   109767       }
   109768     }
   109769   }
   109770   if( rc==SQLITE_OK ){
   109771     fixBoundingBox(pRtree, pNode);
   109772   }
   109773   for(; rc==SQLITE_OK && ii<nCell; ii++){
   109774     /* Find a node to store this cell in. pNode->iNode currently contains
   109775     ** the height of the sub-tree headed by the cell.
   109776     */
   109777     RtreeNode *pInsert;
   109778     RtreeCell *p = &aCell[aOrder[ii]];
   109779     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
   109780     if( rc==SQLITE_OK ){
   109781       int rc2;
   109782       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
   109783       rc2 = nodeRelease(pRtree, pInsert);
   109784       if( rc==SQLITE_OK ){
   109785         rc = rc2;
   109786       }
   109787     }
   109788   }
   109789 
   109790   sqlite3_free(aCell);
   109791   return rc;
   109792 }
   109793 
   109794 /*
   109795 ** Insert cell pCell into node pNode. Node pNode is the head of a
   109796 ** subtree iHeight high (leaf nodes have iHeight==0).
   109797 */
   109798 static int rtreeInsertCell(
   109799   Rtree *pRtree,
   109800   RtreeNode *pNode,
   109801   RtreeCell *pCell,
   109802   int iHeight
   109803 ){
   109804   int rc = SQLITE_OK;
   109805   if( iHeight>0 ){
   109806     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
   109807     if( pChild ){
   109808       nodeRelease(pRtree, pChild->pParent);
   109809       nodeReference(pNode);
   109810       pChild->pParent = pNode;
   109811     }
   109812   }
   109813   if( nodeInsertCell(pRtree, pNode, pCell) ){
   109814 #if VARIANT_RSTARTREE_REINSERT
   109815     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
   109816       rc = SplitNode(pRtree, pNode, pCell, iHeight);
   109817     }else{
   109818       pRtree->iReinsertHeight = iHeight;
   109819       rc = Reinsert(pRtree, pNode, pCell, iHeight);
   109820     }
   109821 #else
   109822     rc = SplitNode(pRtree, pNode, pCell, iHeight);
   109823 #endif
   109824   }else{
   109825     AdjustTree(pRtree, pNode, pCell);
   109826     if( iHeight==0 ){
   109827       rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
   109828     }else{
   109829       rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
   109830     }
   109831   }
   109832   return rc;
   109833 }
   109834 
   109835 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
   109836   int ii;
   109837   int rc = SQLITE_OK;
   109838   int nCell = NCELL(pNode);
   109839 
   109840   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
   109841     RtreeNode *pInsert;
   109842     RtreeCell cell;
   109843     nodeGetCell(pRtree, pNode, ii, &cell);
   109844 
   109845     /* Find a node to store this cell in. pNode->iNode currently contains
   109846     ** the height of the sub-tree headed by the cell.
   109847     */
   109848     rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
   109849     if( rc==SQLITE_OK ){
   109850       int rc2;
   109851       rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
   109852       rc2 = nodeRelease(pRtree, pInsert);
   109853       if( rc==SQLITE_OK ){
   109854         rc = rc2;
   109855       }
   109856     }
   109857   }
   109858   return rc;
   109859 }
   109860 
   109861 /*
   109862 ** Select a currently unused rowid for a new r-tree record.
   109863 */
   109864 static int newRowid(Rtree *pRtree, i64 *piRowid){
   109865   int rc;
   109866   sqlite3_bind_null(pRtree->pWriteRowid, 1);
   109867   sqlite3_bind_null(pRtree->pWriteRowid, 2);
   109868   sqlite3_step(pRtree->pWriteRowid);
   109869   rc = sqlite3_reset(pRtree->pWriteRowid);
   109870   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
   109871   return rc;
   109872 }
   109873 
   109874 #ifndef NDEBUG
   109875 static int hashIsEmpty(Rtree *pRtree){
   109876   int ii;
   109877   for(ii=0; ii<HASHSIZE; ii++){
   109878     assert( !pRtree->aHash[ii] );
   109879   }
   109880   return 1;
   109881 }
   109882 #endif
   109883 
   109884 /*
   109885 ** The xUpdate method for rtree module virtual tables.
   109886 */
   109887 static int rtreeUpdate(
   109888   sqlite3_vtab *pVtab,
   109889   int nData,
   109890   sqlite3_value **azData,
   109891   sqlite_int64 *pRowid
   109892 ){
   109893   Rtree *pRtree = (Rtree *)pVtab;
   109894   int rc = SQLITE_OK;
   109895 
   109896   rtreeReference(pRtree);
   109897 
   109898   assert(nData>=1);
   109899   assert(hashIsEmpty(pRtree));
   109900 
   109901   /* If azData[0] is not an SQL NULL value, it is the rowid of a
   109902   ** record to delete from the r-tree table. The following block does
   109903   ** just that.
   109904   */
   109905   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
   109906     i64 iDelete;                /* The rowid to delete */
   109907     RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
   109908     int iCell;                  /* Index of iDelete cell in pLeaf */
   109909     RtreeNode *pRoot;
   109910 
   109911     /* Obtain a reference to the root node to initialise Rtree.iDepth */
   109912     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
   109913 
   109914     /* Obtain a reference to the leaf node that contains the entry
   109915     ** about to be deleted.
   109916     */
   109917     if( rc==SQLITE_OK ){
   109918       iDelete = sqlite3_value_int64(azData[0]);
   109919       rc = findLeafNode(pRtree, iDelete, &pLeaf);
   109920     }
   109921 
   109922     /* Delete the cell in question from the leaf node. */
   109923     if( rc==SQLITE_OK ){
   109924       int rc2;
   109925       iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
   109926       rc = deleteCell(pRtree, pLeaf, iCell, 0);
   109927       rc2 = nodeRelease(pRtree, pLeaf);
   109928       if( rc==SQLITE_OK ){
   109929         rc = rc2;
   109930       }
   109931     }
   109932 
   109933     /* Delete the corresponding entry in the <rtree>_rowid table. */
   109934     if( rc==SQLITE_OK ){
   109935       sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
   109936       sqlite3_step(pRtree->pDeleteRowid);
   109937       rc = sqlite3_reset(pRtree->pDeleteRowid);
   109938     }
   109939 
   109940     /* Check if the root node now has exactly one child. If so, remove
   109941     ** it, schedule the contents of the child for reinsertion and
   109942     ** reduce the tree height by one.
   109943     **
   109944     ** This is equivalent to copying the contents of the child into
   109945     ** the root node (the operation that Gutman's paper says to perform
   109946     ** in this scenario).
   109947     */
   109948     if( rc==SQLITE_OK && pRtree->iDepth>0 ){
   109949       if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
   109950         RtreeNode *pChild;
   109951         i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
   109952         rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
   109953         if( rc==SQLITE_OK ){
   109954           rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
   109955         }
   109956         if( rc==SQLITE_OK ){
   109957           pRtree->iDepth--;
   109958           writeInt16(pRoot->zData, pRtree->iDepth);
   109959           pRoot->isDirty = 1;
   109960         }
   109961       }
   109962     }
   109963 
   109964     /* Re-insert the contents of any underfull nodes removed from the tree. */
   109965     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
   109966       if( rc==SQLITE_OK ){
   109967         rc = reinsertNodeContent(pRtree, pLeaf);
   109968       }
   109969       pRtree->pDeleted = pLeaf->pNext;
   109970       sqlite3_free(pLeaf);
   109971     }
   109972 
   109973     /* Release the reference to the root node. */
   109974     if( rc==SQLITE_OK ){
   109975       rc = nodeRelease(pRtree, pRoot);
   109976     }else{
   109977       nodeRelease(pRtree, pRoot);
   109978     }
   109979   }
   109980 
   109981   /* If the azData[] array contains more than one element, elements
   109982   ** (azData[2]..azData[argc-1]) contain a new record to insert into
   109983   ** the r-tree structure.
   109984   */
   109985   if( rc==SQLITE_OK && nData>1 ){
   109986     /* Insert a new record into the r-tree */
   109987     RtreeCell cell;
   109988     int ii;
   109989     RtreeNode *pLeaf;
   109990 
   109991     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
   109992     assert( nData==(pRtree->nDim*2 + 3) );
   109993     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   109994       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   109995         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
   109996         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
   109997         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
   109998           rc = SQLITE_CONSTRAINT;
   109999           goto constraint;
   110000         }
   110001       }
   110002     }else{
   110003       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   110004         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
   110005         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
   110006         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
   110007           rc = SQLITE_CONSTRAINT;
   110008           goto constraint;
   110009         }
   110010       }
   110011     }
   110012 
   110013     /* Figure out the rowid of the new row. */
   110014     if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
   110015       rc = newRowid(pRtree, &cell.iRowid);
   110016     }else{
   110017       cell.iRowid = sqlite3_value_int64(azData[2]);
   110018       sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
   110019       if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
   110020         sqlite3_reset(pRtree->pReadRowid);
   110021         rc = SQLITE_CONSTRAINT;
   110022         goto constraint;
   110023       }
   110024       rc = sqlite3_reset(pRtree->pReadRowid);
   110025     }
   110026 
   110027     if( rc==SQLITE_OK ){
   110028       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
   110029     }
   110030     if( rc==SQLITE_OK ){
   110031       int rc2;
   110032       pRtree->iReinsertHeight = -1;
   110033       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
   110034       rc2 = nodeRelease(pRtree, pLeaf);
   110035       if( rc==SQLITE_OK ){
   110036         rc = rc2;
   110037       }
   110038     }
   110039   }
   110040 
   110041 constraint:
   110042   rtreeRelease(pRtree);
   110043   return rc;
   110044 }
   110045 
   110046 /*
   110047 ** The xRename method for rtree module virtual tables.
   110048 */
   110049 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
   110050   Rtree *pRtree = (Rtree *)pVtab;
   110051   int rc = SQLITE_NOMEM;
   110052   char *zSql = sqlite3_mprintf(
   110053     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
   110054     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
   110055     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
   110056     , pRtree->zDb, pRtree->zName, zNewName
   110057     , pRtree->zDb, pRtree->zName, zNewName
   110058     , pRtree->zDb, pRtree->zName, zNewName
   110059   );
   110060   if( zSql ){
   110061     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
   110062     sqlite3_free(zSql);
   110063   }
   110064   return rc;
   110065 }
   110066 
   110067 static sqlite3_module rtreeModule = {
   110068   0,                         /* iVersion */
   110069   rtreeCreate,                /* xCreate - create a table */
   110070   rtreeConnect,               /* xConnect - connect to an existing table */
   110071   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
   110072   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
   110073   rtreeDestroy,               /* xDestroy - Drop a table */
   110074   rtreeOpen,                  /* xOpen - open a cursor */
   110075   rtreeClose,                 /* xClose - close a cursor */
   110076   rtreeFilter,                /* xFilter - configure scan constraints */
   110077   rtreeNext,                  /* xNext - advance a cursor */
   110078   rtreeEof,                   /* xEof */
   110079   rtreeColumn,                /* xColumn - read data */
   110080   rtreeRowid,                 /* xRowid - read data */
   110081   rtreeUpdate,                /* xUpdate - write data */
   110082   0,                          /* xBegin - begin transaction */
   110083   0,                          /* xSync - sync transaction */
   110084   0,                          /* xCommit - commit transaction */
   110085   0,                          /* xRollback - rollback transaction */
   110086   0,                          /* xFindFunction - function overloading */
   110087   rtreeRename                 /* xRename - rename the table */
   110088 };
   110089 
   110090 static int rtreeSqlInit(
   110091   Rtree *pRtree,
   110092   sqlite3 *db,
   110093   const char *zDb,
   110094   const char *zPrefix,
   110095   int isCreate
   110096 ){
   110097   int rc = SQLITE_OK;
   110098 
   110099   #define N_STATEMENT 9
   110100   static const char *azSql[N_STATEMENT] = {
   110101     /* Read and write the xxx_node table */
   110102     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
   110103     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
   110104     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
   110105 
   110106     /* Read and write the xxx_rowid table */
   110107     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
   110108     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
   110109     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
   110110 
   110111     /* Read and write the xxx_parent table */
   110112     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
   110113     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
   110114     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
   110115   };
   110116   sqlite3_stmt **appStmt[N_STATEMENT];
   110117   int i;
   110118 
   110119   pRtree->db = db;
   110120 
   110121   if( isCreate ){
   110122     char *zCreate = sqlite3_mprintf(
   110123 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
   110124 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
   110125 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
   110126 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
   110127       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
   110128     );
   110129     if( !zCreate ){
   110130       return SQLITE_NOMEM;
   110131     }
   110132     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
   110133     sqlite3_free(zCreate);
   110134     if( rc!=SQLITE_OK ){
   110135       return rc;
   110136     }
   110137   }
   110138 
   110139   appStmt[0] = &pRtree->pReadNode;
   110140   appStmt[1] = &pRtree->pWriteNode;
   110141   appStmt[2] = &pRtree->pDeleteNode;
   110142   appStmt[3] = &pRtree->pReadRowid;
   110143   appStmt[4] = &pRtree->pWriteRowid;
   110144   appStmt[5] = &pRtree->pDeleteRowid;
   110145   appStmt[6] = &pRtree->pReadParent;
   110146   appStmt[7] = &pRtree->pWriteParent;
   110147   appStmt[8] = &pRtree->pDeleteParent;
   110148 
   110149   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
   110150     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
   110151     if( zSql ){
   110152       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
   110153     }else{
   110154       rc = SQLITE_NOMEM;
   110155     }
   110156     sqlite3_free(zSql);
   110157   }
   110158 
   110159   return rc;
   110160 }
   110161 
   110162 /*
   110163 ** This routine queries database handle db for the page-size used by
   110164 ** database zDb. If successful, the page-size in bytes is written to
   110165 ** *piPageSize and SQLITE_OK returned. Otherwise, and an SQLite error
   110166 ** code is returned.
   110167 */
   110168 static int getPageSize(sqlite3 *db, const char *zDb, int *piPageSize){
   110169   int rc = SQLITE_NOMEM;
   110170   char *zSql;
   110171   sqlite3_stmt *pStmt = 0;
   110172 
   110173   zSql = sqlite3_mprintf("PRAGMA %Q.page_size", zDb);
   110174   if( !zSql ){
   110175     return SQLITE_NOMEM;
   110176   }
   110177 
   110178   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   110179   sqlite3_free(zSql);
   110180   if( rc!=SQLITE_OK ){
   110181     return rc;
   110182   }
   110183 
   110184   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   110185     *piPageSize = sqlite3_column_int(pStmt, 0);
   110186   }
   110187   return sqlite3_finalize(pStmt);
   110188 }
   110189 
   110190 /*
   110191 ** This function is the implementation of both the xConnect and xCreate
   110192 ** methods of the r-tree virtual table.
   110193 **
   110194 **   argv[0]   -> module name
   110195 **   argv[1]   -> database name
   110196 **   argv[2]   -> table name
   110197 **   argv[...] -> column names...
   110198 */
   110199 static int rtreeInit(
   110200   sqlite3 *db,                        /* Database connection */
   110201   void *pAux,                         /* One of the RTREE_COORD_* constants */
   110202   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
   110203   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
   110204   char **pzErr,                       /* OUT: Error message, if any */
   110205   int isCreate                        /* True for xCreate, false for xConnect */
   110206 ){
   110207   int rc = SQLITE_OK;
   110208   int iPageSize = 0;
   110209   Rtree *pRtree;
   110210   int nDb;              /* Length of string argv[1] */
   110211   int nName;            /* Length of string argv[2] */
   110212   int eCoordType = (int)pAux;
   110213 
   110214   const char *aErrMsg[] = {
   110215     0,                                                    /* 0 */
   110216     "Wrong number of columns for an rtree table",         /* 1 */
   110217     "Too few columns for an rtree table",                 /* 2 */
   110218     "Too many columns for an rtree table"                 /* 3 */
   110219   };
   110220 
   110221   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
   110222   if( aErrMsg[iErr] ){
   110223     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
   110224     return SQLITE_ERROR;
   110225   }
   110226 
   110227   rc = getPageSize(db, argv[1], &iPageSize);
   110228   if( rc!=SQLITE_OK ){
   110229     return rc;
   110230   }
   110231 
   110232   /* Allocate the sqlite3_vtab structure */
   110233   nDb = strlen(argv[1]);
   110234   nName = strlen(argv[2]);
   110235   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
   110236   if( !pRtree ){
   110237     return SQLITE_NOMEM;
   110238   }
   110239   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
   110240   pRtree->nBusy = 1;
   110241   pRtree->base.pModule = &rtreeModule;
   110242   pRtree->zDb = (char *)&pRtree[1];
   110243   pRtree->zName = &pRtree->zDb[nDb+1];
   110244   pRtree->nDim = (argc-4)/2;
   110245   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
   110246   pRtree->eCoordType = eCoordType;
   110247   memcpy(pRtree->zDb, argv[1], nDb);
   110248   memcpy(pRtree->zName, argv[2], nName);
   110249 
   110250   /* Figure out the node size to use. By default, use 64 bytes less than
   110251   ** the database page-size. This ensures that each node is stored on
   110252   ** a single database page.
   110253   **
   110254   ** If the databasd page-size is so large that more than RTREE_MAXCELLS
   110255   ** entries would fit in a single node, use a smaller node-size.
   110256   */
   110257   pRtree->iNodeSize = iPageSize-64;
   110258   if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
   110259     pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
   110260   }
   110261 
   110262   /* Create/Connect to the underlying relational database schema. If
   110263   ** that is successful, call sqlite3_declare_vtab() to configure
   110264   ** the r-tree table schema.
   110265   */
   110266   if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
   110267     *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   110268   }else{
   110269     char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
   110270     char *zTmp;
   110271     int ii;
   110272     for(ii=4; zSql && ii<argc; ii++){
   110273       zTmp = zSql;
   110274       zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
   110275       sqlite3_free(zTmp);
   110276     }
   110277     if( zSql ){
   110278       zTmp = zSql;
   110279       zSql = sqlite3_mprintf("%s);", zTmp);
   110280       sqlite3_free(zTmp);
   110281     }
   110282     if( !zSql ){
   110283       rc = SQLITE_NOMEM;
   110284     }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
   110285       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   110286     }
   110287     sqlite3_free(zSql);
   110288   }
   110289 
   110290   if( rc==SQLITE_OK ){
   110291     *ppVtab = (sqlite3_vtab *)pRtree;
   110292   }else{
   110293     rtreeRelease(pRtree);
   110294   }
   110295   return rc;
   110296 }
   110297 
   110298 
   110299 /*
   110300 ** Implementation of a scalar function that decodes r-tree nodes to
   110301 ** human readable strings. This can be used for debugging and analysis.
   110302 **
   110303 ** The scalar function takes two arguments, a blob of data containing
   110304 ** an r-tree node, and the number of dimensions the r-tree indexes.
   110305 ** For a two-dimensional r-tree structure called "rt", to deserialize
   110306 ** all nodes, a statement like:
   110307 **
   110308 **   SELECT rtreenode(2, data) FROM rt_node;
   110309 **
   110310 ** The human readable string takes the form of a Tcl list with one
   110311 ** entry for each cell in the r-tree node. Each entry is itself a
   110312 ** list, containing the 8-byte rowid/pageno followed by the
   110313 ** <num-dimension>*2 coordinates.
   110314 */
   110315 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   110316   char *zText = 0;
   110317   RtreeNode node;
   110318   Rtree tree;
   110319   int ii;
   110320 
   110321   memset(&node, 0, sizeof(RtreeNode));
   110322   memset(&tree, 0, sizeof(Rtree));
   110323   tree.nDim = sqlite3_value_int(apArg[0]);
   110324   tree.nBytesPerCell = 8 + 8 * tree.nDim;
   110325   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
   110326 
   110327   for(ii=0; ii<NCELL(&node); ii++){
   110328     char zCell[512];
   110329     int nCell = 0;
   110330     RtreeCell cell;
   110331     int jj;
   110332 
   110333     nodeGetCell(&tree, &node, ii, &cell);
   110334     sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
   110335     nCell = strlen(zCell);
   110336     for(jj=0; jj<tree.nDim*2; jj++){
   110337       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
   110338       nCell = strlen(zCell);
   110339     }
   110340 
   110341     if( zText ){
   110342       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
   110343       sqlite3_free(zText);
   110344       zText = zTextNew;
   110345     }else{
   110346       zText = sqlite3_mprintf("{%s}", zCell);
   110347     }
   110348   }
   110349 
   110350   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
   110351 }
   110352 
   110353 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   110354   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
   110355    || sqlite3_value_bytes(apArg[0])<2
   110356   ){
   110357     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
   110358   }else{
   110359     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
   110360     sqlite3_result_int(ctx, readInt16(zBlob));
   110361   }
   110362 }
   110363 
   110364 /*
   110365 ** Register the r-tree module with database handle db. This creates the
   110366 ** virtual table module "rtree" and the debugging/analysis scalar
   110367 ** function "rtreenode".
   110368 */
   110369 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
   110370   int rc = SQLITE_OK;
   110371 
   110372   if( rc==SQLITE_OK ){
   110373     int utf8 = SQLITE_UTF8;
   110374     rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
   110375   }
   110376   if( rc==SQLITE_OK ){
   110377     int utf8 = SQLITE_UTF8;
   110378     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
   110379   }
   110380   if( rc==SQLITE_OK ){
   110381     void *c = (void *)RTREE_COORD_REAL32;
   110382     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
   110383   }
   110384   if( rc==SQLITE_OK ){
   110385     void *c = (void *)RTREE_COORD_INT32;
   110386     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
   110387   }
   110388 
   110389   return rc;
   110390 }
   110391 
   110392 #if !SQLITE_CORE
   110393 SQLITE_API int sqlite3_extension_init(
   110394   sqlite3 *db,
   110395   char **pzErrMsg,
   110396   const sqlite3_api_routines *pApi
   110397 ){
   110398   SQLITE_EXTENSION_INIT2(pApi)
   110399   return sqlite3RtreeInit(db);
   110400 }
   110401 #endif
   110402 
   110403 #endif
   110404 
   110405 /************** End of rtree.c ***********************************************/
   110406 /************** Begin file icu.c *********************************************/
   110407 /*
   110408 ** 2007 May 6
   110409 **
   110410 ** The author disclaims copyright to this source code.  In place of
   110411 ** a legal notice, here is a blessing:
   110412 **
   110413 **    May you do good and not evil.
   110414 **    May you find forgiveness for yourself and forgive others.
   110415 **    May you share freely, never taking more than you give.
   110416 **
   110417 *************************************************************************
   110418 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
   110419 **
   110420 ** This file implements an integration between the ICU library
   110421 ** ("International Components for Unicode", an open-source library
   110422 ** for handling unicode data) and SQLite. The integration uses
   110423 ** ICU to provide the following to SQLite:
   110424 **
   110425 **   * An implementation of the SQL regexp() function (and hence REGEXP
   110426 **     operator) using the ICU uregex_XX() APIs.
   110427 **
   110428 **   * Implementations of the SQL scalar upper() and lower() functions
   110429 **     for case mapping.
   110430 **
   110431 **   * Integration of ICU and SQLite collation seqences.
   110432 **
   110433 **   * An implementation of the LIKE operator that uses ICU to
   110434 **     provide case-independent matching.
   110435 */
   110436 
   110437 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
   110438 
   110439 /* Include ICU headers */
   110440 #include <unicode/utypes.h>
   110441 #include <unicode/uregex.h>
   110442 #include <unicode/ustring.h>
   110443 #include <unicode/ucol.h>
   110444 
   110445 
   110446 #ifndef SQLITE_CORE
   110447   SQLITE_EXTENSION_INIT1
   110448 #else
   110449 #endif
   110450 
   110451 /*
   110452 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
   110453 ** operator.
   110454 */
   110455 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
   110456 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
   110457 #endif
   110458 
   110459 /*
   110460 ** Version of sqlite3_free() that is always a function, never a macro.
   110461 */
   110462 static void xFree(void *p){
   110463   sqlite3_free(p);
   110464 }
   110465 
   110466 /*
   110467 ** Compare two UTF-8 strings for equality where the first string is
   110468 ** a "LIKE" expression. Return true (1) if they are the same and
   110469 ** false (0) if they are different.
   110470 */
   110471 static int icuLikeCompare(
   110472   const uint8_t *zPattern,   /* LIKE pattern */
   110473   const uint8_t *zString,    /* The UTF-8 string to compare against */
   110474   const UChar32 uEsc         /* The escape character */
   110475 ){
   110476   static const int MATCH_ONE = (UChar32)'_';
   110477   static const int MATCH_ALL = (UChar32)'%';
   110478 
   110479   int iPattern = 0;       /* Current byte index in zPattern */
   110480   int iString = 0;        /* Current byte index in zString */
   110481 
   110482   int prevEscape = 0;     /* True if the previous character was uEsc */
   110483 
   110484   while( zPattern[iPattern]!=0 ){
   110485 
   110486     /* Read (and consume) the next character from the input pattern. */
   110487     UChar32 uPattern;
   110488     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
   110489     assert(uPattern!=0);
   110490 
   110491     /* There are now 4 possibilities:
   110492     **
   110493     **     1. uPattern is an unescaped match-all character "%",
   110494     **     2. uPattern is an unescaped match-one character "_",
   110495     **     3. uPattern is an unescaped escape character, or
   110496     **     4. uPattern is to be handled as an ordinary character
   110497     */
   110498     if( !prevEscape && uPattern==MATCH_ALL ){
   110499       /* Case 1. */
   110500       uint8_t c;
   110501 
   110502       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
   110503       ** MATCH_ALL. For each MATCH_ONE, skip one character in the
   110504       ** test string.
   110505       */
   110506       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
   110507         if( c==MATCH_ONE ){
   110508           if( zString[iString]==0 ) return 0;
   110509           U8_FWD_1_UNSAFE(zString, iString);
   110510         }
   110511         iPattern++;
   110512       }
   110513 
   110514       if( zPattern[iPattern]==0 ) return 1;
   110515 
   110516       while( zString[iString] ){
   110517         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
   110518           return 1;
   110519         }
   110520         U8_FWD_1_UNSAFE(zString, iString);
   110521       }
   110522       return 0;
   110523 
   110524     }else if( !prevEscape && uPattern==MATCH_ONE ){
   110525       /* Case 2. */
   110526       if( zString[iString]==0 ) return 0;
   110527       U8_FWD_1_UNSAFE(zString, iString);
   110528 
   110529     }else if( !prevEscape && uPattern==uEsc){
   110530       /* Case 3. */
   110531       prevEscape = 1;
   110532 
   110533     }else{
   110534       /* Case 4. */
   110535       UChar32 uString;
   110536       U8_NEXT_UNSAFE(zString, iString, uString);
   110537       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
   110538       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
   110539       if( uString!=uPattern ){
   110540         return 0;
   110541       }
   110542       prevEscape = 0;
   110543     }
   110544   }
   110545 
   110546   return zString[iString]==0;
   110547 }
   110548 
   110549 /*
   110550 ** Implementation of the like() SQL function.  This function implements
   110551 ** the build-in LIKE operator.  The first argument to the function is the
   110552 ** pattern and the second argument is the string.  So, the SQL statements:
   110553 **
   110554 **       A LIKE B
   110555 **
   110556 ** is implemented as like(B, A). If there is an escape character E,
   110557 **
   110558 **       A LIKE B ESCAPE E
   110559 **
   110560 ** is mapped to like(B, A, E).
   110561 */
   110562 static void icuLikeFunc(
   110563   sqlite3_context *context,
   110564   int argc,
   110565   sqlite3_value **argv
   110566 ){
   110567   const unsigned char *zA = sqlite3_value_text(argv[0]);
   110568   const unsigned char *zB = sqlite3_value_text(argv[1]);
   110569   UChar32 uEsc = 0;
   110570 
   110571   /* Limit the length of the LIKE or GLOB pattern to avoid problems
   110572   ** of deep recursion and N*N behavior in patternCompare().
   110573   */
   110574   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
   110575     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
   110576     return;
   110577   }
   110578 
   110579 
   110580   if( argc==3 ){
   110581     /* The escape character string must consist of a single UTF-8 character.
   110582     ** Otherwise, return an error.
   110583     */
   110584     int nE= sqlite3_value_bytes(argv[2]);
   110585     const unsigned char *zE = sqlite3_value_text(argv[2]);
   110586     int i = 0;
   110587     if( zE==0 ) return;
   110588     U8_NEXT(zE, i, nE, uEsc);
   110589     if( i!=nE){
   110590       sqlite3_result_error(context,
   110591           "ESCAPE expression must be a single character", -1);
   110592       return;
   110593     }
   110594   }
   110595 
   110596   if( zA && zB ){
   110597     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
   110598   }
   110599 }
   110600 
   110601 /*
   110602 ** This function is called when an ICU function called from within
   110603 ** the implementation of an SQL scalar function returns an error.
   110604 **
   110605 ** The scalar function context passed as the first argument is
   110606 ** loaded with an error message based on the following two args.
   110607 */
   110608 static void icuFunctionError(
   110609   sqlite3_context *pCtx,       /* SQLite scalar function context */
   110610   const char *zName,           /* Name of ICU function that failed */
   110611   UErrorCode e                 /* Error code returned by ICU function */
   110612 ){
   110613   char zBuf[128];
   110614   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
   110615   zBuf[127] = '\0';
   110616   sqlite3_result_error(pCtx, zBuf, -1);
   110617 }
   110618 
   110619 /*
   110620 ** Function to delete compiled regexp objects. Registered as
   110621 ** a destructor function with sqlite3_set_auxdata().
   110622 */
   110623 static void icuRegexpDelete(void *p){
   110624   URegularExpression *pExpr = (URegularExpression *)p;
   110625   uregex_close(pExpr);
   110626 }
   110627 
   110628 /*
   110629 ** Implementation of SQLite REGEXP operator. This scalar function takes
   110630 ** two arguments. The first is a regular expression pattern to compile
   110631 ** the second is a string to match against that pattern. If either
   110632 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
   110633 ** is 1 if the string matches the pattern, or 0 otherwise.
   110634 **
   110635 ** SQLite maps the regexp() function to the regexp() operator such
   110636 ** that the following two are equivalent:
   110637 **
   110638 **     zString REGEXP zPattern
   110639 **     regexp(zPattern, zString)
   110640 **
   110641 ** Uses the following ICU regexp APIs:
   110642 **
   110643 **     uregex_open()
   110644 **     uregex_matches()
   110645 **     uregex_close()
   110646 */
   110647 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   110648   UErrorCode status = U_ZERO_ERROR;
   110649   URegularExpression *pExpr;
   110650   UBool res;
   110651   const UChar *zString = sqlite3_value_text16(apArg[1]);
   110652 
   110653   /* If the left hand side of the regexp operator is NULL,
   110654   ** then the result is also NULL.
   110655   */
   110656   if( !zString ){
   110657     return;
   110658   }
   110659 
   110660   pExpr = sqlite3_get_auxdata(p, 0);
   110661   if( !pExpr ){
   110662     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
   110663     if( !zPattern ){
   110664       return;
   110665     }
   110666     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
   110667 
   110668     if( U_SUCCESS(status) ){
   110669       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
   110670     }else{
   110671       assert(!pExpr);
   110672       icuFunctionError(p, "uregex_open", status);
   110673       return;
   110674     }
   110675   }
   110676 
   110677   /* Configure the text that the regular expression operates on. */
   110678   uregex_setText(pExpr, zString, -1, &status);
   110679   if( !U_SUCCESS(status) ){
   110680     icuFunctionError(p, "uregex_setText", status);
   110681     return;
   110682   }
   110683 
   110684   /* Attempt the match */
   110685   res = uregex_matches(pExpr, 0, &status);
   110686   if( !U_SUCCESS(status) ){
   110687     icuFunctionError(p, "uregex_matches", status);
   110688     return;
   110689   }
   110690 
   110691   /* Set the text that the regular expression operates on to a NULL
   110692   ** pointer. This is not really necessary, but it is tidier than
   110693   ** leaving the regular expression object configured with an invalid
   110694   ** pointer after this function returns.
   110695   */
   110696   uregex_setText(pExpr, 0, 0, &status);
   110697 
   110698   /* Return 1 or 0. */
   110699   sqlite3_result_int(p, res ? 1 : 0);
   110700 }
   110701 
   110702 /*
   110703 ** Implementations of scalar functions for case mapping - upper() and
   110704 ** lower(). Function upper() converts its input to upper-case (ABC).
   110705 ** Function lower() converts to lower-case (abc).
   110706 **
   110707 ** ICU provides two types of case mapping, "general" case mapping and
   110708 ** "language specific". Refer to ICU documentation for the differences
   110709 ** between the two.
   110710 **
   110711 ** To utilise "general" case mapping, the upper() or lower() scalar
   110712 ** functions are invoked with one argument:
   110713 **
   110714 **     upper('ABC') -> 'abc'
   110715 **     lower('abc') -> 'ABC'
   110716 **
   110717 ** To access ICU "language specific" case mapping, upper() or lower()
   110718 ** should be invoked with two arguments. The second argument is the name
   110719 ** of the locale to use. Passing an empty string ("") or SQL NULL value
   110720 ** as the second argument is the same as invoking the 1 argument version
   110721 ** of upper() or lower().
   110722 **
   110723 **     lower('I', 'en_us') -> 'i'
   110724 **     lower('I', 'tr_tr') -> '' (small dotless i)
   110725 **
   110726 ** http://www.icu-project.org/userguide/posix.html#case_mappings
   110727 */
   110728 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   110729   const UChar *zInput;
   110730   UChar *zOutput;
   110731   int nInput;
   110732   int nOutput;
   110733 
   110734   UErrorCode status = U_ZERO_ERROR;
   110735   const char *zLocale = 0;
   110736 
   110737   assert(nArg==1 || nArg==2);
   110738   if( nArg==2 ){
   110739     zLocale = (const char *)sqlite3_value_text(apArg[1]);
   110740   }
   110741 
   110742   zInput = sqlite3_value_text16(apArg[0]);
   110743   if( !zInput ){
   110744     return;
   110745   }
   110746   nInput = sqlite3_value_bytes16(apArg[0]);
   110747 
   110748   nOutput = nInput * 2 + 2;
   110749   zOutput = sqlite3_malloc(nOutput);
   110750   if( !zOutput ){
   110751     return;
   110752   }
   110753 
   110754   if( sqlite3_user_data(p) ){
   110755     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
   110756   }else{
   110757     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
   110758   }
   110759 
   110760   if( !U_SUCCESS(status) ){
   110761     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
   110762     return;
   110763   }
   110764 
   110765   sqlite3_result_text16(p, zOutput, -1, xFree);
   110766 }
   110767 
   110768 /*
   110769 ** Collation sequence destructor function. The pCtx argument points to
   110770 ** a UCollator structure previously allocated using ucol_open().
   110771 */
   110772 static void icuCollationDel(void *pCtx){
   110773   UCollator *p = (UCollator *)pCtx;
   110774   ucol_close(p);
   110775 }
   110776 
   110777 /*
   110778 ** Collation sequence comparison function. The pCtx argument points to
   110779 ** a UCollator structure previously allocated using ucol_open().
   110780 */
   110781 static int icuCollationColl(
   110782   void *pCtx,
   110783   int nLeft,
   110784   const void *zLeft,
   110785   int nRight,
   110786   const void *zRight
   110787 ){
   110788   UCollationResult res;
   110789   UCollator *p = (UCollator *)pCtx;
   110790   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
   110791   switch( res ){
   110792     case UCOL_LESS:    return -1;
   110793     case UCOL_GREATER: return +1;
   110794     case UCOL_EQUAL:   return 0;
   110795   }
   110796   assert(!"Unexpected return value from ucol_strcoll()");
   110797   return 0;
   110798 }
   110799 
   110800 /*
   110801 ** Implementation of the scalar function icu_load_collation().
   110802 **
   110803 ** This scalar function is used to add ICU collation based collation
   110804 ** types to an SQLite database connection. It is intended to be called
   110805 ** as follows:
   110806 **
   110807 **     SELECT icu_load_collation(<locale>, <collation-name>);
   110808 **
   110809 ** Where <locale> is a string containing an ICU locale identifier (i.e.
   110810 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
   110811 ** collation sequence to create.
   110812 */
   110813 static void icuLoadCollation(
   110814   sqlite3_context *p,
   110815   int nArg,
   110816   sqlite3_value **apArg
   110817 ){
   110818   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
   110819   UErrorCode status = U_ZERO_ERROR;
   110820   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
   110821   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
   110822   UCollator *pUCollator;    /* ICU library collation object */
   110823   int rc;                   /* Return code from sqlite3_create_collation_x() */
   110824 
   110825   assert(nArg==2);
   110826   zLocale = (const char *)sqlite3_value_text(apArg[0]);
   110827   zName = (const char *)sqlite3_value_text(apArg[1]);
   110828 
   110829   if( !zLocale || !zName ){
   110830     return;
   110831   }
   110832 
   110833   pUCollator = ucol_open(zLocale, &status);
   110834   if( !U_SUCCESS(status) ){
   110835     icuFunctionError(p, "ucol_open", status);
   110836     return;
   110837   }
   110838   assert(p);
   110839 
   110840   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
   110841       icuCollationColl, icuCollationDel
   110842   );
   110843   if( rc!=SQLITE_OK ){
   110844     ucol_close(pUCollator);
   110845     sqlite3_result_error(p, "Error registering collation function", -1);
   110846   }
   110847 }
   110848 
   110849 /*
   110850 ** Register the ICU extension functions with database db.
   110851 */
   110852 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
   110853   struct IcuScalar {
   110854     const char *zName;                        /* Function name */
   110855     int nArg;                                 /* Number of arguments */
   110856     int enc;                                  /* Optimal text encoding */
   110857     void *pContext;                           /* sqlite3_user_data() context */
   110858     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   110859   } scalars[] = {
   110860     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
   110861 
   110862     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
   110863     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
   110864     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
   110865     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
   110866 
   110867     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
   110868     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
   110869     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
   110870     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
   110871 
   110872     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
   110873     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
   110874 
   110875     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
   110876   };
   110877 
   110878   int rc = SQLITE_OK;
   110879   int i;
   110880 
   110881   for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
   110882     struct IcuScalar *p = &scalars[i];
   110883     rc = sqlite3_create_function(
   110884         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
   110885     );
   110886   }
   110887 
   110888   return rc;
   110889 }
   110890 
   110891 #if !SQLITE_CORE
   110892 SQLITE_API int sqlite3_extension_init(
   110893   sqlite3 *db,
   110894   char **pzErrMsg,
   110895   const sqlite3_api_routines *pApi
   110896 ){
   110897   SQLITE_EXTENSION_INIT2(pApi)
   110898   return sqlite3IcuInit(db);
   110899 }
   110900 #endif
   110901 
   110902 #endif
   110903 
   110904 /************** End of icu.c *************************************************/
   110905 /************** Begin file fts3_icu.c ****************************************/
   110906 /*
   110907 ** 2007 June 22
   110908 **
   110909 ** The author disclaims copyright to this source code.  In place of
   110910 ** a legal notice, here is a blessing:
   110911 **
   110912 **    May you do good and not evil.
   110913 **    May you find forgiveness for yourself and forgive others.
   110914 **    May you share freely, never taking more than you give.
   110915 **
   110916 *************************************************************************
   110917 ** This file implements a tokenizer for fts3 based on the ICU library.
   110918 **
   110919 ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
   110920 */
   110921 
   110922 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   110923 #ifdef SQLITE_ENABLE_ICU
   110924 
   110925 
   110926 #include <unicode/ubrk.h>
   110927 #include <unicode/utf16.h>
   110928 
   110929 typedef struct IcuTokenizer IcuTokenizer;
   110930 typedef struct IcuCursor IcuCursor;
   110931 
   110932 struct IcuTokenizer {
   110933   sqlite3_tokenizer base;
   110934   char *zLocale;
   110935 };
   110936 
   110937 struct IcuCursor {
   110938   sqlite3_tokenizer_cursor base;
   110939 
   110940   UBreakIterator *pIter;      /* ICU break-iterator object */
   110941   int nChar;                  /* Number of UChar elements in pInput */
   110942   UChar *aChar;               /* Copy of input using utf-16 encoding */
   110943   int *aOffset;               /* Offsets of each character in utf-8 input */
   110944 
   110945   int nBuffer;
   110946   char *zBuffer;
   110947 
   110948   int iToken;
   110949 };
   110950 
   110951 /*
   110952 ** Create a new tokenizer instance.
   110953 */
   110954 static int icuCreate(
   110955   int argc,                            /* Number of entries in argv[] */
   110956   const char * const *argv,            /* Tokenizer creation arguments */
   110957   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
   110958 ){
   110959   IcuTokenizer *p;
   110960   int n = 0;
   110961 
   110962   if( argc>0 ){
   110963     n = strlen(argv[0])+1;
   110964   }
   110965   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
   110966   if( !p ){
   110967     return SQLITE_NOMEM;
   110968   }
   110969   memset(p, 0, sizeof(IcuTokenizer));
   110970 
   110971   if( n ){
   110972     p->zLocale = (char *)&p[1];
   110973     memcpy(p->zLocale, argv[0], n);
   110974   }
   110975 
   110976   *ppTokenizer = (sqlite3_tokenizer *)p;
   110977 
   110978   return SQLITE_OK;
   110979 }
   110980 
   110981 /*
   110982 ** Destroy a tokenizer
   110983 */
   110984 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
   110985   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
   110986   sqlite3_free(p);
   110987   return SQLITE_OK;
   110988 }
   110989 
   110990 /*
   110991 ** Prepare to begin tokenizing a particular string.  The input
   110992 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   110993 ** used to incrementally tokenize this string is returned in
   110994 ** *ppCursor.
   110995 */
   110996 static int icuOpen(
   110997   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   110998   const char *zInput,                    /* Input string */
   110999   int nInput,                            /* Length of zInput in bytes */
   111000   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   111001 ){
   111002   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
   111003   IcuCursor *pCsr;
   111004 
   111005   const int32_t opt = U_FOLD_CASE_DEFAULT;
   111006   UErrorCode status = U_ZERO_ERROR;
   111007   int nChar;
   111008 
   111009   UChar32 c;
   111010   int iInput = 0;
   111011   int iOut = 0;
   111012 
   111013   *ppCursor = 0;
   111014 
   111015   if( nInput<0 ){
   111016     nInput = strlen(zInput);
   111017   }
   111018   nChar = nInput+1;
   111019   pCsr = (IcuCursor *)sqlite3_malloc(
   111020       sizeof(IcuCursor) +                /* IcuCursor */
   111021       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
   111022       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
   111023   );
   111024   if( !pCsr ){
   111025     return SQLITE_NOMEM;
   111026   }
   111027   memset(pCsr, 0, sizeof(IcuCursor));
   111028   pCsr->aChar = (UChar *)&pCsr[1];
   111029   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
   111030 
   111031   pCsr->aOffset[iOut] = iInput;
   111032   U8_NEXT(zInput, iInput, nInput, c);
   111033   while( c>0 ){
   111034     int isError = 0;
   111035     c = u_foldCase(c, opt);
   111036     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
   111037     if( isError ){
   111038       sqlite3_free(pCsr);
   111039       return SQLITE_ERROR;
   111040     }
   111041     pCsr->aOffset[iOut] = iInput;
   111042 
   111043     if( iInput<nInput ){
   111044       U8_NEXT(zInput, iInput, nInput, c);
   111045     }else{
   111046       c = 0;
   111047     }
   111048   }
   111049 
   111050   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
   111051   if( !U_SUCCESS(status) ){
   111052     sqlite3_free(pCsr);
   111053     return SQLITE_ERROR;
   111054   }
   111055   pCsr->nChar = iOut;
   111056 
   111057   ubrk_first(pCsr->pIter);
   111058   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
   111059   return SQLITE_OK;
   111060 }
   111061 
   111062 /*
   111063 ** Close a tokenization cursor previously opened by a call to icuOpen().
   111064 */
   111065 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
   111066   IcuCursor *pCsr = (IcuCursor *)pCursor;
   111067   ubrk_close(pCsr->pIter);
   111068   sqlite3_free(pCsr->zBuffer);
   111069   sqlite3_free(pCsr);
   111070   return SQLITE_OK;
   111071 }
   111072 
   111073 /*
   111074 ** Extract the next token from a tokenization cursor.
   111075 */
   111076 static int icuNext(
   111077   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
   111078   const char **ppToken,               /* OUT: *ppToken is the token text */
   111079   int *pnBytes,                       /* OUT: Number of bytes in token */
   111080   int *piStartOffset,                 /* OUT: Starting offset of token */
   111081   int *piEndOffset,                   /* OUT: Ending offset of token */
   111082   int *piPosition                     /* OUT: Position integer of token */
   111083 ){
   111084   IcuCursor *pCsr = (IcuCursor *)pCursor;
   111085 
   111086   int iStart = 0;
   111087   int iEnd = 0;
   111088   int nByte = 0;
   111089 
   111090   while( iStart==iEnd ){
   111091     UChar32 c;
   111092 
   111093     iStart = ubrk_current(pCsr->pIter);
   111094     iEnd = ubrk_next(pCsr->pIter);
   111095     if( iEnd==UBRK_DONE ){
   111096       return SQLITE_DONE;
   111097     }
   111098 
   111099     while( iStart<iEnd ){
   111100       int iWhite = iStart;
   111101       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
   111102       if( u_isspace(c) ){
   111103         iStart = iWhite;
   111104       }else{
   111105         break;
   111106       }
   111107     }
   111108     assert(iStart<=iEnd);
   111109   }
   111110 
   111111   do {
   111112     UErrorCode status = U_ZERO_ERROR;
   111113     if( nByte ){
   111114       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
   111115       if( !zNew ){
   111116         return SQLITE_NOMEM;
   111117       }
   111118       pCsr->zBuffer = zNew;
   111119       pCsr->nBuffer = nByte;
   111120     }
   111121 
   111122     u_strToUTF8(
   111123         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
   111124         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
   111125         &status                                  /* Output success/failure */
   111126     );
   111127   } while( nByte>pCsr->nBuffer );
   111128 
   111129   *ppToken = pCsr->zBuffer;
   111130   *pnBytes = nByte;
   111131   *piStartOffset = pCsr->aOffset[iStart];
   111132   *piEndOffset = pCsr->aOffset[iEnd];
   111133   *piPosition = pCsr->iToken++;
   111134 
   111135   return SQLITE_OK;
   111136 }
   111137 
   111138 /*
   111139 ** The set of routines that implement the simple tokenizer
   111140 */
   111141 static const sqlite3_tokenizer_module icuTokenizerModule = {
   111142   0,                           /* iVersion */
   111143   icuCreate,                   /* xCreate  */
   111144   icuDestroy,                  /* xCreate  */
   111145   icuOpen,                     /* xOpen    */
   111146   icuClose,                    /* xClose   */
   111147   icuNext,                     /* xNext    */
   111148 };
   111149 
   111150 /*
   111151 ** Set *ppModule to point at the implementation of the ICU tokenizer.
   111152 */
   111153 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
   111154   sqlite3_tokenizer_module const**ppModule
   111155 ){
   111156   *ppModule = &icuTokenizerModule;
   111157 }
   111158 
   111159 #endif /* defined(SQLITE_ENABLE_ICU) */
   111160 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   111161 
   111162 /************** End of fts3_icu.c ********************************************/
   111163 // Begin Android Add
   111164 /*
   111165 ** Change the default behavior of BEGIN to IMMEDIATE instead of DEFERRED.
   111166 */
   111167 SQLITE_API int sqlite3_set_transaction_default_immediate(sqlite3* db, int immediate){
   111168   sqlite3_mutex_enter(db->mutex);
   111169     if( immediate ){
   111170       db->flags|=SQLITE_BeginImmediate;
   111171     }else{
   111172       db->flags&=~SQLITE_BeginImmediate;
   111173     }
   111174     sqlite3_mutex_leave(db->mutex);
   111175     return SQLITE_OK;
   111176 }
   111177 // End Android Add
   111178